index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
7,468
pathlib
with_stem
Return a new path with the stem changed.
def with_stem(self, stem): """Return a new path with the stem changed.""" return self.with_name(stem + self.suffix)
(self, stem)
7,469
pathlib
with_suffix
Return a new path with the file suffix changed. If the path has no suffix, add given suffix. If the given suffix is an empty string, remove the suffix from the path.
def with_suffix(self, suffix): """Return a new path with the file suffix changed. If the path has no suffix, add given suffix. If the given suffix is an empty string, remove the suffix from the path. """ f = self._flavour if f.sep in suffix or f.altsep and f.altsep in suffix: raise ValueError("Invalid suffix %r" % (suffix,)) if suffix and not suffix.startswith('.') or suffix == '.': raise ValueError("Invalid suffix %r" % (suffix)) name = self.name if not name: raise ValueError("%r has an empty name" % (self,)) old_suffix = self.suffix if not old_suffix: name = name + suffix else: name = name[:-len(old_suffix)] + suffix return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
(self, suffix)
7,470
pathlib
write_bytes
Open the file in bytes mode, write to it, and close the file.
def write_bytes(self, data): """ Open the file in bytes mode, write to it, and close the file. """ # type-check for the buffer interface before truncating the file view = memoryview(data) with self.open(mode='wb') as f: return f.write(view)
(self, data)
7,471
pathlib
write_text
Open the file in text mode, write to it, and close the file.
def write_text(self, data, encoding=None, errors=None, newline=None): """ Open the file in text mode, write to it, and close the file. """ if not isinstance(data, str): raise TypeError('data must be str, not %s' % data.__class__.__name__) encoding = io.text_encoding(encoding) with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: return f.write(data)
(self, data, encoding=None, errors=None, newline=None)
7,472
gruut_lang_de
get_lang_dir
Get directory with language resources
def get_lang_dir() -> Path: """Get directory with language resources""" return _DIR
() -> pathlib.Path
7,473
orjson
Fragment
null
from orjson import Fragment
null
7,474
orjson
JSONDecodeError
null
from orjson import JSONDecodeError
(msg, doc, pos)
7,475
json.decoder
__init__
null
def __init__(self, msg, doc, pos): lineno = doc.count('\n', 0, pos) + 1 colno = pos - doc.rfind('\n', 0, pos) errmsg = '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) ValueError.__init__(self, errmsg) self.msg = msg self.doc = doc self.pos = pos self.lineno = lineno self.colno = colno
(self, msg, doc, pos)
7,476
json.decoder
__reduce__
null
def __reduce__(self): return self.__class__, (self.msg, self.doc, self.pos)
(self)
7,477
builtins
TypeError
Inappropriate argument type.
from builtins import TypeError
null
7,480
example_package_anellenson
add_one
null
def add_one(number): return number + 1
(number)
7,481
eth_account.account
Account
The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node.
class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
()
7,482
eth_account.account
_parsePrivateKey
Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey`
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, key)
7,483
eth_account.account
_recover_hash
null
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, message_hash: eth_typing.evm.Hash32, vrs: Optional[Tuple[~VRS, ~VRS, ~VRS]] = None, signature: bytes = None) -> eth_typing.evm.ChecksumAddress
7,485
eth_account.account
create
Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, extra_entropy='')
7,486
eth_account.account
create_with_mnemonic
Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, passphrase: str = '', num_words: int = 12, language: str = 'english', account_path: str = "m/44'/60'/0'/0/0") -> Tuple[eth_account.signers.local.LocalAccount, str]
7,487
eth_account.account
decrypt
Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364')
@staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes))
(keyfile_json, password)
7,488
eth_account.account
from_key
Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, private_key)
7,489
eth_account.account
from_mnemonic
Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only.
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, mnemonic: str, passphrase: str = '', account_path: str = "m/44'/60'/0'/0/0") -> eth_account.signers.local.LocalAccount
7,490
eth_account.account
recover_message
Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, signable_message: eth_account.messages.SignableMessage, vrs: Optional[Tuple[~VRS, ~VRS, ~VRS]] = None, signature: bytes = None) -> eth_typing.evm.ChecksumAddress
7,491
eth_account.account
recover_transaction
Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23'
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, serialized_transaction)
7,492
eth_account.account
set_key_backend
Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_
def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend)
(self, backend)
7,493
eth_account.account
signHash
Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, message_hash, private_key)
7,494
eth_account.account
sign_message
Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, signable_message: eth_account.messages.SignableMessage, private_key: Union[bytes, eth_typing.encoding.HexStr, int, eth_keys.datatypes.PrivateKey]) -> eth_account.datastructures.SignedMessage
7,495
eth_account.account
sign_transaction
Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, transaction_dict, private_key, blobs=None)
7,496
eth_account.account
sign_typed_data
Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, private_key: Union[bytes, eth_typing.encoding.HexStr, int, eth_keys.datatypes.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None) -> eth_account.datastructures.SignedMessage
7,497
eth_account.account
unsafe_sign_hash
Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage
from collections.abc import ( Mapping, ) import json import os from typing import ( Any, Dict, Optional, Tuple, TypeVar, Union, cast, ) import warnings from eth_keyfile import ( create_keyfile_json, decode_keyfile_json, ) from eth_keys import ( KeyAPI, keys, ) from eth_keys.exceptions import ( ValidationError, ) from eth_typing import ( ChecksumAddress, Hash32, HexStr, ) from eth_utils.curried import ( combomethod, hexstr_if_str, is_dict, keccak, text_if_str, to_bytes, to_int, ) from eth_utils.toolz import ( dissoc, ) from hexbytes import ( HexBytes, ) from eth_account._utils.legacy_transactions import ( Transaction, vrs_from, ) from eth_account._utils.signing import ( hash_of_signed_transaction, sign_message_hash, sign_transaction_dict, to_standard_signature_bytes, to_standard_v, ) from eth_account.datastructures import ( SignedMessage, SignedTransaction, ) from eth_account.hdaccount import ( ETHEREUM_DEFAULT_PATH, generate_mnemonic, key_from_seed, seed_from_mnemonic, ) from eth_account.messages import ( SignableMessage, _hash_eip191_message, encode_typed_data, ) from eth_account.signers.local import ( LocalAccount, ) from eth_account.typed_transactions import ( TypedTransaction, ) VRS = TypeVar("VRS", bytes, HexStr, int) class Account: """ The primary entry point for working with Ethereum private keys. It does **not** require a connection to an Ethereum node. """ _keys = keys _default_kdf = os.getenv("ETH_ACCOUNT_KDF", "scrypt") # Enable unaudited features (off by default) _use_unaudited_hdwallet_features = False @classmethod def enable_unaudited_hdwallet_features(cls): """ Use this flag to enable unaudited HD Wallet features. """ cls._use_unaudited_hdwallet_features = True @combomethod def create(self, extra_entropy=""): r""" Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`. :param extra_entropy: Add extra randomness to whatever randomness your OS can provide :type extra_entropy: str or bytes or int :returns: an object with private key and convenience methods .. code-block:: python >>> from eth_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). # They correspond to the same-named methods in Account.* # but without the private key argument """ extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) return self.from_key(key_bytes) @staticmethod def decrypt(keyfile_json, password): """ Decrypts a private key. The key may have been encrypted using an Ethereum client or :meth:`~Account.encrypt`. :param keyfile_json: The encrypted key :type keyfile_json: dict or str :param str password: The password that was used to encrypt the key :returns: the raw private key :rtype: ~hexbytes.main.HexBytes .. doctest:: python >>> encrypted = { ... 'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', ... 'crypto': {'cipher': 'aes-128-ctr', ... 'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'}, ... 'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be', ... 'kdf': 'scrypt', ... 'kdfparams': {}, ... 'kdfparams': {'dklen': 32, ... 'n': 262144, ... 'p': 8, ... 'r': 1, ... 'salt': 'd3c9a9945000fcb6c9df0f854266d573'}, ... 'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'}, ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', ... 'version': 3} >>> Account.decrypt(encrypted, 'password') HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') """ # noqa: E501 if isinstance(keyfile_json, str): keyfile = json.loads(keyfile_json) elif is_dict(keyfile_json): keyfile = keyfile_json else: raise TypeError( "The keyfile should be supplied as a JSON string, or a dictionary." ) password_bytes = text_if_str(to_bytes, password) return HexBytes(decode_keyfile_json(keyfile, password_bytes)) @classmethod def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639D2D17A3F753ce7d93fa0b9aB12E', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 1, 'r': 8, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json( key_bytes, password_bytes, kdf=kdf, iterations=iterations ) @combomethod def from_key(self, private_key): r""" Returns a convenient object for working with the given private key. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct.key HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument """ key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def from_mnemonic( self, mnemonic: str, passphrase: str = "", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> LocalAccount: """ Generate an account from a mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon :param str mnemonic: space-separated list of BIP39 mnemonic seed words :param str passphrase: Optional passphrase used to encrypt the mnemonic :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :return: object with methods for signing and encrypting :rtype: LocalAccount .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct = Account.from_mnemonic( ... "coral allow abandon recipe top tray caught video climb similar " ... "prepare bracket antenna rubber announce gauge volume " ... "hub hood burden skill immense add acid") >>> acct.address '0x9AdA5dAD14d925f4df1378409731a9B71Bc8569d' # These methods are also available: sign_message(), sign_transaction(), # encrypt(). They correspond to the same-named methods in Account.* # but without the private key argument Or, generate multiple accounts from a mnemonic. >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> iterator = 0 >>> for i in range(10): ... acct = Account.from_mnemonic( ... "health embark april buyer eternal leopard " ... "want before nominee head thing tackle", ... account_path=f"m/44'/60'/0'/0/{iterator}") ... iterator = iterator + 1 ... acct.address '0x61Cc15522D06983Ac7aADe23f9d5433d38e78195' '0x1240460F6E370f28079E5F9B52f9DcB759F051b7' '0xd30dC9f996539826C646Eb48bb45F6ee1D1474af' '0x47e64beb58c9A469c5eD086aD231940676b44e7C' '0x6D39032ffEF9987988a069F52EFe4d95D0770555' '0x3836A6530D1889853b047799Ecd8827255072e77' '0xed5490dEfF8d8FfAe45cb4066C3daC7C6BFF6a22' '0xf04F9Ff322799253bcC6B12762AD127570a092c5' '0x900F7fa9fbe85BB25b6cdB94Da24D807f7feb213' '0xa248e118b0D19010387b1B768686cd9B473FA137' .. CAUTION:: For the love of Bob please do not use this mnemonic, it is for testing purposes only. """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) seed = seed_from_mnemonic(mnemonic, passphrase) private_key = key_from_seed(seed, account_path) key = self._parsePrivateKey(private_key) return LocalAccount(key, self) @combomethod def create_with_mnemonic( self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = ETHEREUM_DEFAULT_PATH, ) -> Tuple[LocalAccount, str]: r""" Create a new private key and related mnemonic. .. CAUTION:: This feature is experimental, unaudited, and likely to change soon Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`, alongside the mnemonic that can used to regenerate it using any BIP39-compatible wallet. :param str passphrase: Extra passphrase to encrypt the seed phrase :param int num_words: Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24]. :param str language: Language to use for BIP39 mnemonic seed phrase. :param str account_path: Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation. :returns: A tuple consisting of an object with private key and convenience methods, and the mnemonic seed phrase that can be used to restore the account. :rtype: (LocalAccount, str) .. doctest:: python >>> from eth_account import Account >>> Account.enable_unaudited_hdwallet_features() >>> acct, mnemonic = Account.create_with_mnemonic() >>> acct.address # doctest: +SKIP '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> acct == Account.from_mnemonic(mnemonic) True # These methods are also available: # sign_message(), sign_transaction(), encrypt() # They correspond to the same-named methods in Account.* # but without the private key argument """ if not self._use_unaudited_hdwallet_features: raise AttributeError( "The use of the Mnemonic features of Account is disabled by " "default until its API stabilizes. To use these features, please " "enable them by running `Account.enable_unaudited_hdwallet_features()` " "and try again." ) mnemonic = generate_mnemonic(num_words, language) return self.from_mnemonic(mnemonic, passphrase, account_path), mnemonic @combomethod def recover_message( self, signable_message: SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: r""" Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature :param signable_message: the message that was signed :param vrs: the three pieces generated by an elliptic curve signature :type vrs: tuple(v, r, s), each element is hex str, bytes or int :param signature: signature bytes concatenated as r+s+v :type signature: hex str or bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> from eth_account.messages import encode_defunct >>> from eth_account import Account >>> message = encode_defunct(text="I♥SF") >>> vrs = ( ... 28, ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # All of these recover calls are equivalent: # variations on vrs >>> vrs = ( ... '0x1c', ... '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', ... '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> vrs = ( ... 0x1c, ... 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3, ... 0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce) >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> vrs = ( ... b'\x1c', ... b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3', ... b'>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce') >>> Account.recover_message(message, vrs=vrs) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' # variations on signature >>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> signature = b'\xe6\xca\x9b\xbaX\xc8\x86\x11\xfa\xd6jl\xe8\xf9\x96\x90\x81\x95Y8\x07\xc4\xb3\x8b\xd5(\xd2\xcf\xf0\x9dN\xb3>[\xfb\xbfM>9\xb1\xa2\xfd\x81jv\x80\xc1\x9e\xbe\xba\xf3\xa1A\xb29\x93J\xd4<\xb3?\xce\xc8\xce\x1c' >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' >>> # Caution about this approach: likely problems if there are leading 0s >>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c >>> Account.recover_message(message, signature=signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(ChecksumAddress, self._recover_hash(message_hash, vrs, signature)) @combomethod def _recover_hash( self, message_hash: Hash32, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: bytes = None, ) -> ChecksumAddress: hash_bytes = HexBytes(message_hash) if len(hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature( signature_bytes=signature_bytes_standard ) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return cast(ChecksumAddress, pubkey.to_checksum_address()) @combomethod def recover_transaction(self, serialized_transaction): """ Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & checksummed :rtype: str .. doctest:: python >>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' >>> Account.recover_transaction(raw_transaction) '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23' """ # noqa: E501 txn_bytes = HexBytes(serialized_transaction) if len(txn_bytes) > 0 and txn_bytes[0] <= 0x7F: # We are dealing with a typed transaction. typed_transaction = TypedTransaction.from_bytes(txn_bytes) msg_hash = typed_transaction.hash() vrs = typed_transaction.vrs() return self._recover_hash(msg_hash, vrs=vrs) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self._recover_hash(msg_hash, vrs=vrs_from(txn)) def set_key_backend(self, backend): """ Change the backend used by the underlying eth-keys library. *(The default is fine for most users)* :param backend: any backend that works in `eth_keys.KeyApi(backend) <https://github.com/ethereum/eth-keys/#keyapibackendnone>`_ """ self._keys = KeyAPI(backend) @combomethod def sign_message( self, signable_message: SignableMessage, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: r""" Sign the provided message. This API supports any messaging format that will encode to EIP-191 messages. If you would like historical compatibility with :meth:`w3.eth.sign() <web3.eth.Eth.sign>` you can use :meth:`~eth_account.messages.encode_defunct`. Other options are the "validator", or "structured data" standards. You can import all supported message encoders in ``eth_account.messages``. :param signable_message: the encoded message for signing :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage .. doctest:: python >>> msg = "I♥SF" >>> from eth_account.messages import encode_defunct >>> msghash = encode_defunct(text=msg) >>> msghash SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF') >>> # If you're curious about the internal fields of SignableMessage, take a look at EIP-191, linked above >>> key = "0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364" >>> Account.sign_message(msghash, key) SignedMessage(messageHash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), message_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) .. _EIP-191: https://eips.ethereum.org/EIPS/eip-191 """ # noqa: E501 message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key)) @combomethod def signHash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. .. CAUTION:: Deprecated for :meth:`~eth_account.account.Account.unsafe_sign_hash`. This method will be removed in v0.13 :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ warnings.warn( "signHash is deprecated in favor of sign_message or unsafe_sign_hash" " depending on your use case", category=DeprecationWarning, stacklevel=2, ) return self._sign_hash(message_hash, private_key) @combomethod def unsafe_sign_hash(self, message_hash, private_key): """ Sign the provided hash. .. WARNING:: *Never* sign a hash that you didn't generate, it can be an arbitrary transaction. For example, it might send all of your account's ether to an attacker. Instead, prefer :meth:`~eth_account.account.Account.sign_message`, which cannot accidentally sign a transaction. :param message_hash: the 32-byte message hash to be signed :type message_hash: hex str, bytes or int :param private_key: the key to sign the message with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage """ return self._sign_hash(message_hash, private_key) @combomethod def _sign_hash( self, message_hash: Hash32, private_key: Union[bytes, HexStr, int, keys.PrivateKey], ) -> SignedMessage: msg_hash_bytes = HexBytes(message_hash) if len(msg_hash_bytes) != 32: raise ValueError("The message hash must be exactly 32-bytes") key = self._parsePrivateKey(private_key) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash_bytes) return SignedMessage( messageHash=msg_hash_bytes, message_hash=msg_hash_bytes, r=r, s=s, v=v, signature=HexBytes(eth_signature_bytes), ) @combomethod def sign_transaction(self, transaction_dict, private_key, blobs=None): r""" Sign a transaction using a local private key. It produces signature details and the hex-encoded transaction suitable for broadcast using :meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`. To create the transaction dict that calls a contract, use contract object: `my_contract.functions.my_function().buildTransaction() <http://web3py.readthedocs.io/en/latest/contracts.html#methods>`_ Note: For non-legacy (typed) transactions, if the transaction type is not explicitly provided, it may be determined from the transaction parameters of a well-formed transaction. See below for examples on how to sign with different transaction types. :param dict transaction_dict: the transaction with available keys, depending on the type of transaction: nonce, chainId, to, data, value, gas, gasPrice, type, accessList, maxFeePerGas, and maxPriorityFeePerGas :param private_key: the private key to sign the data with :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param blobs: optional list of blobs to sign in addition to the transaction :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: SignedTransaction .. doctest:: python >>> # EIP-1559 dynamic fee transaction (more efficient and preferred over legacy txn) >>> from eth_account import Account >>> dynamic_fee_transaction = { ... "type": 2, # optional - can be implicitly determined based on max fee params ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_df_tx = Account.sign_transaction(dynamic_fee_transaction, key) >>> signed_df_tx SignedTransaction(rawTransaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), raw_transaction=HexBytes('0x02f8b28205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107...d58b85d5'), hash=HexBytes('0x2721b2ac99d878695e410af9e8968859b6f6e94f544840be0eb2935bead7deba'), r=48949965662841329840326477994465373664672499148507933176648302825256944281697, s=1123041608316060268133200864147951676126406077675157976022772782796802590165, v=1) >>> w3.eth.sendRawTransaction(signed_df_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> # legacy transaction (less efficient than EIP-1559 dynamic fee txn) >>> from eth_account import Account >>> legacy_transaction = { ... # Note that the address must be in checksum format or native bytes: ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'gasPrice': 234567897654321, ... 'nonce': 0, ... 'chainId': 1337 ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_legacy_tx = Account.sign_transaction(legacy_transaction, key) >>> signed_legacy_tx SignedTransaction(rawTransaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), raw_transaction=HexBytes('0xf86c8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080820a95a01a7...c0bfdb52'), hash=HexBytes('0xd0a3e5dc7439f260c64cb0220139ec5dc7e016f82ce272a25a0f0b38fe751673'), r=11971260903864915610009019893820767192081275151191539081612245320300335068143, s=35365272040292958794699923036506252105590820339897221552886630515981233937234, v=2709) >>> w3.eth.sendRawTransaction(signed_legacy_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> access_list_transaction = { ... "type": 1, # optional - can be implicitly determined based on 'accessList' and 'gasPrice' params ... "gas": 100000, ... "gasPrice": 1000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed_al_tx = Account.sign_transaction(access_list_transaction, key) >>> signed_al_tx SignedTransaction(rawTransaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), raw_transaction=HexBytes('0x01f8ad82053922843b9aca00830186a09409616c3d61b3331fc4109a9e41a8bdb7d9776609865af3107a400086616...2b5043ea'), hash=HexBytes('0xca9af2ef41691e06eb07e02125938fd9bb5a311e8daf330b264e77d6cdf3d17e'), r=107355854401379915513092408112372039746594668141865279802319959599514133709188, s=6729502936685237038651223791038758905953302464070244934323623239104475448298, v=1) >>> w3.eth.sendRawTransaction(signed_al_tx.raw_transaction) # doctest: +SKIP .. doctest:: python >>> from eth_account import Account >>> blob_transaction = { ... "type": 3, # optional - can be implicitly determined based on `maxFeePerBlobGas` param ... "gas": 100000, ... "maxFeePerGas": 2000000000, ... "maxPriorityFeePerGas": 2000000000, ... "maxFeePerBlobGas": 2000000000, ... "data": "0x616263646566", ... "nonce": 34, ... "to": "0x09616C3d61b3331fc4109a9E41a8BDB7d9776609", ... "value": "0x5af3107a4000", ... "accessList": ( # optional ... { ... "address": "0x0000000000000000000000000000000000000001", ... "storageKeys": ( ... "0x0100000000000000000000000000000000000000000000000000000000000000", ... ) ... }, ... ), ... "chainId": 1337, ... } >>> empty_blob = b"\x00" * 32 * 4096 # 4096 empty 32-byte field elements >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> # The `blobVersionedHashes` transaction field is calculated from the `blobs` kwarg >>> signed_blob_tx = Account.sign_transaction(blob_transaction, key, blobs=[empty_blob]) >>> signed_blob_tx SignedTransaction(rawTransaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), raw_transaction=HexBytes('0x03fa020147f8d98205392284773594008477359400830186a09409616c3d61b3331fc4109a9e41a8bdb7d97766098...00000000'), hash=HexBytes('0xf9dc8867c4324fd7f4506622aa700989562770f01d7d681cef74a1a1deb9fea9'), r=14319949980593194209648175507603206696573324965145502821772573913457715875718, s=9129184742597516615341309773045281461399831333162885393648678700392065987233, v=1) >>> w3.eth.sendRawTransaction(signed_blob_tx.raw_transaction) # doctest: +SKIP """ # noqa: E501 if not isinstance(transaction_dict, Mapping): raise TypeError( f"transaction_dict must be dict-like, got {repr(transaction_dict)}" ) account = self.from_key(private_key) # allow from field, *only* if it matches the private key if "from" in transaction_dict: if transaction_dict["from"] == account.address: sanitized_transaction = dissoc(transaction_dict, "from") else: raise TypeError( f"from field must match key's {account.address}, but it was " f"{transaction_dict['from']}" ) else: sanitized_transaction = transaction_dict # sign transaction ( v, r, s, encoded_transaction, ) = sign_transaction_dict(account._key_obj, sanitized_transaction, blobs=blobs) transaction_hash = keccak(encoded_transaction) return SignedTransaction( rawTransaction=HexBytes(encoded_transaction), raw_transaction=HexBytes(encoded_transaction), hash=HexBytes(transaction_hash), r=r, s=s, v=v, ) @combomethod def _parsePrivateKey(self, key): """ Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` will be generated :type key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :returns: the provided key represented as a :class:`eth_keys.datatypes.PrivateKey` """ if isinstance(key, self._keys.PrivateKey): return key try: return self._keys.PrivateKey(HexBytes(key)) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " f"{len(key)} bytes." ) from original_exception @combomethod def sign_typed_data( self, private_key: Union[bytes, HexStr, int, keys.PrivateKey], domain_data: Dict[str, Any] = None, message_types: Dict[str, Any] = None, message_data: Dict[str, Any] = None, full_message: Dict[str, Any] = None, ) -> SignedMessage: r""" Sign the provided EIP-712 message with the provided key. :param private_key: the key to sign the message with :param domain_data: EIP712 domain data :param message_types: custom types used by the `value` data :param message_data: data to be signed :param full_message: a dict containing all data and types :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :type domain_data: dict :type message_types: dict :type message_data: dict :type full_message: dict :returns: Various details about the signature - most importantly the fields: v, r, and s :rtype: ~eth_account.datastructures.SignedMessage You may supply the information to be encoded in one of two ways: As exactly three arguments: - ``domain_data``, a dict of the EIP-712 domain data - ``message_types``, a dict of custom types (do not include a ``EIP712Domain`` key) - ``message_data``, a dict of the data to be signed Or as a single argument: - ``full_message``, a dict containing the following keys: - ``types``, a dict of custom types (may include a ``EIP712Domain`` key) - ``primaryType``, (optional) a string of the primary type of the message - ``domain``, a dict of the EIP-712 domain data - ``message``, a dict of the data to be signed .. WARNING:: Note that this code has not gone through an external audit, and the test cases are incomplete. See documentation for :meth:`~eth_account.messages.encode_typed_data` for usage details See the `EIP-712 spec <https://eips.ethereum.org/EIPS/eip-712>`_ for more information. .. doctest:: python >>> # examples of basic usage >>> from eth_account import Account >>> # 3-argument usage >>> # all domain properties are optional >>> domain_data = { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef", ... } >>> # custom types >>> message_types = { ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... } >>> # the data to be signed >>> message_data = { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", ... }, ... "contents": "Hello, Bob!", ... } >>> key = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" >>> signed_message = Account.sign_typed_data(key, domain_data, message_types, message_data) >>> signed_message.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> # 1-argument usage >>> # all domain properties are optional >>> full_message = { ... "types": { ... "EIP712Domain": [ ... {"name": "name", "type": "string"}, ... {"name": "version", "type": "string"}, ... {"name": "chainId", "type": "uint256"}, ... {"name": "verifyingContract", "type": "address"}, ... {"name": "salt", "type": "bytes32"}, ... ], ... "Person": [ ... {"name": "name", "type": "string"}, ... {"name": "wallet", "type": "address"}, ... ], ... "Mail": [ ... {"name": "from", "type": "Person"}, ... {"name": "to", "type": "Person"}, ... {"name": "contents", "type": "string"}, ... ], ... }, ... "primaryType": "Mail", ... "domain": { ... "name": "Ether Mail", ... "version": "1", ... "chainId": 1, ... "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", ... "salt": b"decafbeef" ... }, ... "message": { ... "from": { ... "name": "Cow", ... "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" ... }, ... "to": { ... "name": "Bob", ... "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" ... }, ... "contents": "Hello, Bob!", ... }, ... } >>> signed_message_2 = Account.sign_typed_data(key, full_message=full_message) >>> signed_message_2.message_hash HexBytes('0xc5bb16ccc59ae9a3ad1cb8343d4e3351f057c994a97656e1aff8c134e56f7530') >>> signed_message_2 == signed_message True .. _EIP-712: https://eips.ethereum.org/EIPS/eip-712 """ # noqa: E501 signable_message = encode_typed_data( domain_data, message_types, message_data, full_message, ) message_hash = _hash_eip191_message(signable_message) return cast(SignedMessage, self._sign_hash(message_hash, private_key))
(self, message_hash, private_key)
7,506
gitignorefile
Cache
Caches information about different `.gitignore` files in the directory tree. Allows to reduce number of queries to filesystem to mininum.
class Cache: """Caches information about different `.gitignore` files in the directory tree. Allows to reduce number of queries to filesystem to mininum. """ def __init__(self, ignore_names=DEFAULT_IGNORE_NAMES): """Constructs `Cache` objects. Args: ignore_names (list[str], optional): List of names of ignore files. """ self.__ignore_names = ignore_names self.__gitignores = {} def __call__(self, path, is_dir=None): """Checks whether the specified path is ignored. Args: path (str): Path to check against ignore rules. is_dir (bool, optional): Set if you know whether the specified path is a directory. """ path = _Path(path) add_to_children = {} plain_paths = [] for parent in path.parents(): if parent.parts in self.__gitignores: break ignore_paths = [] for ignore_name in self.__ignore_names: ignore_path = parent.join(ignore_name) if ignore_path.isfile(): ignore_paths.append(str(ignore_path)) if ignore_paths: matches = [parse(ignore_path, base_path=parent) for ignore_path in ignore_paths] add_to_children[parent] = (matches, plain_paths) plain_paths = [] else: plain_paths.append(parent) else: parent = _Path(tuple()) # Null path. self.__gitignores[parent.parts] = [] for plain_path in plain_paths: # assert plain_path.parts not in self.__gitignores self.__gitignores[plain_path.parts] = self.__gitignores[parent.parts] for parent, (_, parent_plain_paths) in reversed(list(add_to_children.items())): # assert parent.parts not in self.__gitignores self.__gitignores[parent.parts] = self.__gitignores[parent.parts[:-1]].copy() for parent_to_add, (gitignores_to_add, _) in reversed(list(add_to_children.items())): self.__gitignores[parent.parts].extend(gitignores_to_add) if parent_to_add == parent: break self.__gitignores[parent.parts].reverse() for plain_path in parent_plain_paths: # assert plain_path.parts not in self.__gitignores self.__gitignores[plain_path.parts] = self.__gitignores[parent.parts] # This parent comes either from first or second loop. return any((m(path, is_dir=is_dir) for m in self.__gitignores[parent.parts]))
(ignore_names=['.gitignore', '.git/info/exclude'])
7,507
gitignorefile
__call__
Checks whether the specified path is ignored. Args: path (str): Path to check against ignore rules. is_dir (bool, optional): Set if you know whether the specified path is a directory.
def __call__(self, path, is_dir=None): """Checks whether the specified path is ignored. Args: path (str): Path to check against ignore rules. is_dir (bool, optional): Set if you know whether the specified path is a directory. """ path = _Path(path) add_to_children = {} plain_paths = [] for parent in path.parents(): if parent.parts in self.__gitignores: break ignore_paths = [] for ignore_name in self.__ignore_names: ignore_path = parent.join(ignore_name) if ignore_path.isfile(): ignore_paths.append(str(ignore_path)) if ignore_paths: matches = [parse(ignore_path, base_path=parent) for ignore_path in ignore_paths] add_to_children[parent] = (matches, plain_paths) plain_paths = [] else: plain_paths.append(parent) else: parent = _Path(tuple()) # Null path. self.__gitignores[parent.parts] = [] for plain_path in plain_paths: # assert plain_path.parts not in self.__gitignores self.__gitignores[plain_path.parts] = self.__gitignores[parent.parts] for parent, (_, parent_plain_paths) in reversed(list(add_to_children.items())): # assert parent.parts not in self.__gitignores self.__gitignores[parent.parts] = self.__gitignores[parent.parts[:-1]].copy() for parent_to_add, (gitignores_to_add, _) in reversed(list(add_to_children.items())): self.__gitignores[parent.parts].extend(gitignores_to_add) if parent_to_add == parent: break self.__gitignores[parent.parts].reverse() for plain_path in parent_plain_paths: # assert plain_path.parts not in self.__gitignores self.__gitignores[plain_path.parts] = self.__gitignores[parent.parts] # This parent comes either from first or second loop. return any((m(path, is_dir=is_dir) for m in self.__gitignores[parent.parts]))
(self, path, is_dir=None)
7,508
gitignorefile
__init__
Constructs `Cache` objects. Args: ignore_names (list[str], optional): List of names of ignore files.
def __init__(self, ignore_names=DEFAULT_IGNORE_NAMES): """Constructs `Cache` objects. Args: ignore_names (list[str], optional): List of names of ignore files. """ self.__ignore_names = ignore_names self.__gitignores = {}
(self, ignore_names=['.gitignore', '.git/info/exclude'])
7,509
gitignorefile
_IgnoreRule
null
class _IgnoreRule: def __init__(self, regexp, negation, directory_only): self.__regexp = re.compile(regexp) self.__negation = negation self.__directory_only = directory_only self.__match = self.__regexp.match @property def regexp(self): return self.__regexp @property def negation(self): return self.__negation def match(self, rel_path, is_dir): m = self.__match(rel_path) # If we need a directory, check there is something after slash and if there is not, target must be a directory. # If there is something after slash then it's a directory irrelevant to type of target. # `self.directory_only` implies we have group number 1. # N.B. Question mark inside a group without a name can shift indices. :( return m and (not self.__directory_only or m.group(1) is not None or is_dir)
(regexp, negation, directory_only)
7,510
gitignorefile
__init__
null
def __init__(self, regexp, negation, directory_only): self.__regexp = re.compile(regexp) self.__negation = negation self.__directory_only = directory_only self.__match = self.__regexp.match
(self, regexp, negation, directory_only)
7,511
gitignorefile
match
null
def match(self, rel_path, is_dir): m = self.__match(rel_path) # If we need a directory, check there is something after slash and if there is not, target must be a directory. # If there is something after slash then it's a directory irrelevant to type of target. # `self.directory_only` implies we have group number 1. # N.B. Question mark inside a group without a name can shift indices. :( return m and (not self.__directory_only or m.group(1) is not None or is_dir)
(self, rel_path, is_dir)
7,512
gitignorefile
_IgnoreRules
null
class _IgnoreRules: def __init__(self, rules, base_path): self.__rules = rules self.__can_return_immediately = not any((r.negation for r in rules)) self.__base_path = _Path(base_path) if isinstance(base_path, str) else base_path def match(self, path, is_dir=None): if isinstance(path, str): path = _Path(path) rel_path = path.relpath(self.__base_path) if rel_path is not None: if is_dir is None: is_dir = path.isdir() # TODO Pass callable here. if self.__can_return_immediately: return any((r.match(rel_path, is_dir) for r in self.__rules)) else: matched = False for rule in self.__rules: if rule.match(rel_path, is_dir): matched = not rule.negation else: return matched else: return False
(rules, base_path)
7,513
gitignorefile
__init__
null
def __init__(self, rules, base_path): self.__rules = rules self.__can_return_immediately = not any((r.negation for r in rules)) self.__base_path = _Path(base_path) if isinstance(base_path, str) else base_path
(self, rules, base_path)
7,514
gitignorefile
match
null
def match(self, path, is_dir=None): if isinstance(path, str): path = _Path(path) rel_path = path.relpath(self.__base_path) if rel_path is not None: if is_dir is None: is_dir = path.isdir() # TODO Pass callable here. if self.__can_return_immediately: return any((r.match(rel_path, is_dir) for r in self.__rules)) else: matched = False for rule in self.__rules: if rule.match(rel_path, is_dir): matched = not rule.negation else: return matched else: return False
(self, path, is_dir=None)
7,515
gitignorefile
_Path
null
class _Path: def __init__(self, path): if isinstance(path, str): abs_path = os.path.abspath(path) self.__parts = tuple(_path_split(abs_path)) self.__joined = abs_path self.__is_dir = None else: self.__parts = path self.__joined = None self.__is_dir = None @property def parts(self): return self.__parts def join(self, name): return _Path(self.__parts + (name,)) def relpath(self, base_path): if self.__parts[: len(base_path.__parts)] == base_path.__parts: return "/".join(self.__parts[len(base_path.__parts) :]) else: return None def parents(self): for i in range(len(self.__parts) - 1, 0, -1): yield _Path(self.__parts[:i]) def isfile(self): return os.path.isfile(str(self)) def isdir(self): if self.__is_dir is not None: return self.__is_dir self.__is_dir = os.path.isdir(str(self)) return self.__is_dir def __str__(self): if self.__joined is None: self.__joined = os.sep.join(self.__parts) if self.__parts != ("",) else os.sep return self.__joined
(path)
7,516
gitignorefile
__init__
null
def __init__(self, path): if isinstance(path, str): abs_path = os.path.abspath(path) self.__parts = tuple(_path_split(abs_path)) self.__joined = abs_path self.__is_dir = None else: self.__parts = path self.__joined = None self.__is_dir = None
(self, path)
7,517
gitignorefile
__str__
null
def __str__(self): if self.__joined is None: self.__joined = os.sep.join(self.__parts) if self.__parts != ("",) else os.sep return self.__joined
(self)
7,518
gitignorefile
isdir
null
def isdir(self): if self.__is_dir is not None: return self.__is_dir self.__is_dir = os.path.isdir(str(self)) return self.__is_dir
(self)
7,519
gitignorefile
isfile
null
def isfile(self): return os.path.isfile(str(self))
(self)
7,520
gitignorefile
join
null
def join(self, name): return _Path(self.__parts + (name,))
(self, name)
7,521
gitignorefile
parents
null
def parents(self): for i in range(len(self.__parts) - 1, 0, -1): yield _Path(self.__parts[:i])
(self)
7,522
gitignorefile
relpath
null
def relpath(self, base_path): if self.__parts[: len(base_path.__parts)] == base_path.__parts: return "/".join(self.__parts[len(base_path.__parts) :]) else: return None
(self, base_path)
7,523
gitignorefile
_fnmatch_pathname_to_regexp
null
def _fnmatch_pathname_to_regexp(pattern, anchored, directory_only): # Implements `fnmatch` style-behavior, as though with `FNM_PATHNAME` flagged; # the path separator will not match shell-style `*` and `.` wildcards. # Frustratingly, python's fnmatch doesn't provide the FNM_PATHNAME # option that `.gitignore`'s behavior depends on. if not pattern: if directory_only: return "[^/]+(/.+)?$" # Empty name means no path fragment. else: return ".*" i, n = 0, len(pattern) res = ["(?:^|.+/)" if not anchored else ""] while i < n: c = pattern[i] i += 1 if c == "*": if i < n and pattern[i] == "*": i += 1 if i < n and pattern[i] == "/": i += 1 res.append("(.+/)?") # `/**/` matches `/`. else: res.append(".*") else: res.append("[^/]*") elif c == "?": res.append("[^/]") elif c == "[": j = i if j < n and pattern[j] == "!": j += 1 if j < n and pattern[j] == "]": j += 1 while j < n and pattern[j] != "]": j += 1 if j >= n: res.append("\\[") else: stuff = pattern[i:j].replace("\\", "\\\\") i = j + 1 if stuff[0] == "!": stuff = f"^{stuff[1:]}" elif stuff[0] == "^": stuff = f"\\{stuff}" res.append(f"[{stuff}]") else: res.append(re.escape(c)) if directory_only: # In this case we are interested if there is something after slash. res.append("(/.+)?$") else: res.append("(?:/.+)?$") return "".join(res)
(pattern, anchored, directory_only)
7,524
gitignorefile
<lambda>
null
_path_split = lambda path: path.split(os.sep)
(path)
7,525
gitignorefile
_rule_from_pattern
null
def _rule_from_pattern(pattern): # Takes a `.gitignore` match pattern, such as "*.py[cod]" or "**/*.bak", # and returns an `_IgnoreRule` suitable for matching against files and # directories. Patterns which do not match files, such as comments # and blank lines, will return `None`. # Store the exact pattern for our repr and string functions orig_pattern = pattern # Early returns follow # Discard comments and separators if not pattern.lstrip() or pattern.lstrip().startswith("#"): return # Discard anything with more than two consecutive asterisks if "***" in pattern: return # Strip leading bang before examining double asterisks if pattern.startswith("!"): negation = True pattern = pattern[1:] else: negation = False # Discard anything with invalid double-asterisks -- they can appear # at the start or the end, or be surrounded by slashes for m in re.finditer("\\*\\*", pattern): start_index = m.start() if ( start_index != 0 and start_index != len(pattern) - 2 and (pattern[start_index - 1] != "/" or pattern[start_index + 2] != "/") ): return # Special-casing '/', which doesn't match any files or directories if pattern.rstrip() == "/": return directory_only = pattern.endswith("/") # A slash is a sign that we're tied to the `base_path` of our rule # set. anchored = "/" in pattern[:-1] if pattern.startswith("/"): pattern = pattern[1:] if pattern.startswith("**"): pattern = pattern[2:] anchored = False if pattern.startswith("/"): pattern = pattern[1:] if pattern.endswith("/"): pattern = pattern[:-1] # patterns with leading hashes are escaped with a backslash in front, unescape it if pattern.startswith("\\#"): pattern = pattern[1:] # trailing spaces are ignored unless they are escaped with a backslash i = len(pattern) - 1 striptrailingspaces = True while i > 1 and pattern[i] == " ": if pattern[i - 1] == "\\": pattern = pattern[: i - 1] + pattern[i:] i -= 1 striptrailingspaces = False else: if striptrailingspaces: pattern = pattern[:i] i -= 1 regexp = _fnmatch_pathname_to_regexp(pattern, anchored, directory_only) return _IgnoreRule(regexp, negation, directory_only)
(pattern)
7,527
gitignorefile
ignore
Returns `shutil.copytree()`-compatible ignore function for skipping ignored files. It will check if file is ignored by any `.gitignore` in the directory tree. Args: ignore_names (list[str], optional): List of names of ignore files. Returns: Callable[[str, list[str]], list[str]]: Callable compatible with `shutil.copytree()`.
def ignore(ignore_names=DEFAULT_IGNORE_NAMES): """Returns `shutil.copytree()`-compatible ignore function for skipping ignored files. It will check if file is ignored by any `.gitignore` in the directory tree. Args: ignore_names (list[str], optional): List of names of ignore files. Returns: Callable[[str, list[str]], list[str]]: Callable compatible with `shutil.copytree()`. """ matches = Cache(ignore_names=ignore_names) return lambda root, names: {name for name in names if matches(os.path.join(root, name))}
(ignore_names=['.gitignore', '.git/info/exclude'])
7,528
gitignorefile
ignored
Checks if file is ignored by any `.gitignore` in the directory tree. Args: path (str): Path to check against ignore rules. is_dir (bool, optional): Set if you know whether the specified path is a directory. ignore_names (list[str], optional): List of names of ignore files. Returns: bool: `True` if the path is ignored.
def ignored(path, is_dir=None, ignore_names=DEFAULT_IGNORE_NAMES): """Checks if file is ignored by any `.gitignore` in the directory tree. Args: path (str): Path to check against ignore rules. is_dir (bool, optional): Set if you know whether the specified path is a directory. ignore_names (list[str], optional): List of names of ignore files. Returns: bool: `True` if the path is ignored. """ return Cache(ignore_names=ignore_names)(path, is_dir=is_dir)
(path, is_dir=None, ignore_names=['.gitignore', '.git/info/exclude'])
7,530
gitignorefile
parse
Parses single `.gitignore` file. Args: path (str): Path to `.gitignore` file. base_path (str): Base path for applying ignore rules. Returns: Callable[[str], bool]: Callable which returns `True` if specified path is ignored. You can also pass `is_dir: bool` optional parameter if you know whether the specified path is a directory.
def parse(path, base_path=None): """Parses single `.gitignore` file. Args: path (str): Path to `.gitignore` file. base_path (str): Base path for applying ignore rules. Returns: Callable[[str], bool]: Callable which returns `True` if specified path is ignored. You can also pass `is_dir: bool` optional parameter if you know whether the specified path is a directory. """ if base_path is None: base_path = os.path.dirname(path) or os.path.dirname(os.path.abspath(path)) rules = [] with open(path) as ignore_file: for line in ignore_file: line = line.rstrip("\r\n") rule = _rule_from_pattern(line) if rule: rules.append(rule) return _IgnoreRules(rules, base_path).match
(path, base_path=None)
7,532
hsbalance.IC_matrix
Alpha
Docstring for ALPHA. Alpha is the an influence coefficient matrix Influence coefficient matrix is a representation of the change of vibration vector in a measuring point when putting a unit weight on a balancing plane.
class Alpha(): """ Docstring for ALPHA. Alpha is the an influence coefficient matrix Influence coefficient matrix is a representation of the change of vibration vector in a measuring point when putting a unit weight on a balancing plane. """ def __init__(self:'Influence matrix', name:'string'=''): """ Instantiate an instance of Alpha name: optional name of Alpha """ self.name = name self.value = None def add(self, direct_matrix:'np.array'=None, A:'initial_vibration numpy.array'=None, B:'trial matrix numpy.array'=None, U:'trial weight row vector numpy.array'=None, keep_trial:'optional keep the previous trial weight in every succeeding trial'=False, name:'string'=''): ''' Method to add new values for Alpha instance either the direct_matrix is needed or ALL of (A, B, U) Args: direct_matrix: numpy array M rows -> measuring points, N columns -> balancing planes A: Initial vibration column array -> numpy array B: Trial matrix MxN array -> numpy array ''' self.A = A self.B = B self.U = U self.keep_trial = keep_trial try: # test if direct input _ = direct_matrix.shape if direct_matrix.ndim < 2: raise IndexError('Influence coefficient matrix should be of more than 1 dimensions.') if direct_matrix.shape[0] >= direct_matrix.shape[1]: self.value = direct_matrix else: raise tools.CustomError('Number of rows(measuring points) should be ' 'equal or more than the number of columns ' '(balancing planes)!') if self.A is not None or self.B is not None or self.U is not None: raise ValueError('Either (direct Matrix) or (A, B, U) should be input, but not both.') except AttributeError: # if direct matrix is not input calculate it from A, B, U # test the exstiance of A, A0, B, U to calculate ALPHA try: all([A.shape, B.shape, U.shape]) # Test dimensions if A.shape[1] > 1: raise tools.CustomError('`A` should be column vector') elif U.ndim > 1: raise tools.CustomError('`U` should be row vector') elif B.shape[0] != A.shape[0] or B.shape[1] != U.shape[0]: raise tools.CustomError('`B` dimensions should match `A`and `U`') else: self.A = A self.B = B self.U = U if not keep_trial: self.value = (self.B - self.A) / self.U else: _A_keep_trial = np.delete((np.insert(self.B, [0], self.A, axis=1)), -1, axis=1) self.value = (self.B - _A_keep_trial) / self.U except AttributeError: raise tools.CustomError('Either direct_matrix or (A,B,U) ' 'should be passed "numpy arrays"') if self.value is not None: self.M = self.value.shape[0] self.N = self.value.shape[1] def check(self, ill_condition_remove=False): ''' Method to check the alpha value * check the symmetrical of the matrix (check for square matrix only, for square matrix it should be symmetric obeying the reciprocity law) * check for ill conditioned planes: if for any reason two or more planes has independent readings for example [[1, 2 , 3], [2, 4, 6]] this is named as ill-conditioned planes as they does not carry new information from the system and considering them cause solution infiltration. ill_condition_remove = True : remove the ill_condition planes after the check ''' if self.M == self.N: _check_sym = np.allclose(self.value, self.value.T, 0.1, 1e-06) if not _check_sym: warnings.warn('\nWarning: Influence Matrix is asymmetrical!') _logger.info('\nInfluence Matrix is asymmetrical, check your data.') else: _logger.info('\nInfluence Matrix is symmetric --> OK') else: _logger.info('\nNot a square matrix --> no exact solution.') # Checking ILL-CONDITIONED planes ill_plane = tools.ill_condition(self.value) if ill_plane: _logger.info(f'\nIll-conditioned found in plane # {ill_plane}') if ill_condition_remove: _logger.warn(f'\nRemoving Ill-conditioned plane # {ill_plane}') _logger.info(f'\nIC matrix before removing\n{tools.convert_cart_math(self.value)}\n') self.value = np.delete(self.value,[ill_plane], axis=1) _logger.info(f'\nIC matrix after removing\n{tools.convert_cart_math(self.value)}\n') else: _logger.info('\nNo ill conditioned planes --> ok') def _info(self): ''' Method to summarize the results for alpha. return generator of tuples(title:str, item) ''' if self.name: yield ('Name', self.name) if self.value is not None: _index = (f'Sensor {m+1}' for m in range(self.value.shape[0])) _columns = (f'Plane {n+1}' for n in range(self.value.shape[1])) yield ('Coefficient Values', pd.DataFrame(tools.convert_cart_math(self.value), index=_index, columns=_columns)) if self.A is not None: _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('Initial Vibration', pd.DataFrame(tools.convert_cart_math(self.A), index=_index, columns=['Vibration'])) if self.B is not None: _index = (f'Sensor {m+1}' for m in range(self.B.shape[0])) _columns = (f'Plane {n+1}' for n in range(self.B.shape[1])) yield ('Trial Runs Vibration', pd.DataFrame(tools.convert_cart_math(self.B), index=_index, columns=_columns)) if self.U is not None: _index = (f'Plane {n+1}' for n in range(self.U.shape[0])) yield ('Trial Masses', pd.DataFrame(tools.convert_cart_math(self.U), index=_index, columns=['Mass'])) def __repr__(self): ''' Method to print out alpha value ''' formatter = tools.InfoFormatter(name = 'Influence Coefficient Matrix', info_parameters= self._info()) return ''.join(formatter.info()) def save(self, file:str): ''' Method to save influence coefficient values ''' if isinstance(file, str): self.file = file np.save(file, self.value) def load(self, file:str): ''' Method to load influence coefficient value ''' if isinstance(file, str): self.file = file + '.npy' _matrix = np.load(self.file) self.add(direct_matrix=_matrix) @property def shape(self): ''' returns shape of Influence coefficient matrix (no. Measuring Points, no. Balancing Planes) ''' if (self.M is not None) and (self.N is not None): return (self.M, self.N)
(name: 'string' = '')
7,533
hsbalance.IC_matrix
__init__
Instantiate an instance of Alpha name: optional name of Alpha
def __init__(self:'Influence matrix', name:'string'=''): """ Instantiate an instance of Alpha name: optional name of Alpha """ self.name = name self.value = None
(self: 'Influence matrix', name: 'string' = '')
7,534
hsbalance.IC_matrix
__repr__
Method to print out alpha value
def __repr__(self): ''' Method to print out alpha value ''' formatter = tools.InfoFormatter(name = 'Influence Coefficient Matrix', info_parameters= self._info()) return ''.join(formatter.info())
(self)
7,535
hsbalance.IC_matrix
_info
Method to summarize the results for alpha. return generator of tuples(title:str, item)
def _info(self): ''' Method to summarize the results for alpha. return generator of tuples(title:str, item) ''' if self.name: yield ('Name', self.name) if self.value is not None: _index = (f'Sensor {m+1}' for m in range(self.value.shape[0])) _columns = (f'Plane {n+1}' for n in range(self.value.shape[1])) yield ('Coefficient Values', pd.DataFrame(tools.convert_cart_math(self.value), index=_index, columns=_columns)) if self.A is not None: _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('Initial Vibration', pd.DataFrame(tools.convert_cart_math(self.A), index=_index, columns=['Vibration'])) if self.B is not None: _index = (f'Sensor {m+1}' for m in range(self.B.shape[0])) _columns = (f'Plane {n+1}' for n in range(self.B.shape[1])) yield ('Trial Runs Vibration', pd.DataFrame(tools.convert_cart_math(self.B), index=_index, columns=_columns)) if self.U is not None: _index = (f'Plane {n+1}' for n in range(self.U.shape[0])) yield ('Trial Masses', pd.DataFrame(tools.convert_cart_math(self.U), index=_index, columns=['Mass']))
(self)
7,536
hsbalance.IC_matrix
add
Method to add new values for Alpha instance either the direct_matrix is needed or ALL of (A, B, U) Args: direct_matrix: numpy array M rows -> measuring points, N columns -> balancing planes A: Initial vibration column array -> numpy array B: Trial matrix MxN array -> numpy array
def add(self, direct_matrix:'np.array'=None, A:'initial_vibration numpy.array'=None, B:'trial matrix numpy.array'=None, U:'trial weight row vector numpy.array'=None, keep_trial:'optional keep the previous trial weight in every succeeding trial'=False, name:'string'=''): ''' Method to add new values for Alpha instance either the direct_matrix is needed or ALL of (A, B, U) Args: direct_matrix: numpy array M rows -> measuring points, N columns -> balancing planes A: Initial vibration column array -> numpy array B: Trial matrix MxN array -> numpy array ''' self.A = A self.B = B self.U = U self.keep_trial = keep_trial try: # test if direct input _ = direct_matrix.shape if direct_matrix.ndim < 2: raise IndexError('Influence coefficient matrix should be of more than 1 dimensions.') if direct_matrix.shape[0] >= direct_matrix.shape[1]: self.value = direct_matrix else: raise tools.CustomError('Number of rows(measuring points) should be ' 'equal or more than the number of columns ' '(balancing planes)!') if self.A is not None or self.B is not None or self.U is not None: raise ValueError('Either (direct Matrix) or (A, B, U) should be input, but not both.') except AttributeError: # if direct matrix is not input calculate it from A, B, U # test the exstiance of A, A0, B, U to calculate ALPHA try: all([A.shape, B.shape, U.shape]) # Test dimensions if A.shape[1] > 1: raise tools.CustomError('`A` should be column vector') elif U.ndim > 1: raise tools.CustomError('`U` should be row vector') elif B.shape[0] != A.shape[0] or B.shape[1] != U.shape[0]: raise tools.CustomError('`B` dimensions should match `A`and `U`') else: self.A = A self.B = B self.U = U if not keep_trial: self.value = (self.B - self.A) / self.U else: _A_keep_trial = np.delete((np.insert(self.B, [0], self.A, axis=1)), -1, axis=1) self.value = (self.B - _A_keep_trial) / self.U except AttributeError: raise tools.CustomError('Either direct_matrix or (A,B,U) ' 'should be passed "numpy arrays"') if self.value is not None: self.M = self.value.shape[0] self.N = self.value.shape[1]
(self, direct_matrix: 'np.array' = None, A: 'initial_vibration numpy.array' = None, B: 'trial matrix numpy.array' = None, U: 'trial weight row vector numpy.array' = None, keep_trial: 'optional keep the previous trial weight in every succeeding trial' = False, name: 'string' = '')
7,537
hsbalance.IC_matrix
check
Method to check the alpha value * check the symmetrical of the matrix (check for square matrix only, for square matrix it should be symmetric obeying the reciprocity law) * check for ill conditioned planes: if for any reason two or more planes has independent readings for example [[1, 2 , 3], [2, 4, 6]] this is named as ill-conditioned planes as they does not carry new information from the system and considering them cause solution infiltration. ill_condition_remove = True : remove the ill_condition planes after the check
def check(self, ill_condition_remove=False): ''' Method to check the alpha value * check the symmetrical of the matrix (check for square matrix only, for square matrix it should be symmetric obeying the reciprocity law) * check for ill conditioned planes: if for any reason two or more planes has independent readings for example [[1, 2 , 3], [2, 4, 6]] this is named as ill-conditioned planes as they does not carry new information from the system and considering them cause solution infiltration. ill_condition_remove = True : remove the ill_condition planes after the check ''' if self.M == self.N: _check_sym = np.allclose(self.value, self.value.T, 0.1, 1e-06) if not _check_sym: warnings.warn('\nWarning: Influence Matrix is asymmetrical!') _logger.info('\nInfluence Matrix is asymmetrical, check your data.') else: _logger.info('\nInfluence Matrix is symmetric --> OK') else: _logger.info('\nNot a square matrix --> no exact solution.') # Checking ILL-CONDITIONED planes ill_plane = tools.ill_condition(self.value) if ill_plane: _logger.info(f'\nIll-conditioned found in plane # {ill_plane}') if ill_condition_remove: _logger.warn(f'\nRemoving Ill-conditioned plane # {ill_plane}') _logger.info(f'\nIC matrix before removing\n{tools.convert_cart_math(self.value)}\n') self.value = np.delete(self.value,[ill_plane], axis=1) _logger.info(f'\nIC matrix after removing\n{tools.convert_cart_math(self.value)}\n') else: _logger.info('\nNo ill conditioned planes --> ok')
(self, ill_condition_remove=False)
7,538
hsbalance.IC_matrix
load
Method to load influence coefficient value
def load(self, file:str): ''' Method to load influence coefficient value ''' if isinstance(file, str): self.file = file + '.npy' _matrix = np.load(self.file) self.add(direct_matrix=_matrix)
(self, file: str)
7,539
hsbalance.IC_matrix
save
Method to save influence coefficient values
def save(self, file:str): ''' Method to save influence coefficient values ''' if isinstance(file, str): self.file = file np.save(file, self.value)
(self, file: str)
7,540
hsbalance.IC_matrix
Condition
Docstring for conditions. Condition is defined as speed or load or operating condition that is concerned in the balancing process. Conditions class is meant to be used for creating multispeed-multi_condition It is designed to arrange the conditions speeds and loads in explicit way.
class Condition(): """ Docstring for conditions. Condition is defined as speed or load or operating condition that is concerned in the balancing process. Conditions class is meant to be used for creating multispeed-multi_condition It is designed to arrange the conditions speeds and loads in explicit way. """ def __init__(self:'condition', name:'string'=''): """ Instantiate a conditions instance that will encapsulate all model speeds and loads name: optional name of Alpha """ self.name = name def add(self, alpha:'Alpha instance', A:'initial_vibration numpy.array'): ''' Method to add a new condition Args: alpha: Alpha class instance A: Initial vibration column array -> numpy array ''' if isinstance(alpha, Alpha): self.alpha = alpha else: raise TypeError('alpha should be class Alpha.') try: _A_shape = A.shape # Test dimensions if A.ndim != 2: raise IndexError('A should be column vector of Mx1 dimension.') elif _A_shape[1] != 1: raise IndexError('A should be column vector of Mx1 dimension.') elif _A_shape[0] != self.alpha.value.shape[0]: raise IndexError('A and alpha should have the same 0 dimension(M).') else: self.A = A except AttributeError: raise TypeError('`A` should be passed as "numpy array"') def _info(self): ''' Method to summarize the results for condition. ''' if self.name: yield ('Name', self.name) if self.alpha is not None: yield ('Condition IC Matrix', str(self.alpha)) if self.A is not None: _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('Initial Vibration', pd.DataFrame(tools.convert_cart_math(self.A), index=_index, columns=['Vibration'])) def __repr__(self): ''' Method to print out condition value ''' formatter = tools.InfoFormatter(name = 'Operation Condition', info_parameters= self._info(), level=2) return ''.join(formatter.info()) def save(self, file:str): ''' Method to save condition instance. ''' if isinstance(file, str): self.file = file with open(self.file, 'wb') as f: pickle.dump(self, f) def load(self, file:str): ''' Method to load condition instance. ''' if isinstance(file, str): self.file = file with open(self.file, 'rb') as f: _loaded_instance = pickle.load(f) self.add(_loaded_instance.alpha, _loaded_instance.A)
(name: 'string' = '')
7,541
hsbalance.IC_matrix
__init__
Instantiate a conditions instance that will encapsulate all model speeds and loads name: optional name of Alpha
def __init__(self:'condition', name:'string'=''): """ Instantiate a conditions instance that will encapsulate all model speeds and loads name: optional name of Alpha """ self.name = name
(self: 'condition', name: 'string' = '')
7,542
hsbalance.IC_matrix
__repr__
Method to print out condition value
def __repr__(self): ''' Method to print out condition value ''' formatter = tools.InfoFormatter(name = 'Operation Condition', info_parameters= self._info(), level=2) return ''.join(formatter.info())
(self)
7,543
hsbalance.IC_matrix
_info
Method to summarize the results for condition.
def _info(self): ''' Method to summarize the results for condition. ''' if self.name: yield ('Name', self.name) if self.alpha is not None: yield ('Condition IC Matrix', str(self.alpha)) if self.A is not None: _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('Initial Vibration', pd.DataFrame(tools.convert_cart_math(self.A), index=_index, columns=['Vibration']))
(self)
7,544
hsbalance.IC_matrix
add
Method to add a new condition Args: alpha: Alpha class instance A: Initial vibration column array -> numpy array
def add(self, alpha:'Alpha instance', A:'initial_vibration numpy.array'): ''' Method to add a new condition Args: alpha: Alpha class instance A: Initial vibration column array -> numpy array ''' if isinstance(alpha, Alpha): self.alpha = alpha else: raise TypeError('alpha should be class Alpha.') try: _A_shape = A.shape # Test dimensions if A.ndim != 2: raise IndexError('A should be column vector of Mx1 dimension.') elif _A_shape[1] != 1: raise IndexError('A should be column vector of Mx1 dimension.') elif _A_shape[0] != self.alpha.value.shape[0]: raise IndexError('A and alpha should have the same 0 dimension(M).') else: self.A = A except AttributeError: raise TypeError('`A` should be passed as "numpy array"')
(self, alpha: 'Alpha instance', A: 'initial_vibration numpy.array')
7,545
hsbalance.IC_matrix
load
Method to load condition instance.
def load(self, file:str): ''' Method to load condition instance. ''' if isinstance(file, str): self.file = file with open(self.file, 'rb') as f: _loaded_instance = pickle.load(f) self.add(_loaded_instance.alpha, _loaded_instance.A)
(self, file: str)
7,546
hsbalance.IC_matrix
save
Method to save condition instance.
def save(self, file:str): ''' Method to save condition instance. ''' if isinstance(file, str): self.file = file with open(self.file, 'wb') as f: pickle.dump(self, f)
(self, file: str)
7,547
hsbalance.tools
CustomError
The class is used to raise custom expections
class CustomError(Exception): ''' The class is used to raise custom expections ''' pass
null
7,549
hsbalance.tools
InfoFormatter
Class to format info method of every class.
class InfoFormatter: ''' Class to format info method of every class. ''' def __init__(self, name:str, info_parameters:Iterable, level:int=1) -> str: '''Args: info_parameters generator of tuple(name, parm) from _info method level: level for nested appearance ''' self.info_parameters = info_parameters self.name = name self.line_header = f'\n{(30+10*level)*"+"}\n' self.line_separator = f'\n{(20+10*level)*"="}\n' def info(self): ''' return generator with the strings to be printed ''' # Header yield f'{self.line_header}{self.name}{self.line_header}' # parameters for item in self.info_parameters: title, param = item yield f'''{self.line_header}{title}{self.line_separator}{param }{self.line_separator}End of {title}{ self.line_header} '''
(name: str, info_parameters: Iterable, level: int = 1) -> str
7,550
hsbalance.tools
__init__
Args: info_parameters generator of tuple(name, parm) from _info method level: level for nested appearance
def __init__(self, name:str, info_parameters:Iterable, level:int=1) -> str: '''Args: info_parameters generator of tuple(name, parm) from _info method level: level for nested appearance ''' self.info_parameters = info_parameters self.name = name self.line_header = f'\n{(30+10*level)*"+"}\n' self.line_separator = f'\n{(20+10*level)*"="}\n'
(self, name: str, info_parameters: Iterable, level: int = 1) -> str
7,551
hsbalance.tools
info
return generator with the strings to be printed
def info(self): ''' return generator with the strings to be printed ''' # Header yield f'{self.line_header}{self.name}{self.line_header}' # parameters for item in self.info_parameters: title, param = item yield f'''{self.line_header}{title}{self.line_separator}{param }{self.line_separator}End of {title}{ self.line_header} '''
(self)
7,552
hsbalance.model
LMI
subclass of model solving using linear matrix inequality this is mainly to insert 'lazy constraints' Lazy constraints will relax the solution at certain planes (not to exceed certain vibration limit)
class LMI(_Model): """ subclass of model solving using linear matrix inequality this is mainly to insert 'lazy constraints' Lazy constraints will relax the solution at certain planes (not to exceed certain vibration limit) """ def __init__(self, A:np.array, alpha:'instance of Alpha class', conditions=None, weight_const={}, critical_planes={}, V_max=None, name=''): """ Args: A: Initial vibration vector -> np.ndarray alpha: Instance of Alpha class critical_planes: set of critical planes weight_const: dict class of planes index and maximum permissible weight V_max: max vibration for non-critical_planes Return: Solution Matrix W """ self.weight_const = weight_const self.critical_planes = list(critical_planes) self.V_max = V_max super().__init__(A=A, alpha=alpha, conditions= conditions, name=name) def solve(self, solver=None): ''' solving the LMI model returns solution matrix W ''' # Weight constraints N = self.N M = self.M _wc = np.zeros(N) if self.weight_const != {}: try: for key, value in self.weight_const.items(): _wc[key] = value except NameError: raise tools.CustomError('Invalid weight constraint format') else: pass # Identify critical planes if self.V_max: _Vm = self.V_max else: raise tools.CustomError('V_max is not specified') if self.critical_planes and len(self.critical_planes)>0: _list_cr = self.critical_planes else: raise tools.CustomError('Critical Planes are not set.') _ALPHA = self.ALPHA.copy() A = self.A.copy() _ALPHAcr = _ALPHA[_list_cr] Acr = A[_list_cr] _ALPHAncr = np.delete(_ALPHA, _list_cr, axis=0) _Ancr = np.delete(A, _list_cr, axis=0) # assign cvxpy variables _WR = cp.Variable((N, 1)) _WI = cp.Variable((N, 1)) _Vc = cp.Variable() _RRfcr = cp.diag(np.real(Acr) + np.real(_ALPHAcr) @ _WR-np.imag(_ALPHAcr) @ _WI) _IRfcr = cp.diag(np.imag(Acr) + np.imag(_ALPHAcr) @ _WR+np.real(_ALPHAcr) @ _WI) _RRfNcr = cp.diag(np.real(_Ancr) + np.real(_ALPHAncr) @ _WR - np.imag(_ALPHAncr) @ _WI) _IRfNcr = cp.diag(np.imag(_Ancr)+ np.imag(_ALPHAncr) @ _WR + np.real(_ALPHAncr) @ _WI) _zcr = np.zeros((_RRfcr.shape[0], _RRfcr.shape[1])) _Icr = np.eye(_RRfcr.shape[0]) _zncr = np.zeros((_RRfNcr.shape[0], _RRfNcr.shape[1])) _Incr = np.eye(_RRfNcr.shape[0]) _objective = cp.Minimize(_Vc) _LMI_real = cp.bmat( [ [_Vc*_Icr, _RRfcr, _zcr, -_IRfcr], [_RRfcr, _Icr, _IRfcr, _zcr], [_zcr, _IRfcr, _Vc*_Icr, _RRfcr], [-_IRfcr, _zcr, _RRfcr, _Icr] ]) _LMI_imag =cp.bmat( [ [_Vm**2*_Incr, _RRfNcr, _zncr, -_IRfNcr], [_RRfNcr, _Incr, _IRfNcr, _zncr], [_zncr, _IRfNcr, _Vm**2*_Incr, _RRfNcr], [-_IRfNcr, _zncr, _RRfNcr, _Incr] ]) # Model weight constraints _const_LMI_w = [] for i in range(N): _LMI_weight = cp.bmat( [ [_wc[i]**2, _WR[i], 0, -_WI[i]], [_WR[i], 1, _WI[i], 0], [0, _WI[i], _wc[i]**2, _WR[i]], [-_WI[i], 0, _WR[i], 1] ]) _const_LMI_w.append(_LMI_weight >> 0) _const_LMI_w.append( _LMI_real >> 0) _const_LMI_w.append( _LMI_imag >> 0) # Stating the problem prob = cp.Problem(_objective, _const_LMI_w) prob.solve(cp.CVXOPT, kktsolver=cp.ROBUST_KKTSOLVER) W = _WR + _WI * 1j self.W = W.value return self.W
(A: <built-in function array>, alpha: 'instance of Alpha class', conditions=None, weight_const={}, critical_planes={}, V_max=None, name='')
7,553
hsbalance.model
__init__
Args: A: Initial vibration vector -> np.ndarray alpha: Instance of Alpha class critical_planes: set of critical planes weight_const: dict class of planes index and maximum permissible weight V_max: max vibration for non-critical_planes Return: Solution Matrix W
def __init__(self, A:np.array, alpha:'instance of Alpha class', conditions=None, weight_const={}, critical_planes={}, V_max=None, name=''): """ Args: A: Initial vibration vector -> np.ndarray alpha: Instance of Alpha class critical_planes: set of critical planes weight_const: dict class of planes index and maximum permissible weight V_max: max vibration for non-critical_planes Return: Solution Matrix W """ self.weight_const = weight_const self.critical_planes = list(critical_planes) self.V_max = V_max super().__init__(A=A, alpha=alpha, conditions= conditions, name=name)
(self, A: <built-in function array>, alpha: 'instance of Alpha class', conditions=None, weight_const={}, critical_planes={}, V_max=None, name='')
7,554
hsbalance.model
_info
Method to summarize the results for Model.
def _info(self): ''' Method to summarize the results for Model. ''' yield ('MODEL TYPE', type(self).__name__) if self.name: yield ('MODEL NAME' , self.name) if self.alpha is not None: yield ('INFLUENCE COEFFICIENT MATRIX', str(self.alpha)) if self.A is not None and self.conditions is None: _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('INITIAL VIBRATION' , pd.DataFrame(tools.convert_cart_math(self.A), index=_index, columns=['Vibration'])) if self.conditions is not None: yield ('CONDITIONS',''.join(str(condition) for condition in self.conditions)) if self.W is not None: _index = (f'Plane {n+1}' for n in range(self.W.shape[0])) yield ('SOLUTION', pd.DataFrame(tools.convert_cart_math(self.W), index=_index, columns=['Correction Masses'])) yield ('RMSE', self.rmse()) _index = (f'Sensor {m+1}' for m in range(self.A.shape[0])) yield ('Resiudal Vibration Expected', pd.DataFrame(tools.convert_cart_math(self.expected_residual_vibration()), index=_index, columns=['Expected Vibration'])) else: yield ('SOLUTION','No solution calculated.') if self.split_instance is not None : if self.split_instance: yield ('SPLITS','\n\n'.join(str(split.results()) for split in self.split_instance))
(self)
7,555
hsbalance.model
create_split
Factory method to create a split instance
def create_split(self): """ Factory method to create a split instance """ return _Model.Split(self)
(self)
7,556
hsbalance.model
expected_residual_vibration
Returns the residual_vibration from tools module
def expected_residual_vibration(self): """ Returns the residual_vibration from tools module """ return tools.residual_vibration(self.ALPHA, self.W, self.A)
(self)
7,557
hsbalance.model
info
null
def info(self): formatter = tools.InfoFormatter(name='MODEL', info_parameters=self._info(), level=3) return ''.join(formatter.info())
(self)
7,558
hsbalance.model
rmse
Returns the root mean squares from tools module
def rmse(self): """ Returns the root mean squares from tools module """ return tools.rmse(self.expected_residual_vibration())
(self)
7,559
hsbalance.model
solve
solving the LMI model returns solution matrix W
def solve(self, solver=None): ''' solving the LMI model returns solution matrix W ''' # Weight constraints N = self.N M = self.M _wc = np.zeros(N) if self.weight_const != {}: try: for key, value in self.weight_const.items(): _wc[key] = value except NameError: raise tools.CustomError('Invalid weight constraint format') else: pass # Identify critical planes if self.V_max: _Vm = self.V_max else: raise tools.CustomError('V_max is not specified') if self.critical_planes and len(self.critical_planes)>0: _list_cr = self.critical_planes else: raise tools.CustomError('Critical Planes are not set.') _ALPHA = self.ALPHA.copy() A = self.A.copy() _ALPHAcr = _ALPHA[_list_cr] Acr = A[_list_cr] _ALPHAncr = np.delete(_ALPHA, _list_cr, axis=0) _Ancr = np.delete(A, _list_cr, axis=0) # assign cvxpy variables _WR = cp.Variable((N, 1)) _WI = cp.Variable((N, 1)) _Vc = cp.Variable() _RRfcr = cp.diag(np.real(Acr) + np.real(_ALPHAcr) @ _WR-np.imag(_ALPHAcr) @ _WI) _IRfcr = cp.diag(np.imag(Acr) + np.imag(_ALPHAcr) @ _WR+np.real(_ALPHAcr) @ _WI) _RRfNcr = cp.diag(np.real(_Ancr) + np.real(_ALPHAncr) @ _WR - np.imag(_ALPHAncr) @ _WI) _IRfNcr = cp.diag(np.imag(_Ancr)+ np.imag(_ALPHAncr) @ _WR + np.real(_ALPHAncr) @ _WI) _zcr = np.zeros((_RRfcr.shape[0], _RRfcr.shape[1])) _Icr = np.eye(_RRfcr.shape[0]) _zncr = np.zeros((_RRfNcr.shape[0], _RRfNcr.shape[1])) _Incr = np.eye(_RRfNcr.shape[0]) _objective = cp.Minimize(_Vc) _LMI_real = cp.bmat( [ [_Vc*_Icr, _RRfcr, _zcr, -_IRfcr], [_RRfcr, _Icr, _IRfcr, _zcr], [_zcr, _IRfcr, _Vc*_Icr, _RRfcr], [-_IRfcr, _zcr, _RRfcr, _Icr] ]) _LMI_imag =cp.bmat( [ [_Vm**2*_Incr, _RRfNcr, _zncr, -_IRfNcr], [_RRfNcr, _Incr, _IRfNcr, _zncr], [_zncr, _IRfNcr, _Vm**2*_Incr, _RRfNcr], [-_IRfNcr, _zncr, _RRfNcr, _Incr] ]) # Model weight constraints _const_LMI_w = [] for i in range(N): _LMI_weight = cp.bmat( [ [_wc[i]**2, _WR[i], 0, -_WI[i]], [_WR[i], 1, _WI[i], 0], [0, _WI[i], _wc[i]**2, _WR[i]], [-_WI[i], 0, _WR[i], 1] ]) _const_LMI_w.append(_LMI_weight >> 0) _const_LMI_w.append( _LMI_real >> 0) _const_LMI_w.append( _LMI_imag >> 0) # Stating the problem prob = cp.Problem(_objective, _const_LMI_w) prob.solve(cp.CVXOPT, kktsolver=cp.ROBUST_KKTSOLVER) W = _WR + _WI * 1j self.W = W.value return self.W
(self, solver=None)
7,560
hsbalance.model
LeastSquares
subclass of Model solving the model using Least squares method, The objective function is to minimize the least squares of residual vibration.
class LeastSquares(_Model): """subclass of Model solving the model using Least squares method, The objective function is to minimize the least squares of residual vibration. """ def __init__(self, A:np.array=None, alpha:'instance of Alpha class'=None, conditions=None, C=np.zeros(1), name=''): """ Instantiate the model Args: A: Initial vibration vector -> np.ndarray ALPHA: Influence coefficient matrix -> class Alpha C: Weighted Least squares coefficients name: optional name of the model -> string """ super().__init__(A=A, alpha=alpha, conditions=conditions, name=name) if C.any(): self.C = C else: self.C = np.ones(self.A.shape) def solve(self, solver='OLE'): ''' Method to solve the model Args: solver:'OLE' Ordinary Least Squares method 'Huber': Uses Huber smoother to down estimate the outliers. ''' W = cp.Variable((self.N, 1), complex=True) if solver.upper() == 'OLE': # Ordinary least squares _objective = cp.Minimize(cp.sum_squares(self.ALPHA @ W + self.A)) elif solver.upper() == 'HUBER': # TODO test Huber solver for robust optimization _real = cp.real(self.ALPHA @ W + self.A) _imag = cp.imag(self.ALPHA @ W + self.A) _objective = cp.Minimize(cp.sum_squares(cp.huber(cp.hstack([_real, _imag]), M=0))) elif solver.upper() == 'WLS': # TODO test weighted least squares _objective = cp.Minimize(cp.sum_squares(cp.diag(self.C) @ (self.ALPHA @ W + self.A))) else: raise tools.CustomError('Unrecognized Solver name') prob = cp.Problem(_objective) prob.solve() self.W = W.value return W.value
(A: <built-in function array> = None, alpha: 'instance of Alpha class' = None, conditions=None, C=array([0.]), name='')
7,561
hsbalance.model
__init__
Instantiate the model Args: A: Initial vibration vector -> np.ndarray ALPHA: Influence coefficient matrix -> class Alpha C: Weighted Least squares coefficients name: optional name of the model -> string
def __init__(self, A:np.array=None, alpha:'instance of Alpha class'=None, conditions=None, C=np.zeros(1), name=''): """ Instantiate the model Args: A: Initial vibration vector -> np.ndarray ALPHA: Influence coefficient matrix -> class Alpha C: Weighted Least squares coefficients name: optional name of the model -> string """ super().__init__(A=A, alpha=alpha, conditions=conditions, name=name) if C.any(): self.C = C else: self.C = np.ones(self.A.shape)
(self, A: <built-in function array> = None, alpha: 'instance of Alpha class' = None, conditions=None, C=array([0.]), name='')
7,567
hsbalance.model
solve
Method to solve the model Args: solver:'OLE' Ordinary Least Squares method 'Huber': Uses Huber smoother to down estimate the outliers.
def solve(self, solver='OLE'): ''' Method to solve the model Args: solver:'OLE' Ordinary Least Squares method 'Huber': Uses Huber smoother to down estimate the outliers. ''' W = cp.Variable((self.N, 1), complex=True) if solver.upper() == 'OLE': # Ordinary least squares _objective = cp.Minimize(cp.sum_squares(self.ALPHA @ W + self.A)) elif solver.upper() == 'HUBER': # TODO test Huber solver for robust optimization _real = cp.real(self.ALPHA @ W + self.A) _imag = cp.imag(self.ALPHA @ W + self.A) _objective = cp.Minimize(cp.sum_squares(cp.huber(cp.hstack([_real, _imag]), M=0))) elif solver.upper() == 'WLS': # TODO test weighted least squares _objective = cp.Minimize(cp.sum_squares(cp.diag(self.C) @ (self.ALPHA @ W + self.A))) else: raise tools.CustomError('Unrecognized Solver name') prob = cp.Problem(_objective) prob.solve() self.W = W.value return W.value
(self, solver='OLE')
7,568
hsbalance.model
Min_max
subclass of model: Solving the model using Minmax optimization method to minimize the maximum of residual_vibration.
class Min_max(_Model): """ subclass of model: Solving the model using Minmax optimization method to minimize the maximum of residual_vibration. """ def __init__(self, A:np.array, alpha:'instance of Alpha class', conditions=None, weight_const={}, name=''): """ Instantiate the model Args: A: Initial vibration vector -> np.ndarray alpha: instance of Alpha class weight_const: dict class of planes index and maximum permissible weight Returns: solution matrix W """ self.weight_const = weight_const super().__init__(A=A, alpha=alpha, conditions=conditions, name=name) def solve(self, solver=None): ''' Method to solve the Minmax model ''' W = cp.Variable((self.N,1),complex=True) _objective = cp.Minimize(cp.norm((self.ALPHA @ W + self.A),"inf")) # Define weight constraints _constrains = [] if self.weight_const != {}: try: for key, value in self.weight_const.items(): _constrains += [cp.norm(W[key]) <= value] except NameError: raise tools.CustomError('Invalid weight constraint format') else: pass prob=cp.Problem(_objective, _constrains) prob.solve() self.W = W.value return W.value
(A: <built-in function array>, alpha: 'instance of Alpha class', conditions=None, weight_const={}, name='')
7,569
hsbalance.model
__init__
Instantiate the model Args: A: Initial vibration vector -> np.ndarray alpha: instance of Alpha class weight_const: dict class of planes index and maximum permissible weight Returns: solution matrix W
def __init__(self, A:np.array, alpha:'instance of Alpha class', conditions=None, weight_const={}, name=''): """ Instantiate the model Args: A: Initial vibration vector -> np.ndarray alpha: instance of Alpha class weight_const: dict class of planes index and maximum permissible weight Returns: solution matrix W """ self.weight_const = weight_const super().__init__(A=A, alpha=alpha, conditions=conditions, name=name)
(self, A: <built-in function array>, alpha: 'instance of Alpha class', conditions=None, weight_const={}, name='')
7,575
hsbalance.model
solve
Method to solve the Minmax model
def solve(self, solver=None): ''' Method to solve the Minmax model ''' W = cp.Variable((self.N,1),complex=True) _objective = cp.Minimize(cp.norm((self.ALPHA @ W + self.A),"inf")) # Define weight constraints _constrains = [] if self.weight_const != {}: try: for key, value in self.weight_const.items(): _constrains += [cp.norm(W[key]) <= value] except NameError: raise tools.CustomError('Invalid weight constraint format') else: pass prob=cp.Problem(_objective, _constrains) prob.solve() self.W = W.value return W.value
(self, solver=None)
7,578
hsbalance.tools
convert_matrix_to_cart
docs: Convert influence coeffecient matrix ALPHA from mathematical expression form to cartesian form. :ALPHA_math: list of lists with polar mathmematical expression ex . [[90@58, 21@140] [10.9@10, 37.9@142]] :returns: np.dnarray with cartesian form
def convert_matrix_to_cart(ALPHA_math): """ docs: Convert influence coeffecient matrix ALPHA from mathematical expression form to cartesian form. :ALPHA_math: list of lists with polar mathmematical expression ex . [[90@58, 21@140] [10.9@10, 37.9@142]] :returns: np.dnarray with cartesian form """ return convert_math_cart(ALPHA_math)
(ALPHA_math)
7,579
hsbalance.tools
convert_matrix_to_math
inverse of convert_matrix_to_cart
def convert_matrix_to_math(matrix): """ inverse of convert_matrix_to_cart """ return convert_cart_math(matrix)
(matrix)
7,580
hsbalance.tools
convert_to_cartesian
docs: Convert number from polar form to cartesian complex number. :inputs: polar: Complex number in polar form (modulus, phase in degrees) ex.(12, 90) -> <class 'tuple'> output: Complex number in cartesian number ex. 12+23j -> <class 'complex'>
def convert_to_cartesian(polar): ''' docs: Convert number from polar form to cartesian complex number. :inputs: polar: Complex number in polar form (modulus, phase in degrees) ex.(12, 90) -> <class 'tuple'> output: Complex number in cartesian number ex. 12+23j -> <class 'complex'> ''' theta = polar[1] * cm.pi / 180 return complex(polar[0]*cm.cos(theta), polar[0] * cm.sin(theta))
(polar)
7,581
hsbalance.tools
convert_to_polar
docs: Convert complex number in the cartesian form into polar form. :inputs: cart: Complex number in cartesian number ex. 12+23j -> <class 'complex'> output: Complex number in polar form (modulus, phase in degrees) ex.(12, 90) -> <class 'tuple'>
def convert_to_polar(cart): ''' docs: Convert complex number in the cartesian form into polar form. :inputs: cart: Complex number in cartesian number ex. 12+23j -> <class 'complex'> output: Complex number in polar form (modulus, phase in degrees) ex.(12, 90) -> <class 'tuple'> ''' phase = cm.phase(cart) * 180 / cm.pi if phase<0: phase= phase+360 return (abs(cart), phase)
(cart)
7,583
hsbalance.tools
ill_condition
null
def ill_condition(alpha): # Checking ILL-CONDITIONED planes # Using the algorithm as in Darlow `Balancing of High Speed Machinery 1989 chapter 6` # Find the norm of the influence matrix columns alpha_value = alpha.copy() U = np.linalg.norm(alpha_value, axis = 0) # arrange the influence matrix by the magnitude of the norm (descending) index = np.argsort(U)[::-1] alpha_arranged_by_column_norm = alpha_value[:, index] def u(i): ''' returns column vector by index i in alpha_arranged_by_column_norm ''' return alpha_arranged_by_column_norm[:, i, np.newaxis] def normalized(vector): ''' Normalize vector = vector / norm(vector) Arg: vector -> complex of vector returns: normalized vector ''' return vector / np.linalg.norm(vector) sf =[] # Significance Factor # find e = u/norm(u) e = normalized(u(0)) sigma = (np.conjugate(e).T @ u(1)) * e for i in range(0, len(index)-1): # find v1 = u1 - (conjugate(e0).T * u2)e1 v = u(i+1) - sigma # sf1 = norm(v1) / norm(u1) sf.append(np.linalg.norm(v) / np.linalg.norm(u(i+1))) # calculate e1 = v2 / norm(v2) e = normalized(v) sigma += (np.conjugate(e).T @ u(i+1)) * e ill_plane = [] for i, factor in enumerate(sf): if factor <= 0.2: ill_plane.append(index[i+1]) return ill_plane
(alpha)
7,589
hsbalance.tools
residual_vibration
Calculate the residual vibration between ALPHA matrix and solution W with intial vibration A Args: ALPHA : Influence coefficient matrix -> np.array A : Initial vibration column array -> np.array W : Solution balancing weight row vector -> np.array Return: residual_vibration column array -> np.array
def residual_vibration(ALPHA, W, A): ''' Calculate the residual vibration between ALPHA matrix and solution W with intial vibration A Args: ALPHA : Influence coefficient matrix -> np.array A : Initial vibration column array -> np.array W : Solution balancing weight row vector -> np.array Return: residual_vibration column array -> np.array ''' return ALPHA @ W + A
(ALPHA, W, A)
7,590
hsbalance.tools
rmse
Calculate the root mean square error for residual_vibration column matrix subtract each residual vibration from zero and taking the square root of the summation, rounding the result to the fourth decimal point Args: residual_vibration: numpy array Return: RMSE deviated from 0
def rmse(residual_vibration): ''' Calculate the root mean square error for residual_vibration column matrix subtract each residual vibration from zero and taking the square root of the summation, rounding the result to the fourth decimal point Args: residual_vibration: numpy array Return: RMSE deviated from 0 ''' return round(np.sqrt(np.abs(residual_vibration) ** 2).mean(), 4)
(residual_vibration)
7,613
pypsrp
_setup_logging
null
def _setup_logging(logger: logging.Logger) -> None: log_path = os.environ.get("PYPSRP_LOG_CFG", None) if log_path is not None and os.path.exists(log_path): # pragma: no cover # log log config from JSON file with open(log_path, "rt") as f: config = json.load(f) logging.config.dictConfig(config) else: # no logging was provided logger.addHandler(NullHandler())
(logger: logging.Logger) -> NoneType
7,617
emmett.app
App
null
class App: __slots__ = [ '__dict__', '_asgi_handlers', '_extensions_env', '_extensions_listeners', '_language_default', '_language_force_on_url', '_languages_set', '_languages', '_logger', '_modules', '_pipeline', '_router_http', '_router_ws', 'cli', 'config_path', 'config', 'error_handlers', 'ext', 'import_name', 'logger_name', 'root_path', 'static_path', 'template_default_extension', 'template_path', 'templater', 'translator' ] debug = None test_client_class = None def __init__( self, import_name: str, root_path: Optional[str] = None, url_prefix: Optional[str] = None, template_folder: str = 'templates', config_folder: str = 'config' ): self.import_name = import_name #: init debug var self.debug = os.environ.get('EMMETT_RUN_ENV') == "true" #: set paths for the application if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self.static_path = os.path.join(self.root_path, "static") self.template_path = os.path.join(self.root_path, template_folder) self.config_path = os.path.join(self.root_path, config_folder) #: the click command line context for this application self.cli = click.Group(self.import_name) #: init the configuration self.config = Config(self) #: try to create needed folders create_missing_app_folders(self) #: init languages self._languages: List[str] = [] self._languages_set: Set[str] = set() self._language_default: Optional[str] = None self._language_force_on_url = False self.translator = Translator( os.path.join(self.root_path, 'languages'), default_language=self.language_default or 'en', watch_changes=self.debug, str_class=Tstr ) #: init routing self._pipeline: List[Pipe] = [] self._router_http = HTTPRouter(self, url_prefix=url_prefix) self._router_ws = WebsocketRouter(self, url_prefix=url_prefix) self._asgi_handlers = { 'http': asgi_handlers.HTTPHandler(self), 'lifespan': asgi_handlers.LifeSpanHandler(self), 'websocket': asgi_handlers.WSHandler(self) } self._rsgi_handlers = { 'http': rsgi_handlers.HTTPHandler(self), 'ws': rsgi_handlers.WSHandler(self) } self.error_handlers: Dict[int, Callable[[], Awaitable[str]]] = {} self.template_default_extension = '.html' #: init logger self._logger = None self.logger_name = self.import_name #: init extensions self.ext: sdict[str, Extension] = sdict() self._extensions_env: sdict[str, Any] = sdict() self._extensions_listeners: Dict[str, List[Callable[..., Any]]] = { element.value: [] for element in Signals } #: init templater self.templater: Templater = Templater( path=self.template_path, encoding=self.config.templates_encoding, escape=self.config.templates_escape, adjust_indent=self.config.templates_adjust_indent, reload=self.config.templates_auto_reload ) #: finalise self._modules: Dict[str, AppModule] = {} current.app = self def _configure_asgi_handlers(self): self._asgi_handlers['http']._configure_methods() self._rsgi_handlers['http']._configure_methods() @cachedprop def name(self): if self.import_name == '__main__': fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: rv = '__main__' else: rv = os.path.splitext(os.path.basename(fn))[0] else: rv = self.import_name return rv @property def languages(self) -> List[str]: return self._languages @languages.setter def languages(self, value: List[str]): self._languages = value self._languages_set = set(self._languages) @property def language_default(self) -> Optional[str]: return self._language_default @language_default.setter def language_default(self, value: str): self._language_default = value self.translator._update_config(self._language_default or 'en') @property def language_force_on_url(self) -> bool: return self._language_force_on_url @language_force_on_url.setter def language_force_on_url(self, value: bool): self._language_force_on_url = value self._router_http._set_language_handling() self._router_ws._set_language_handling() self._configure_asgi_handlers() @property def pipeline(self) -> List[Pipe]: return self._pipeline @pipeline.setter def pipeline(self, pipes: List[Pipe]): self._pipeline = pipes self._router_http.pipeline = self._pipeline self._router_ws.pipeline = self._pipeline @property def injectors(self) -> List[Injector]: return self._router_http.injectors @injectors.setter def injectors(self, injectors: List[Injector]): self._router_http.injectors = injectors def route( self, paths: Optional[Union[str, List[str]]] = None, name: Optional[str] = None, template: Optional[str] = None, pipeline: Optional[List[Pipe]] = None, injectors: Optional[List[Injector]] = None, schemes: Optional[Union[str, List[str]]] = None, hostname: Optional[str] = None, methods: Optional[Union[str, List[str]]] = None, prefix: Optional[str] = None, template_folder: Optional[str] = None, template_path: Optional[str] = None, cache: Optional[RouteCacheRule] = None, output: str = 'auto' ) -> RoutingCtx: if callable(paths): raise SyntaxError('Use @route(), not @route.') return self._router_http( paths=paths, name=name, template=template, pipeline=pipeline, injectors=injectors, schemes=schemes, hostname=hostname, methods=methods, prefix=prefix, template_folder=template_folder, template_path=template_path, cache=cache, output=output ) def websocket( self, paths: Optional[Union[str, List[str]]] = None, name: Optional[str] = None, pipeline: Optional[List[Pipe]] = None, schemes: Optional[Union[str, List[str]]] = None, hostname: Optional[str] = None, prefix: Optional[str] = None ) -> RoutingCtx: if callable(paths): raise SyntaxError('Use @websocket(), not @websocket.') return self._router_ws( paths=paths, name=name, pipeline=pipeline, schemes=schemes, hostname=hostname, prefix=prefix ) def on_error(self, code: int) -> Callable[[ErrorHandlerType], ErrorHandlerType]: def decorator(f: ErrorHandlerType) -> ErrorHandlerType: self.error_handlers[code] = f return f return decorator @property def command(self): return self.cli.command @property def command_group(self): return self.cli.group @property def log(self) -> Logger: if self._logger and self._logger.name == self.logger_name: return self._logger from .logger import _logger_lock, create_logger with _logger_lock: if self._logger and self._logger.name == self.logger_name: return self._logger self._logger = rv = create_logger(self) return rv def render_template(self, filename: str) -> str: ctx = { 'current': current, 'url': url, 'asis': asis, 'load_component': load_component } return self.templater.render(filename, ctx) def config_from_yaml(self, filename: str, namespace: Optional[str] = None): #: import configuration from yaml files rc = read_file(os.path.join(self.config_path, filename)) rc = ymlload(rc, Loader=ymlLoader) c = self.config if namespace is None else self.config[namespace] for key, val in rc.items(): c[key] = dict_to_sdict(val) #: Register modules def _register_module(self, mod: AppModule): self._modules[mod.name] = mod #: Creates the extensions' environments and configs def __init_extension(self, ext): if ext.namespace is None: ext.namespace = ext.__name__ if self._extensions_env[ext.namespace] is None: self._extensions_env[ext.namespace] = sdict() return self._extensions_env[ext.namespace], self.config[ext.namespace] #: Register extension listeners def __register_extension_listeners(self, ext): for signal, listener in ext._listeners_: self._extensions_listeners[signal].append(listener) #: Add an extension to application def use_extension(self, ext_cls: Type[ExtensionType]) -> ExtensionType: if not issubclass(ext_cls, Extension): raise RuntimeError( f'{ext_cls.__name__} is an invalid Emmett extension' ) ext_env, ext_config = self.__init_extension(ext_cls) ext = self.ext[ext_cls.__name__] = ext_cls(self, ext_env, ext_config) self.__register_extension_listeners(ext) ext.on_load() return ext #: Add a template extension to application def use_template_extension(self, ext_cls, **config): return self.templater.use_extension(ext_cls, **config) def send_signal(self, signal: Union[str, Signals], *args, **kwargs): if not isinstance(signal, Signals): warn_of_deprecation( "App.send_signal str argument", "extensions.Signals as argument", stack=3 ) try: signal = Signals[signal] except KeyError: raise SyntaxError(f"{signal} is not a valid signal") for listener in self._extensions_listeners[signal]: listener(*args, **kwargs) def make_shell_context(self, context: Dict[str, Any] = {}) -> Dict[str, Any]: context['app'] = self return context def test_client(self, use_cookies: bool = True, **kwargs) -> EmmettTestClient: tclass = self.test_client_class or EmmettTestClient return tclass(self, use_cookies=use_cookies, **kwargs) def __call__(self, scope, receive, send): return self._asgi_handlers[scope['type']](scope, receive, send) def __rsgi__(self, scope, protocol): return self._rsgi_handlers[scope.proto](scope, protocol) def __rsgi_init__(self, loop): self.send_signal(Signals.after_loop, loop=loop) def module( self, import_name: str, name: str, template_folder: Optional[str] = None, template_path: Optional[str] = None, static_folder: Optional[str] = None, static_path: Optional[str] = None, url_prefix: Optional[str] = None, hostname: Optional[str] = None, cache: Optional[RouteCacheRule] = None, root_path: Optional[str] = None, pipeline: Optional[List[Pipe]] = None, injectors: Optional[List[Injector]] = None, module_class: Optional[Type[AppModule]] = None, **kwargs: Any ) -> AppModule: module_class = module_class or self.config.modules_class return module_class.from_app( self, import_name, name, template_folder=template_folder, template_path=template_path, static_folder=static_folder, static_path=static_path, url_prefix=url_prefix, hostname=hostname, cache=cache, root_path=root_path, pipeline=pipeline or [], injectors=injectors or [], opts=kwargs ) def module_group(self, *modules: AppModule) -> AppModuleGroup: return AppModuleGroup(*modules)
(import_name: 'str', root_path: 'Optional[str]' = None, url_prefix: 'Optional[str]' = None, template_folder: 'str' = 'templates', config_folder: 'str' = 'config')
7,618
emmett.app
__init_extension
null
def __init_extension(self, ext): if ext.namespace is None: ext.namespace = ext.__name__ if self._extensions_env[ext.namespace] is None: self._extensions_env[ext.namespace] = sdict() return self._extensions_env[ext.namespace], self.config[ext.namespace]
(self, ext)
7,619
emmett.app
__register_extension_listeners
null
def __register_extension_listeners(self, ext): for signal, listener in ext._listeners_: self._extensions_listeners[signal].append(listener)
(self, ext)
7,620
emmett.app
__call__
null
def __call__(self, scope, receive, send): return self._asgi_handlers[scope['type']](scope, receive, send)
(self, scope, receive, send)
7,621
emmett.app
__init__
null
def __init__( self, import_name: str, root_path: Optional[str] = None, url_prefix: Optional[str] = None, template_folder: str = 'templates', config_folder: str = 'config' ): self.import_name = import_name #: init debug var self.debug = os.environ.get('EMMETT_RUN_ENV') == "true" #: set paths for the application if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self.static_path = os.path.join(self.root_path, "static") self.template_path = os.path.join(self.root_path, template_folder) self.config_path = os.path.join(self.root_path, config_folder) #: the click command line context for this application self.cli = click.Group(self.import_name) #: init the configuration self.config = Config(self) #: try to create needed folders create_missing_app_folders(self) #: init languages self._languages: List[str] = [] self._languages_set: Set[str] = set() self._language_default: Optional[str] = None self._language_force_on_url = False self.translator = Translator( os.path.join(self.root_path, 'languages'), default_language=self.language_default or 'en', watch_changes=self.debug, str_class=Tstr ) #: init routing self._pipeline: List[Pipe] = [] self._router_http = HTTPRouter(self, url_prefix=url_prefix) self._router_ws = WebsocketRouter(self, url_prefix=url_prefix) self._asgi_handlers = { 'http': asgi_handlers.HTTPHandler(self), 'lifespan': asgi_handlers.LifeSpanHandler(self), 'websocket': asgi_handlers.WSHandler(self) } self._rsgi_handlers = { 'http': rsgi_handlers.HTTPHandler(self), 'ws': rsgi_handlers.WSHandler(self) } self.error_handlers: Dict[int, Callable[[], Awaitable[str]]] = {} self.template_default_extension = '.html' #: init logger self._logger = None self.logger_name = self.import_name #: init extensions self.ext: sdict[str, Extension] = sdict() self._extensions_env: sdict[str, Any] = sdict() self._extensions_listeners: Dict[str, List[Callable[..., Any]]] = { element.value: [] for element in Signals } #: init templater self.templater: Templater = Templater( path=self.template_path, encoding=self.config.templates_encoding, escape=self.config.templates_escape, adjust_indent=self.config.templates_adjust_indent, reload=self.config.templates_auto_reload ) #: finalise self._modules: Dict[str, AppModule] = {} current.app = self
(self, import_name: str, root_path: Optional[str] = None, url_prefix: Optional[str] = None, template_folder: str = 'templates', config_folder: str = 'config')
7,622
emmett.app
__rsgi__
null
def __rsgi__(self, scope, protocol): return self._rsgi_handlers[scope.proto](scope, protocol)
(self, scope, protocol)
7,623
emmett.app
__rsgi_init__
null
def __rsgi_init__(self, loop): self.send_signal(Signals.after_loop, loop=loop)
(self, loop)
7,624
emmett.app
_configure_asgi_handlers
null
def _configure_asgi_handlers(self): self._asgi_handlers['http']._configure_methods() self._rsgi_handlers['http']._configure_methods()
(self)
7,625
emmett.app
_register_module
null
def _register_module(self, mod: AppModule): self._modules[mod.name] = mod
(self, mod: emmett.app.AppModule)