cfx_account
cfx_account¶
-
class
cfx_account.account.
Account
[source]¶ -
create
(extra_entropy: str = '', network_id: Optional[int] = None) → cfx_account.signers.local.LocalAccount[source]¶ Creates a new private key, and returns it as a
LocalAccount
.- Parameters
extra_entropy (str) – Add extra randomness to the randomness provided by your OS, defaults to ‘’
network_id (Optional[int]) – the network id of the generated account, which determines the address encoding, defaults to None
- Return LocalAccount
an object with private key and convenience methods
- Examples
>>> from cfx_account import Account >>> acct = Account.create() >>> acct.address '0x187EE3Cb948fFb5a34417344f7fA01c638aa2F96' >>> Account.create(network_id=1029).address 'cfx:aapapvutg83zauuexwdrgjp4v6xm3dkbm2vevh1rub'
-
create_with_mnemonic
(passphrase: str = '', num_words: int = 12, language: str = 'english', account_path: str = "m/44'/503'/0'/0/0", network_id: Optional[int] = None) → Tuple[cfx_account.signers.local.LocalAccount, str][source]¶ Create mnemonic and derive an account using parameters
- Parameters
passphrase (str) – Extra passphrase to encrypt the seed phrase, defaults to “”
num_words (int) – Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24].
language (str) – Language to use for BIP39 mnemonic seed phrase, defaults to “english”
account_path (str) – Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation, defaults to CONFLUX_DEFAULT_PATH(m/44’/503’/0’/0/0)
network_id (Optional[int]) – the network id of returned account, defaults to None
- Return Tuple[LocalAccount, str]
a LocalAccount object and related mnemonic
-
static
decrypt
(keyfile_json: Union[Dict[str, Any], str, cfx_account.types.KeyfileDict], password: str) → hexbytes.main.HexBytes[source]¶ Decrypts a keyfile and returns the secret key.
- Parameters
keyfile_json (Union[Dict[str,Any],str,KeyfileDict]) – encrypted keyfile
password (str) – the password that was used to encrypt the key
- Return HexBytes
the hex private key
-
classmethod
encrypt
(private_key: Union[bytes, str, eth_keys.datatypes.PrivateKey], password: str, kdf: Optional[typing_extensions.Literal[scrypt, pbkdf2]] = None, iterations: Optional[int] = None) → cfx_account.types.KeyfileDict[source]¶ 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 keypassword (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.>>> 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': 8, 'r': 1, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: ... f.write(json.dumps(encrypted))
-
from_key
(private_key: Union[bytes, str, eth_keys.datatypes.PrivateKey], network_id: Optional[int] = None) → cfx_account.signers.local.LocalAccount[source]¶ returns a LocalAccount object
- Parameters
private_key (str) – the raw private key
network_id (Optional[int]) – target network of the account, defaults to None
- Return LocalAccount
object with methods for signing and encrypting
>>> acct = Account.from_key( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364) >>> acct.address '0x1ce9454909639d2d17a3f753ce7d93fa0b9ab12e' >>> 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_mnemonic
(mnemonic: str, passphrase: str = '', account_path: str = "m/44'/503'/0'/0/0", network_id: Optional[int] = None) → cfx_account.signers.local.LocalAccount[source]¶ Generate an account from a mnemonic.
- Parameters
mnemonic (str) – space-separated list of BIP39 mnemonic seed words
passphrase (str) – Optional passphrase used to encrypt the mnemonic, defaults to “”
account_path (str) – pecify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation, defaults to CONFLUX_DEFAULT_PATH(m/44’/503’/0’/0/0)
network_id (Optional[int]) – the network id of returned account, defaults to None
- Return LocalAccount
a LocalAccount object
- Examples
>>> from cfx_account import Account >>> acct = Account.from_mnemonic('faint also eye industry survey unhappy boil public lemon myself cube sense', network_id=1) >>> acct.address 'cfxtest:aargrnff46pmuy2g1mmrntctkhr5mzamh6nmg361n0'
-
recover_message
(signable_message: eth_account.messages.SignableMessage, vrs: Optional[Tuple[VRS, VRS, VRS]] = None, signature: Optional[bytes] = None) → ChecksumAddress[source]¶ Get the address of the account that signed the given message. Must specify exactly one of vrs or signature. Refer to
sign_message()
for usage examples.- Parameters
signable_message (SignableMessage) – an encoded message generated by encode_defunct or encode_structured_data
vrs (Optional[Tuple[VRS,VRS,VRS]]) – the three pieces generated by an elliptic curve signature, defaults to None
signature (Optional[bytes]) – signature bytes concatenated as r+s+v, defaults to None
- Return ChecksumAddress
the checksum address of the account that signed the given message
-
recover_transaction
(serialized_transaction: Union[bytes, HexStr, str]) → ChecksumAddress[source]¶ Get the address of the account that signed this transaction.
- Parameters
serialized_transaction (Union[bytes,HexStr,str]) – the complete signed transaction
- Return ChecksumAddress
address of signer, hex-encoded & checksummed
- Example
>>> raw_transaction = '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428' # noqa: E501 >>> Account.recover_transaction(raw_transaction) '0x1c7536e3605d9c16a7a3d7b1898e529396a65c23'
-
sign_message
(signable_message: eth_account.messages.SignableMessage, private_key: Union[bytes, HexStr, int, eth_keys.datatypes.PrivateKey]) → eth_account.datastructures.SignedMessage[source]¶ Sign the provided encoded message. The message is encoded according to CIP-23
- Parameters
signable_message (SignableMessage) – an encoded message generated by encode_defunct or encode_structured_data
private_key (Union[bytes,HexStr,int,keys.PrivateKey]) – the private key used to sign message
- Return SignedMessage
a signed message object
- Examples
>>> from from cfx_account import Account >>> from cfx_account.messages import encode_structured_data, encode_defunct >>> encoded_message = encode_defunct(text=message) >>> acct = Account.create() >>> signed = acct.sign_message(encoded_message) >>> signed.signature '0xd72ea2020802d6dfce0d49fc1d92a16b43baa58fc152d6f437d852a014e0c5740b3563375b0b844a835be4f1521b4ae2a691048622f70026e0470acc5351043a01' >>> assert acct.hex_address == Account.recover_message(encoded_message, signature=signed.signature)
>>> # https://github.com/Conflux-Chain/CIPs/blob/master/CIPs/cip-23.md#typed-data >>> typed_data = { "types": { "CIP23Domain": [ ... ] }, ... } >>> encoded_data = encode_structured_data(typed_data) >>> signed = acct.sign_message(encoded_data) >>> signed.signature '0xd7fb6dca3b084ae3a9bf1ea3527de7a9bc2bd40e0c38d3faf9da214f1d5637ab2944a8a993dc59365c1e74e18a1589b358e3fb81bd03892d159f221e8ac765c701' >>> assert acct.hex_address == Account.recover_message(encoded_data, signature=signed.signature)
-
sign_transaction
(transaction_dict: Union[cfx_utils.types.TxDict, Dict[str, Any]], private_key: Union[bytes, str, eth_keys.datatypes.PrivateKey]) → eth_account.datastructures.SignedTransaction[source]¶ Sign a transaction using a local private key. Produces signature details and the hex-encoded transaction suitable for broadcast using
w3.cfx.send_raw_transaction()
.Refer to Interact with a Contract to see how to sign for a contract method using build_transaction
- Parameters
transaction_dict (TxParam) – the transaction with keys: nonce, chainId, to, data, value, storageLimit, epochHeight, gas, and gasPrice.
private_key (Union[bytes,str,PrivateKey]) – private_key to be used for signing
- Raises
TypeError – transaction_dict is not a dict-like object
ValueError – transaction’s from field does not match private_key
- Return SignedTransaction
an attribute dict contains various details about the signature - most importantly the fields: v, r, and s
>>> transaction = { # Note that the address must be in Base32 format or native bytes: 'to': 'cfxtest:aak7fsws4u4yf38fk870218p1h3gxut3ku00u1k1da', 'nonce': 1, 'value': 1, 'gas': 100, 'gasPrice': 1, 'storageLimit': 100, 'epochHeight': 100, 'chainId': 1 } >>> key = '0xcc7939276283a32f60d2fad7d16cac972300308fe99ec98d0e63765d02e24863' >>> signed = Account.sign_transaction(transaction, key) {'hash': HexBytes('0x692a0ea530a264f4e80ce39f393233e90638ef929c8706802e15299fd0b042b9'), 'r': 74715349327018893060702835194036838027583623083228589573427622179540208747230, 'rawTransaction': HexBytes('0xf861dd0101649413d2ba4ed43542e7c54fbb6c5fccb9f269c1f94c016464018080a0a52f639cbed11262a7b88d0a37aef909aa7dc2c36c40689a3d52b8bd1d9482dea054f3bdeb654f73704db4cbc12451fb4c9830ef62b0f24de1a40e4b6fe10f57b2'), # noqa: E501 's': 38424933894051759888751352802050752143518665905311311986258635963723328477106, 'v': 0} >>> w3.cfx.sendRawTransaction(signed.rawTransaction)
-
w3
: Optional[Web3] = None¶
-
-
class
cfx_account.signers.local.
LocalAccount
(key: Any, account: Union[Account, Type[Account]], network_id: Optional[int] = None)[source]¶ Initialize a new account with the given private key.
- Parameters
key (eth_keys.PrivateKey) – to prefill in private key execution
account (Account) – the key-unaware management API
-
property
address
¶ Returns the address of the account.
- Return Union[Base32Address,ChecksumAddress]
Returns a Base32Address if network id is not None, else ChecksumAddress
-
encrypt
(password: str, kdf: Optional[typing_extensions.Literal[scrypt, pbkdf2]] = None, iterations: Optional[int] = None) → cfx_account.types.KeyfileDict[source]¶ This uses the same structure as in
encrypt()
, but without a private key argument.
-
get_base32_address
(specific_network_id: int) → cfx_address.address.Base32Address[source]¶ Returns the Base32Address of the account in specific network without changing the account network id
- Parameters
specific_network_id (int) – the network id of the target network
- Return Base32Address
-
property
hex_address
¶ Returns the hex address of the account.
- Return ChecksumAddress
the hex address in checksum format
-
property
key
¶ Get the private key.
-
property
network_id
¶ The network id of the account, which determines its address. Can be set using a positive int or None
- Return Union[int, None]
the network id of the account, 1029 for mainnet and 1 for testnet
- Examples
>>> from cfx_account import Account >>> acct = Account.create() >>> assert acct.network_id is None >>> acct.address '0x1261D876E5C589Bc26248c53C68b71c2d28470e9' >>> acct.network_id = 1 >>> acct.address 'cfxtest:aakgd0d061c2xtbgewgfhvynshbrfbdu7e55kdxfxx'
-
sign_message
(signable_message: eth_account.messages.SignableMessage) → eth_account.datastructures.SignedMessage[source]¶ This uses the same structure as in
sign_message()
, but without a private key argument.
-
sign_transaction
(transaction_dict: Union[cfx_utils.types.TxDict, Dict[str, Any]]) → eth_account.datastructures.SignedTransaction[source]¶ This uses the same structure as in
sign_transaction()
, but without a private key argument.