From what I've tested, this script dumps private keys for bech32 addresses, only receiving addresses.
To dump change addresses and other scripts addresses (legacy, p2sh-segwit and bech32m) you should add more functions to this script as I described.
I have a similar script, you can base it on it, at the moment it only accepts mnemonics and bip39 passphrases, but you can make changes to allow for the inclusion of extended private keys.
import sys
import hashlib
from bip_utils import (
Bip39MnemonicGenerator, Bip39MnemonicValidator, Bip39SeedGenerator,
Bip44, Bip49, Bip84, Bip86, Bip44Coins, Bip49Coins, Bip84Coins, Bip86Coins,
Bip44Changes, Bip32Slip10Secp256k1, Secp256k1PrivateKey, WifEncoder
)
from getpass import getpass
def main():
# Ask if a new mnemonic should be created
mnemonic_choice = input("Enter the number of words to create a new mnemonic (12, 18, 24) or press Enter to use an existing mnemonic: ").strip()
if mnemonic_choice in ['12', '18', '24']:
# Generate a new mnemonic with the specified number of words
num_words = int(mnemonic_choice)
mnemonic = Bip39MnemonicGenerator().FromWordsNumber(num_words)
print(f"New mnemonic generated ({num_words} words): {mnemonic}")
else:
# Ask for the mnemonic
mnemonic = input("Enter the mnemonic: ").strip()
# Validate the mnemonic
if not Bip39MnemonicValidator().IsValid(mnemonic):
print("Invalid mnemonic!")
sys.exit(1)
# Ask for the passphrase (optional)
passphrase = getpass("Enter the passphrase (optional): ").strip()
# Generate the BIP39 seed
seed = Bip39SeedGenerator(mnemonic).Generate(passphrase)
# Define default paths
deriv_paths = {
'1': "m/44'/0'", # p2pkh
'2': "m/49'/0'", # p2wpkh-p2sh
'3': "m/84'/0'", # p2wpkh
'4': "m/86'/0'" # p2tr
}
print("Available derivation paths and address types:")
print("1: p2pkh (m/44'/0')")
print("2: p2wpkh-p2sh (m/49'/0')")
print("3: p2wpkh (m/84'/0')")
print("4: p2tr (m/86'/0')")
address_type = input("Choose the address type (1-4): ").strip()
if address_type not in deriv_paths:
print("Invalid address type!")
sys.exit(1)
# Base derivation path
base_derivation_path = deriv_paths[address_type]
# Ask for the account index
account_index = input("Enter the account index (default 0): ").strip()
account_index = int(account_index) if account_index.isdigit() else 0
# Ask if generating receiving addresses (0) or change addresses (1)
address_purpose = input("Generate receiving addresses (0) or change addresses (1)? ").strip()
if address_purpose not in ['0', '1']:
print("Invalid option!")
sys.exit(1)
# Ask from which index to display addresses
start_index = int(input("From which index to display addresses (default 0)? ").strip() or 0)
# Ask how many addresses to display
address_count = int(input("How many addresses to display (default 50)? ").strip() or 50)
# Initialize the appropriate BIP class
bip_cls_dict = {
'1': (Bip44, Bip44Coins.BITCOIN),
'2': (Bip49, Bip49Coins.BITCOIN),
'3': (Bip84, Bip84Coins.BITCOIN),
'4': (Bip86, Bip86Coins.BITCOIN)
}
bip_cls, coin_type = bip_cls_dict[address_type]
bip_obj = bip_cls.FromSeed(seed, coin_type)
# Derive the main account
bip_acc_obj = bip_obj.Purpose().Coin().Account(account_index)
# Get the fingerprint of the BIP32 root public key
root_pubkey = bip_obj.PublicKey().RawCompressed().ToBytes()
fingerprint = hashlib.new('ripemd160', hashlib.sha256(root_pubkey).digest()).digest()[:4]
# Derive addresses
addresses = []
for i in range(start_index, start_index + address_count):
addr_obj = bip_acc_obj.Change(Bip44Changes(int(address_purpose))).AddressIndex(i)
priv_key = addr_obj.PrivateKey().Raw().ToBytes()
priv_key_wif = WifEncoder.Encode(Secp256k1PrivateKey.FromBytes(priv_key))
addresses.append({
'index': i,
'address': addr_obj.PublicKey().ToAddress(),
'private_key_wif': priv_key_wif,
'hdkeypath': f"{base_derivation_path}/{account_index}'/{address_purpose}/{i}"
})
# Generate the BIP32 root private key
bip32_obj = Bip32Slip10Secp256k1.FromSeed(seed)
root_xpriv = bip32_obj.PrivateKey().ToExtended()
# Generate the BIP32 extended private key at the account level
account_xpriv = bip_acc_obj.PrivateKey().ToExtended()
# Generate the WIF for the root private key
root_priv_key_bytes = bip32_obj.PrivateKey().Raw().ToBytes()
root_priv_key_wif = WifEncoder.Encode(Secp256k1PrivateKey.FromBytes(root_priv_key_bytes))
# Display results
print("\nMnemonic:", mnemonic)
if passphrase:
print("Passphrase:", passphrase)
print("\nBIP32 Masterkey:", root_xpriv)
print("BIP32 Extended Private Key (account Level):", account_xpriv)
print("Derivation Path used:", f"{base_derivation_path}/{account_index}'/{address_purpose}")
print("Wallet Fingerprint:", fingerprint.hex())
print("BIP32 Root PrivKey (WIF):", root_priv_key_wif)
print()
for addr in addresses:
print(f"{addr['private_key_wif']} # addr={addr['address']} hdkeypath={addr['hdkeypath']}")
# Ask if a dump.txt file should be created
save_to_file = input("Do you want to generate a dump.txt file to import into a wallet? (y/n): ").strip().lower()
if save_to_file == 'y':
with open('dump.txt', 'w') as f:
f.write(f"Mnemonic: {mnemonic}\n")
if passphrase:
f.write(f"Passphrase: {passphrase}\n")
f.write(f"\nBIP32 Masterkey: {root_xpriv}\n")
f.write(f"BIP32 Extended Private Key (account Level): {account_xpriv}\n")
f.write(f"Derivation Path used: {base_derivation_path}/{account_index}'/{address_purpose}\n")
f.write(f"Wallet Fingerprint: {fingerprint.hex()}\n")
f.write(f"BIP32 Root PrivKey (WIF): {root_priv_key_wif}\n\n")
for addr in addresses:
f.write(f"{addr['private_key_wif']} # addr={addr['address']} hdkeypath={addr['hdkeypath']}\n")
print("dump.txt file exported successfully!")
else:
print("Output saved only to screen.")
if __name__ == "__main__":
main()
How to import an existing private key or address into the core wallet?
Do you mean importing a single private key or an extended private key (xpriv)?
If you want to import single private keys from one or more addresses, I have a guide, you can access it through the link:
[HOW-TO] Import privkeys into a Bitcoin Core descriptor walletTo import all addresses from a wallet derived from an xpriv, follow this thread:
How to import an xpriv to a descriptor wallet in bitcoin core?