eth_account

Account

class eth_account.account.Account

The primary entry point for working with Ethereum private keys.

It does not require a connection to an Ethereum node.

create(extra_entropy='')

Creates a new private key, and returns it as a LocalAccount.

Parameters:extra_entropy (str or bytes or int) – Add extra randomness to whatever randomness your OS can provide
Returns:an object with private key and convenience methods
>>> from eth_account import Account
>>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
>>> acct.address
'0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
>>> acct.key
b"\xb2\}\xb3\x1f\xee\xd9\x12''\xbf\t9\xdcv\x9a\x96VK-\xe4\xc4rm\x03[6\xec\xf1\xe5\xb3d"

# 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
static decrypt(keyfile_json, password)

Decrypts a private key that was encrypted using an Ethereum client or encrypt().

Parameters:
  • keyfile_json (dict or str) – The encrypted key
  • password (str) – The password that was used to encrypt the key
Returns:

the raw private key

Return type:

HexBytes

>>> encrypted = {
 'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
 'crypto': {'cipher': 'aes-128-ctr',
  'cipherparams': {'iv': '78f214584844e0b241b433d7c3bb8d5f'},
  'ciphertext': 'd6dbb56e4f54ba6db2e8dc14df17cb7352fdce03681dd3f90ce4b6c1d5af2c4f',
  'kdf': 'pbkdf2',
  'kdfparams': {'c': 1000000,
   'dklen': 32,
   'prf': 'hmac-sha256',
   'salt': '45cf943b4de2c05c2c440ef96af914a2'},
  'mac': 'f5e1af09df5ded25c96fcf075ada313fb6f79735a914adc8cb02e8ddee7813c3'},
 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0',
 'version': 3}

>>> import getpass
>>> Account.decrypt(encrypted, getpass.getpass())
HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364')
classmethod encrypt(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 json.dumps() and save it to disk where your client keeps key files.

Parameters:
  • private_key (hex str, bytes, int or eth_keys.datatypes.PrivateKey) – The raw private key
  • password (str) – The password which you will need to unlock the account in your client
  • kdf (str) – The key derivation function to use when encrypting your private key
  • iterations (int) – The work factor for the key derivation function
Returns:

The data to use in your encrypted file

Return type:

dict

If kdf is not set, the default key derivation function falls back to the environment variable ETH_ACCOUNT_KDF. If that is not set, then ‘scrypt’ will be used as the default.

>>> import getpass
>>> encrypted = Account.encrypt(
    0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364,
    getpass.getpass()
)

{
    'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
    'crypto': {
        'cipher': 'aes-128-ctr',
        'cipherparams': {
            'iv': '0b7845a5c3597d3d378bde9b7c7319b7'
        },
        'ciphertext': 'a494f1feb3c854e99c1ff01e6aaa17d43c0752009073503b908457dc8de5d2a5',  # noqa: E501
        'kdf': 'scrypt',
        'kdfparams': {
            'dklen': 32,
            'n': 262144,
            'p': 8,
            'r': 1,
            'salt': '13c4a48123affaa29189e9097726c698'
        },
        'mac': 'f4cfb027eb0af9bd7a320b4374a3fa7bef02cfbafe0ec5d1fd7ad129401de0b1'
    },
    'id': 'a60e0578-0e5b-4a75-b991-d55ec6451a6f',
    'version': 3
}

 >>> with open('my-keyfile', 'w') as f:
     f.write(json.dumps(encrypted))
from_key(private_key)

Returns a convenient object for working with the given private key.

Parameters:private_key (hex str, bytes, int or eth_keys.datatypes.PrivateKey) – The raw private key
Returns:object with methods for signing and encrypting
Return type:LocalAccount
>>> acct = Account.from_key(
  0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364)
>>> acct.address
'0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
>>> acct.key
b"\xb2\}\xb3\x1f\xee\xd9\x12''xbf\t9\xdcv\x9a\x96VK-\xe4\xc4rm\x03[6\xec\xf1\xe5\xb3d"

# 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
privateKeyToAccount(private_key)

Caution

Deprecated for from_key(). This method will be removed in v0.5

recoverHash(message_hash, vrs=None, signature=None)

Get the address of the account that signed the message with the given hash. You must specify exactly one of: vrs or signature

Caution

Deprecated for recover_message(). This method might be removed as early as v0.5

Parameters:
  • message_hash (hex str or bytes or int) – the hash of the message that you want to verify
  • vrs (tuple(v, r, s), each element is hex str, bytes or int) – the three pieces generated by an elliptic curve signature
  • signature (hex str or bytes or int) – signature bytes concatenated as r+s+v
Returns:

address of signer, hex-encoded & checksummed

Return type:

str

recoverTransaction(serialized_transaction)

Caution

Deprecated for recover_transaction(). This method will be removed in v0.5

recover_message(signable_message: eth_account.messages.SignableMessage, vrs=None, signature=None)

Get the address of the account that signed the given message. You must specify exactly one of: vrs or signature

Parameters:
  • signable_message – the message that was signed
  • vrs (tuple(v, r, s), each element is hex str, bytes or int) – the three pieces generated by an elliptic curve signature
  • signature (hex str or bytes or int) – signature bytes concatenated as r+s+v
Returns:

address of signer, hex-encoded & checksummed

Return type:

str

>>> from eth_account.messages import encode_defunct
>>> 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)
>>> 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',  # noqa: E501
      b'>[\\xfb\\xbfM>9\\xb1\\xa2\\xfd\\x81jv\\x80\\xc1\\x9e\\xbe\\xba\\xf3\\xa1A\\xb29\\x93J\\xd4<\\xb3?\\xce\\xc8\\xce')  # noqa: E501
>>> Account.recover_message(message, vrs=vrs)
>>> # Caution about this approach: likely problems if there are leading 0s
>>> vrs = (
      0x1c,
      0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3,
      0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce)
>>> Account.recover_message(message, vrs=vrs)

# variations on signature
>>> signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c'  # noqa: E501
>>> Account.recover_message(message, signature=signature)
>>> 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'  # noqa: E501
>>> Account.recover_message(message, signature=signature)
>>> # Caution about this approach: likely problems if there are leading 0s
>>> signature = 0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c  # noqa: E501
>>> Account.recover_message(message, signature=signature)
recover_transaction(serialized_transaction)

Get the address of the account that signed this transaction.

Parameters:serialized_transaction (hex str, bytes or int) – the complete signed transaction
Returns:address of signer, hex-encoded & checksummed
Return type:str
>>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',  # noqa: E501
>>> Account.recover_transaction(raw_transaction)
'0x2c7536E3605D9C16a7a3D7b1898e529396a65c23'
setKeyBackend(backend)

Caution

Deprecated for set_key_backend(). This method will be removed in v0.5

set_key_backend(backend)

Change the backend used by the underlying eth-keys library.

(The default is fine for most users)

Parameters:backend – any backend that works in eth_keys.KeyApi(backend)
signHash(message_hash, private_key)

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 sign_message(), which cannot accidentally sign a transaction.

Sign the provided hash.

Caution

Deprecated for sign_message(). This method will be removed in v0.5

Parameters:
  • message_hash (hex str, bytes or int) – the 32-byte message hash to be signed
  • private_key (hex str, bytes, int or eth_keys.datatypes.PrivateKey) – the key to sign the message with
Returns:

Various details about the signature - most importantly the fields: v, r, and s

Return type:

AttributeDict

signTransaction(transaction_dict, private_key)

Caution

Deprecated for sign_transaction(). This method will be removed in v0.5

sign_message(signable_message: eth_account.messages.SignableMessage, private_key)

Sign the provided message.

This API supports any messaging format that will encode to EIP-191 messages.

If you would like historical compatibility with w3.eth.sign() you can use encode_defunct().

Other options are the “validator”, or “structured data” standards. (Both of these are in DRAFT status currently, so be aware that the implementation is not guaranteed to be stable). You can import all supported message encoders in eth_account.messages.

Parameters:
  • signable_message – the encoded message for signing
  • private_key (hex str, bytes, int or eth_keys.datatypes.PrivateKey) – the key to sign the message with
Returns:

Various details about the signature - most importantly the fields: v, r, and s

Return type:

AttributeDict

>>> msg = "I♥SF"
>>> from eth_account.messages import encode_defunct
>>> msghash = encode_defunct(text=msg)
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)
{'messageHash': HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'),  # noqa: E501
 'r': 104389933075820307925104709181714897380569894203213074526835978196648170704563,
 's': 28205917190874851400050446352651915501321657673772411533993420917949420456142,
 'signature': HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c'),  # noqa: E501
 'v': 28}
sign_transaction(transaction_dict, private_key)

Sign a transaction using a local private key. Produces signature details and the hex-encoded transaction suitable for broadcast using w3.eth.sendRawTransaction().

Create the transaction dict for a contract method with my_contract.functions.my_function().buildTransaction()

Parameters:
  • transaction_dict (dict) – the transaction with keys: nonce, chainId, to, data, value, gas, and gasPrice.
  • private_key (hex str, bytes, int or eth_keys.datatypes.PrivateKey) – the private key to sign the data with
Returns:

Various details about the signature - most importantly the fields: v, r, and s

Return type:

AttributeDict

>>> transaction = {
        # Note that the address must be in checksum format or native bytes:
        'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
        'value': 1000000000,
        'gas': 2000000,
        'gasPrice': 234567897654321,
        'nonce': 0,
        'chainId': 1
    }
>>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'
>>> signed = Account.sign_transaction(transaction, key)
{'hash': HexBytes('0x6893a6ee8df79b0f5d64a180cd1ef35d030f3e296a5361cf04d02ce720d32ec5'),
 'r': 4487286261793418179817841024889747115779324305375823110249149479905075174044,
 'rawTransaction': HexBytes('0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428'),  # noqa: E501
 's': 30785525769477805655994251009256770582792548537338581640010273753578382951464,
 'v': 37}
>>> w3.eth.sendRawTransaction(signed.rawTransaction)

See Signers for alternative signers.

AttributeDict

class eth_account.datastructures.AttributeDict(*args, **kwargs)

Bases: attrdict.dictionary.AttrDict

See AttrDict docs

This class differs only in that it is made immutable. This immutability is not a security guarantee. It is only a style-check convenience.

Messages

class eth_account.messages.SignableMessage

Bases: tuple

These are the components of an EIP-191 signable message. Other message formats can be encoded into this format for easy signing. This data structure doesn’t need to know about the original message format.

In typical usage, you should never need to create these by hand. Instead, use one of the available encode_* methods in this module, like:

body

Alias for field number 2

header

Alias for field number 1

version

Alias for field number 0

eth_account.messages.defunct_hash_message(primitive: bytes = None, *, hexstr: str = None, text: str = None) → hexbytes.main.HexBytes

Convert the provided message into a message hash, to be signed.

Caution

Intented for use with the deprecated eth_account.account.Account.signHash(). This is for backwards compatibility only. All new implementations should use encode_defunct() instead.

Parameters:
  • primitive (bytes or int) – the binary message to be signed
  • hexstr (str) – the message encoded as hex
  • text (str) – the message as a series of unicode characters (a normal Py3 str)
Returns:

The hash of the message, after adding the prefix

eth_account.messages.encode_defunct(primitive: bytes = None, *, hexstr: str = None, text: str = None) → eth_account.messages.SignableMessage

Encode a message for signing, using an old, unrecommended approach.

Only use this method if you must have compatibility with w3.eth.sign().

EIP-191 defines this as “version E”.

Supply exactly one of the three arguments: bytes, a hex string, or a unicode string.

Parameters:
  • primitive (bytes or int) – the binary message to be signed
  • hexstr (str) – the message encoded as hex
  • text (str) – the message as a series of unicode characters (a normal Py3 str)
Returns:

The EIP-191 encoded message, ready for signing

>>> from eth_account.messages import encode_defunct

>>> message_text = "I♥SF"
>>> encode_defunct(text=message_text)
SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF')

# these four also produce the same hash:
>>> encode_defunct(w3.toBytes(text=message_text))
SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF')

>>> encode_defunct(bytes(message_text, encoding='utf-8'))
SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF')

>>> Web3.toHex(text=message_text)
'0x49e299a55346'
>>> encode_defunct(hexstr='0x49e299a55346')
SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF')

>>> encode_defunct(0x49e299a55346)
SignableMessage(version=b'E', header=b'thereum Signed Message:\n6', body=b'I\xe2\x99\xa5SF')
eth_account.messages.encode_intended_validator(validator_address: Union[NewType.<locals>.new_type, str], primitive: bytes = None, *, hexstr: str = None, text: str = None) → eth_account.messages.SignableMessage

Encode a message using the “intended validator” approach (ie~ version 0) defined in EIP-191.

Supply the message as exactly one of these three arguments: bytes as a primitive, a hex string, or a unicode string.

Warning

Note that this code has not gone through an external audit. Also, watch for updates to the format, as the EIP is still in DRAFT.

Parameters:
  • validator_address – which on-chain contract is capable of validating this message, provided as a checksummed address or in native bytes.
  • primitive (bytes or int) – the binary message to be signed
  • hexstr (str) – the message encoded as hex
  • text (str) – the message as a series of unicode characters (a normal Py3 str)
Returns:

The EIP-191 encoded message, ready for signing

eth_account.messages.encode_structured_data(primitive: Union[bytes, int, collections.abc.Mapping] = None, *, hexstr: str = None, text: str = None) → eth_account.messages.SignableMessage

Encode a message using the “structured data” approach (ie~ version 1) defined in EIP-712.

Supply the message as exactly one of the three arguments:

  • primitive, as a dict that defines the structured data
  • primitive, as bytes
  • text, as a json-encoded string
  • hexstr, as a hex-encoded (json-encoded) string

Warning

Note that this code has not gone through an external audit. Also, watch for updates to the format, as the EIP is still in DRAFT.

Parameters:
  • primitive (bytes or int or Mapping (eg~ dict )) – the binary message to be signed
  • hexstr – the message encoded as hex
  • text – the message as a series of unicode characters (a normal Py3 str)
Returns:

The EIP-191 encoded message, ready for signing