- Convert BIP-39 mnemonic to Ethereum private key in Python
- 1 Answer 1
- Create an Account on TestNet with Python
- Requirements
- Background
- Steps
- 1. Generate an Algorand Key Pair.
- 2. Retrieve the Private Key Mnemonic
- 3. Send Algos to the New Account
- 4. Completed Code
- 5. Check Your Balance
- Blockthon 7.6.9
- Навигация
- Ссылки проекта
- Статистика
- Метаданные
- Сопровождающие
- Классификаторы
- Описание проекта
- Blockthon
- Private Key
- Mnemonic
- Bytes (seed)
- Binary
- Private Key To Bytes
- Private Key To Wif
- Private Key To Mnemonic
- Private Key To Binary
- Private Key To Decimal (int)
- Private Key To RIPEMD160
- Private Key To Address
- Private Key To Public Key
- Bytes To Private Key
- Bytes To Wif
- Bytes To Public Key
- Bytes to Dec (number)
- Wif To Public Key
- Wif To Mnemonic
- Wif To RIPEMD160
- Mnemonic To Private key
- Mnemonic To Address
- Passphrase To Private Key
- Passphrase to Wif
- How to create a Ethereum Address with Python
- Mnemonic Phrase
- Dependencies
- Create a Wallet
- Retrieve the Private Key from Mnemonic
- Thank You
Convert BIP-39 mnemonic to Ethereum private key in Python
How do I convert a BIP-39 mnemonic to an Ethereum private key in Python (via BIP-44 key derivation)? All the libraries I found that gave me the intended result depend on the two1 package, which conflicts with modern versions of requests , which is a non-starter. I found https://github.com/vergl4s/ethereum-mnemonic-utils/, which produces a private key, but it’s incorrect (or at least it does not match what is derived by https://iancoleman.io/bip39/ and the truffle-hdwallet-provider node packages).
1 Answer 1
I realized my error: https://github.com/vergl4s/ethereum-mnemonic-utils works, but the full derivation path I was looking for is m/44’/60’/0’/0/0 (note the extra /0 to select the first account). Here is a full example:
#!/usr/bin/env python3 ''' MIT License Copyright (c) 2018 Luis Teixeira Copyright (c) 2019 Niklas Baumstark Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import binascii, hashlib, hmac, struct from ecdsa.curves import SECP256k1 from eth_utils import to_checksum_address, keccak as eth_utils_keccak BIP39_PBKDF2_ROUNDS = 2048 BIP39_SALT_MODIFIER = "mnemonic" BIP32_PRIVDEV = 0x80000000 BIP32_CURVE = SECP256k1 BIP32_SEED_MODIFIER = b'Bitcoin seed' ETH_DERIVATION_PATH = "m/44'/60'/0'/0" class PublicKey: def __init__(self, private_key): self.point = int.from_bytes(private_key, byteorder='big') * BIP32_CURVE.generator def __bytes__(self): xstr = self.point.x().to_bytes(32, byteorder='big') parity = self.point.y() & 1 return (2 + parity).to_bytes(1, byteorder='big') + xstr def address(self): x = self.point.x() y = self.point.y() s = x.to_bytes(32, 'big') + y.to_bytes(32, 'big') return to_checksum_address(eth_utils_keccak(s)[12:]) def mnemonic_to_bip39seed(mnemonic, passphrase): mnemonic = bytes(mnemonic, 'utf8') salt = bytes(BIP39_SALT_MODIFIER + passphrase, 'utf8') return hashlib.pbkdf2_hmac('sha512', mnemonic, salt, BIP39_PBKDF2_ROUNDS) def bip39seed_to_bip32masternode(seed): k = seed h = hmac.new(BIP32_SEED_MODIFIER, seed, hashlib.sha512).digest() key, chain_code = h[:32], h[32:] return key, chain_code def derive_bip32childkey(parent_key, parent_chain_code, i): assert len(parent_key) == 32 assert len(parent_chain_code) == 32 k = parent_chain_code if (i & BIP32_PRIVDEV) != 0: key = b'\x00' + parent_key else: key = bytes(PublicKey(parent_key)) d = key + struct.pack('>L', i) while True: h = hmac.new(k, d, hashlib.sha512).digest() key, chain_code = h[:32], h[32:] a = int.from_bytes(key, byteorder='big') b = int.from_bytes(parent_key, byteorder='big') key = (a + b) % BIP32_CURVE.order if a < BIP32_CURVE.order and key != 0: key = key.to_bytes(32, byteorder='big') break d = b'\x01' + h[32:] + struct.pack('>L', i) return key, chain_code def parse_derivation_path(str_derivation_path): path = [] if str_derivation_path[0:2] != 'm/': raise ValueError("Can't recognize derivation path. It should look like \"m/44'/60/0'/0\".") for i in str_derivation_path.lstrip('m/').split('/'): if "'" in i: path.append(BIP32_PRIVDEV + int(i[:-1])) else: path.append(int(i)) return path def mnemonic_to_private_key(mnemonic, str_derivation_path, passphrase=""): derivation_path = parse_derivation_path(str_derivation_path) bip39seed = mnemonic_to_bip39seed(mnemonic, passphrase) master_private_key, master_chain_code = bip39seed_to_bip32masternode(bip39seed) private_key, chain_code = master_private_key, master_chain_code for i in derivation_path: private_key, chain_code = derive_bip32childkey(private_key, chain_code, i) return private_key if __name__ == '__main__': import sys with open(sys.argv[1], 'r') as f: mnemonic = ' '.join(f.read().split()) private_key = mnemonic_to_private_key(mnemonic, str_derivation_path=f'/0') public_key = PublicKey(private_key) print(f'privkey: ') print(f'pubkey: ') print(f'address: ')
Create an Account on TestNet with Python
Generate a new standalone account, fund it with the TestNet faucet, and check your balance using the Python SDK.
Requirements
Background
To send any type of transaction, you must first have an account. This tutorial focuses on generating a Standalone Account. To learn more about Accounts on Algorand visit the Accounts Overview page in the docs.
Steps
1. Generate an Algorand Key Pair.
Import the account module from the Python sdk.
Generate a public/private keypair with the generate_account function.
Print the private key an Algorand address so you can see what they look like.
The private key is the base64 representation and the Algorand address is the base32 checksummed version of the public key.
2. Retrieve the Private Key Mnemonic
Transform this key into a mnemonic that you can save for later use. To do this, first import the mnemonic module. Then export the private key as a mnemonic.
Note that the mnemonic will be different set of 25 words each time you run this tutorial. Because we are on TestNet and demonstrating an example, we are openly sharing this private key. You should never do this in real life; especially when your private key represents an account with real-value assets.
With this mnemonic, anyone can sign spend transactions from the corresponding account.
3. Send Algos to the New Account
Let’s send Algos to the new account by visiting the TestNet faucet linked here.
Enter the Algorand Public Address in the textbox, complete the recaptcha, and click “Dispense”. If you receive a 200 status code, your account should now be funded with 100 Algos.
4. Completed Code
The following code generates 3 accounts. It is sometimes useful to have multiple accounts. Three accounts will be needed for ASA tutorials for example. Be sure to fund each generated account using the TestNet Dispenser as described above.
5. Check Your Balance
You can check your balance with any block explorer connected to TestNet.
You can also connect to a node through the Python algod client. Make sure to first retrieve an IP address and access token through one of the methods described in the Workspace Setup.
Once you have an address and token. Instantiate a client and call the account_info method to check the account’s balance.
Blockthon 7.6.9
Blockthon: Fast and easy generation of Private Keys and Mnemonics, converting Seed, Binary, and Decimal.
Навигация
Ссылки проекта
Статистика
Метаданные
Лицензия: MIT License
Метки blockthon, bitcoin, ethereum, tron, dogecoin, dash, qtum, litecoin, bitcoingold, wallet, private key, mnemonic, seed, binary, hex, hunter, compress, un compress, compress address, un compress address
Требует: Python >=3.6
Сопровождающие
Классификаторы
Описание проекта
Blockthon
Blockthon Python Package for Generate and Converting Wallet Private Key and Mnemonic for Address Bitcoin
pip install Blockthon pip3 install Blockthon
sudo apt-get update apt-get upgrade -y sudo apt-get install -y autoconf automake build-essential libffi-dev libtool pkg-config python3-dev pip3 install blockthon
Private Key
generated random private key without repeat :
Mnemonic
Generated random mnemonic with standard size :
Bytes (seed)
Generated Random Bytes Without Repeat :
Binary
Generate Random Binary Without repeat 0/1 :
Private Key To Bytes
Private Key To Wif
generated private key (hex) and convert to wif compressed and uncompressed.
Private Key To Mnemonic
Private Key To Binary
Private Key To Decimal (int)
Private Key To RIPEMD160
Private Key To Address
convert private key Hex to Compress and Uncompress Address
Private Key To Public Key
generated private key and convert to public key compress and uncompress:
Bytes To Private Key
convert bytes to mnemonic with default size=12
can use standard sizr: 12, 18, 24
Bytes To Wif
convert bytes To wif Compress and uncompress:
Bytes To Public Key
convert bytes to public key compress and uncompress
Bytes to Dec (number)
convert bytes to decimal number
Wif To Public Key
convert wif to public key compress and uncompress
Wif To Mnemonic
convert Wif To Mnemonic With Default size=12 , Can use Standard Size 12, 18, 24
Wif To RIPEMD160
convert wif to RIPEMD160 return hex string
Mnemonic To Private key
Mnemonic To Address
convert mnemonic to compressed and uncompressed Address
Passphrase To Private Key
convert word passphrase to private key (hex)
Passphrase to Wif
Programmer & Owner : Mmdrza.Com
How to create a Ethereum Address with Python
In this tutorial, we will create an Ethereum wallet address using Python and also return our private key and mnemonic phrase.
Mnemonic Phrase
A mnemonic phrase or a seed phrase is a group of words, that gets generated when a new wallet has been created. The mnemonic phrase can be used to restore or gain access to your wallet. So treat this phrase as you would treat passwords and keep them safe.
Dependencies
First, we will install our Python packages required for creating an ethereum wallet:
pip install eth_keys pip install eth-hash[pycryptodome] pip install bip-utils pip install mnemonic
Create a Wallet
We will use Python to create the wallet and return the following:
Please note that the mnemonic phrase and private key should be stored safely as if someone gains access to this, they can gain access to your wallet.
from mnemonic import Mnemonic from bip_utils import Bip39SeedGenerator, Bip44Coins, Bip44, Bip44Changes # Define a dictionary where we will store our values body = <> # Generate a random mnemonic in english mnemo = Mnemonic("english") mnemonic = mnemo.generate(256) body['mnemonic'] = mnemonic # Generate the seed from the mnemonic seed = Bip39SeedGenerator(mnemonic).Generate() # Generate the Bip44 wallet (Ethereum) wallet = Bip44.FromSeed(seed, Bip44Coins.ETHEREUM) # Get the first account account = wallet.Purpose().Coin().Account(0).Change(Bip44Changes.CHAIN_EXT).AddressIndex(0) # Extract the private key from the account private_key = account.PrivateKey().Raw().ToHex() body['private_key'] = private_key # Extract the address from the account address = account.PublicKey().ToAddress() body['address'] = address # Print the stored values print(body)
In my example, I am defining this code in create_ethereum_wallet.py and running it:
python3 create_ethereum_wallet.py
The following content gets returned:
< "mnemonic": "something foobar foobar foobar purple foobar focus foobar lion foobar bag foobar foobar foobar security foobar foobar ladder foobar foobar foobar foobar foobar where", "private_key": "0000000000000000000000000000000000000000000000000000000000000000", "address": "0xC35f7DCe60e3f0C22c5E55eCAdDF917Ee4576891" >
I have mixed up some of the output for security reasons, but we can see that the account exists:
Retrieve the Private Key from Mnemonic
We can also retrieve the private key and address when we provide the mnemonic seed phrase:
from mnemonic import Mnemonic from bip_utils import Bip39SeedGenerator, Bip44Coins, Bip44, Bip44Changes # Set your mnemonic seed phrase mnemonic_phrase = "something foobar foobar foobar purple foobar focus foobar lion foobar bag foobar foobar foobar security foobar foobar ladder foobar foobar foobar foobar foobar where" # Define a dictionary where we will store our values body = <> # Generate seed from mnemonic seed = Bip39SeedGenerator(mnemonic).Generate() # Create a Bip44 wallet wallet = Bip44.FromSeed(seed, Bip44Coins.ETHEREUM) # Get the first account account = wallet.Purpose().Coin().Account(0).Change(Bip44Changes.CHAIN_EXT).AddressIndex(0) # Extract the private key from the account private_key = account.PrivateKey().Raw().ToHex() body['private_key'] = private_key # Extract the address from the account address = account.PublicKey().ToAddress() body['address'] = address # Print the stored values print(body)
Let’s say we store this code to recover_ethereum_address.py and we run it:
python3 recover_ethereum_address.py
Then the response should be something like:
< "private_key": "0000000000000000000000000000000000000000000000000000000000000000", "address": "0xC35f7DCe60e3f0C22c5E55eCAdDF917Ee4576891" >
Thank You
Thanks for reading, feel free to check out my website, feel free to subscribe to my newsletter or follow me at @ruanbekker on Twitter.