def get_default_coin(private_key): decoded_wif = WifDecoder.Decode( wif_str=private_key, net_addr_ver=BitcoinCashConf.WIF_NET_VER.Main()) key_pair = Bip44.FromAddressPrivKey(decoded_wif, Bip44Coins.BITCOIN_CASH) address = key_pair.PublicKey().ToAddress().replace('bitcoincash:', '') return CryptoCoin(address, private_key)
def get_default_coin(private_key): decoded_wif = WifDecoder.Decode(wif_str=private_key, net_addr_ver=CLUB_WIF_NET_VER.Main()) bip44_mst = Bip44.FromAddressPrivKey(decoded_wif, Bip44Coins.BITCOIN) pub_key_bytes = bip44_mst.PublicKey().RawCompressed().ToBytes() address = Base58Encoder.CheckEncode(CLUB_P2PKH_NET_VER.Main() + CryptoUtils.Hash160(pub_key_bytes)) return CryptoCoin(address, private_key)
def get_uncompressed_coin(private_key): print("Warning Uncompressed key") decoded_wif = WifDecoder.Decode(wif_str=private_key, net_addr_ver=CLUB_WIF_NET_VER.Main()) bip44_mst = Bip44.FromAddressPrivKey(decoded_wif, Bip44Coins.BITCOIN) to_hex = bip44_mst.PublicKey().RawUncompressed().ToBytes() pub_key_bytes = b'\x04' + to_hex address = Base58Encoder.CheckEncode(CLUB_P2PKH_NET_VER.Main() + CryptoUtils.Hash160(pub_key_bytes)) return CryptoCoin(address, private_key)
def get_uncompressed_coin(private_key): print("Warning Uncompressed key") config_alias = DashConf coin_type = Bip44Coins.DASH decoded_wif = WifDecoder.Decode( wif_str=private_key, net_addr_ver=config_alias.WIF_NET_VER.Main()) bip44_mst = Bip44.FromAddressPrivKey(decoded_wif, coin_type) to_hex = bip44_mst.PublicKey().RawUncompressed().ToBytes() pub_key_bytes = b'\x04' + to_hex address = Base58Encoder.CheckEncode(config_alias.P2PKH_NET_VER.Main() + CryptoUtils.Hash160(pub_key_bytes)) return CryptoCoin(address, private_key)
def generate(self): # Generate random mnemonic mnemonic = Bip39MnemonicGenerator.FromWordsNumber(12) # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Generate BIP44 master keys bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.DASH) address = bip_obj_mst.PublicKey().ToAddress() wif = bip_obj_mst.PrivateKey().ToWif() seed = mnemonic return CryptoCoin(address, wif, seed)
def get_uncompressed_coin(private_key): print("Warning Uncompressed key") config_alias = BitcoinConf coin_type = Bip44Coins.BITCOIN decodedWif = WifDecoder.Decode( wif_str=private_key, net_addr_ver=config_alias.WIF_NET_VER.Main()) bip44_mst = Bip44.FromAddressPrivKey(decodedWif, coin_type) to_hex = bip44_mst.PublicKey().RawUncompressed().ToBytes() pub_key_bytes = b'\x04' + to_hex legacy_address = Base58Encoder.CheckEncode( config_alias.P2PKH_NET_VER.Main() + CryptoUtils.Hash160(pub_key_bytes)) address = convert.to_cash_address(legacy_address).replace( 'bitcoincash:', '') return CryptoCoin(address, private_key)
def get_address_at_index(self, index): if self.config["bip"] == "BIP84": bip84_acc = Bip84.FromExtendedKey(self.config["xpub"], Bip84Coins.BITCOIN) child_key = bip84_acc.Change( Bip44Changes.CHAIN_EXT).AddressIndex(index) elif self.config["bip"] == "BIP44": bip44_acc = Bip44.FromExtendedKey(self.config["xpub"], Bip44Coins.BITCOIN) child_key = bip44_acc.Change( Bip44Changes.CHAIN_EXT).AddressIndex(index) else: raise NotImplementedError("{} is not yet implemented!".format( self.config["bip"])) address = child_key.PublicKey().ToAddress() return address
def generate(self): # Generate random mnemonic mnemonic = Bip39MnemonicGenerator.FromWordsNumber(12) # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Generate BIP44 master keys bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN) wif = WifEncoder.Encode(bip_obj_mst.PrivateKey().Raw().ToBytes(), True, POTE_WIF_NET_VER.Main()) pub_key_bytes = bip_obj_mst.PublicKey().RawCompressed().ToBytes() address = Base58Encoder.CheckEncode(POTE_P2PKH_NET_VER.Main() + CryptoUtils.Hash160(pub_key_bytes)) seed = mnemonic return CryptoCoin(address, wif, seed)
def _RunTest(self, seed_bytes: bytes) -> None: for i in range(0, self.m_test_itr_num): bip44_ctx = Bip44.FromSeed(seed_bytes, self.m_bip44_coin) bip44_chg = bip44_ctx.Purpose().Coin().Account(0).Change( Bip44Changes.CHAIN_EXT) for j in range(0, self.m_test_cache_num): bip44_chg.PublicKey().ToAddress() bip44_chg.PublicKey().ToExtended() bip44_chg.PrivateKey().ToExtended() bip44_chg.PublicKey().RawCompressed().ToHex() bip44_chg.PublicKey().RawUncompressed().ToHex() bip44_chg.PrivateKey().Raw().ToHex() bip44_addr = bip44_chg.AddressIndex(i) for j in range(0, self.m_test_cache_num): bip44_addr.PublicKey().ToAddress() bip44_addr.PublicKey().ToExtended() bip44_addr.PrivateKey().ToExtended() bip44_addr.PublicKey().RawCompressed().ToHex() bip44_addr.PublicKey().RawUncompressed().ToHex() bip44_addr.PrivateKey().Raw().ToHex()
def cli( mnemonic: str, passphrase: str, limit: int, prompt_mnemonic: bool, prompt_passphrase: bool, hide_mnemonic: bool, hide_private: bool, ): if prompt_passphrase: passphrase = click.prompt("passphrase", hide_input=True) if prompt_mnemonic: mnemonic = click.prompt("mnemonic", hide_input=True) if not mnemonic: mnemonic = Bip39MnemonicGenerator.FromWordsNumber( Bip39WordsNum.WORDS_NUM_24) if not Bip39MnemonicValidator(mnemonic).Validate(): return fatal("Invalid mnemonic") seed_bytes = Bip39SeedGenerator(mnemonic).Generate(passphrase) if not hide_mnemonic: click.echo(mnemonic + "\n") bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN) bip_obj_acc = bip_obj_mst.Purpose().Coin().Account(0) bip_obj_chain = bip_obj_acc.Change(Bip44Changes.CHAIN_EXT) # m/44'/0'/0'/0/i for i in range(limit): bip_obj_addr = bip_obj_chain.AddressIndex(i) address = bip_obj_addr.PublicKey().ToAddress() private = bip_obj_addr.PrivateKey().ToWif() acc = address if hide_private else f"{address} / {private}" click.echo(acc)
def test_vector(self): for test in TEST_VECT: lang = test["lang"] # Test mnemonic generator mnemonic = AlgorandMnemonicGenerator(lang).FromEntropy( binascii.unhexlify(test["entropy"])) self.assertEqual(test["mnemonic"], mnemonic.ToStr()) self.assertEqual(test["mnemonic"], str(mnemonic)) self.assertEqual(test["mnemonic"].split(" "), mnemonic.ToList()) self.assertEqual(len(test["mnemonic"].split(" ")), mnemonic.WordsCount()) # Test mnemonic validator (language specified) mnemonic_validator = AlgorandMnemonicValidator(lang) self.assertTrue(mnemonic_validator.IsValid(mnemonic)) # Test mnemonic validator (automatic language detection) mnemonic_validator = AlgorandMnemonicValidator() self.assertTrue(mnemonic_validator.IsValid(mnemonic)) # Test decoder (language specified) entropy = AlgorandMnemonicDecoder(lang).Decode(mnemonic) self.assertEqual(test["entropy"], binascii.hexlify(entropy)) # Test decoder (automatic language detection) entropy = AlgorandMnemonicDecoder().Decode(mnemonic) self.assertEqual(test["entropy"], binascii.hexlify(entropy)) # Test seed generator (seed is the entropy itself for Algorand) seed = AlgorandSeedGenerator(mnemonic, lang).Generate() self.assertEqual(test["entropy"], binascii.hexlify(seed)) # Test address bip44_ctx = Bip44.FromPrivateKey(seed, Bip44Coins.ALGORAND) self.assertEqual(test["address"], bip44_ctx.PublicKey().ToAddress())
"Create word list of combination a-z with number of character input.") new_parser.add_argument("-a", "--address", help="enter wallet address", type=int) arguments = new_parser.parse_args() mnemo = Mnemonic("english") # Seed bytes words = "winner equip edge stock junior kangaroo avocado wild escape never guide embody comfort slide account cycle hip unaware field view warfare toss soup small" # seed_bytes = binascii.unhexlify(b"fbe985196b0792f303ffd84d12a19e2432e3970061b66bfd8d57f9ff71cb73fe") seed = mnemo.to_seed(words, passphrase="hello") # Create from seed bip44_mst = Bip44.FromSeed(seed, Bip44Coins.BITCOIN) # # Print master key in extended format # print(bip44_mst.PrivateKey().ToExtended()) # # Print master key in hex format # print(bip44_mst.PrivateKey().Raw().ToHex()) # # Print public key in extended format (default: Bip44PubKeyTypes.EXT_KEY) # print(bip44_mst.PublicKey()) # # Print public key in raw uncompressed format # print(bip44_mst.PublicKey().RawUncompressed().ToHex()) # # Print public key in raw compressed format # print(bip44_mst.PublicKey().RawCompressed().ToHex()) # # Print the master key in WIF # print(bip44_mst.PrivateKey().ToWif())
def test_spec_name(self): self.assertEqual(Bip44.SpecName(), "BIP-0044")
"""Example of wallet creation using Algorand (same addresses of official wallet).""" from bip_utils import (AlgorandWordsNum, AlgorandMnemonicGenerator, AlgorandSeedGenerator, Bip44Coins, Bip44) # Generate random mnemonic mnemonic = AlgorandMnemonicGenerator().FromWordsNumber( AlgorandWordsNum.WORDS_NUM_25) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = AlgorandSeedGenerator(mnemonic).Generate() # The seed is used as private key in the official wallet bip44_ctx = Bip44.FromPrivateKey(seed_bytes, Bip44Coins.ALGORAND) # Print keys print(f"Algorand private key: {bip44_ctx.PrivateKey().Raw().ToHex()}") print(f"Algorand public key: {bip44_ctx.PublicKey().RawCompressed().ToHex()}") # Print address print(f"Algorand address: {bip44_ctx.PublicKey().ToAddress()}")
def generate(): # Tells the library what network we are using setup() if not mnemonic_phrase: # Generate mnemonic from random 192-bit entropy entropy_bytes = Bip39EntropyGenerator( Bip39EntropyBitLen.BIT_LEN_192).Generate() mnemonic = Bip39MnemonicGenerator.FromEntropy(entropy_bytes) print("Generated random mnemonic:\n" + mnemonic) else: print("Using included mnemonic.") mnemonic = mnemonic_phrase # Get seed bytes from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() bip44_mst = Bip44.FromSeed( seed_bytes, Bip44Coins.BITCOIN) # Could add in multi currency support # Derive account 0 for Bitcoin: m/44'/0'/0' bip44_acc = bip44_mst.Purpose() \ .Coin() \ .Account(0) # Derive the external chain: m/44'/0'/0'/0 bip44_change = bip44_acc.Change(Bip44Changes.CHAIN_EXT) with open(output_dest, 'w') as output_file: # Open the output file output_file.write("address, public_key" + (", private_key" if privates else "") + "\n") # Go through each address for i in range(number): bip44_addr = bip44_change.AddressIndex(i) # create segwit address addr3 = PrivateKey.from_wif(bip44_addr.PrivateKey().ToWif( )).get_public_key().get_segwit_address() # wrap in P2SH address addr4 = P2shAddress.from_script(addr3.to_script_pub_key()) if addr4.to_string() == compare: print("Found it!") print("Path: m/44'/0'/0'/0/" + str(i)) break #print("P2SH(P2WPKH):", addr4.to_string()) if (i % int(number / 10)) == 0: print('Finished {}'.format(i)) out = "{0}, {1}".format(addr4.to_string(), bip44_addr.PublicKey().ToExtended() ) # Public addresses not including private if (privates): # Include the private keys out = "{0}, {1}, {2}".format( addr4.to_string(), bip44_addr.PublicKey().RawCompressed().ToHex(), bip44_addr.PrivateKey().ToWif()) #bip44_addr.PublicKey().ToAddress() # This is the regular address (not P2SH(P2WPKH)) # Print extended keys and address if (verbose): print(out) output_file.write(out + "\n")
def get_default_coin(private_key): decoded_wif = WifDecoder.Decode( wif_str=private_key, net_addr_ver=DashConf.WIF_NET_VER.Main()) key_pair = Bip44.FromAddressPrivKey(decoded_wif, Bip44Coins.DASH) address = key_pair.PublicKey().ToAddress() return CryptoCoin(address, private_key)
""" Example of wallet creation in the same way of Solana-CLI. Solana-CLI works differently from other wallets. First of all, it's not a HD-wallet but it only generates a master key without deriving any child key. Secondly, the master private key is just the first 32-byte of the seed generated from the mnemonic, it's not computing the HMAC-SHA512 like BIP32. """ from bip_utils import (Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44Coins, Bip44) # Generate random mnemonic mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_12) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # The first 32-byte of the seed is the private key bip44_ctx = Bip44.FromPrivateKey(seed_bytes[:32], Bip44Coins.SOLANA) # Same address of Solana-CLI print(f"Address: {bip44_ctx.PublicKey().ToAddress()}") # Print master key, no need to derive any child key print(f"Public key: {bip44_ctx.PublicKey().RawCompressed().ToHex()}") print(f"Private key: {bip44_ctx.PrivateKey().Raw().ToHex()}")
Example of key derivation for ed25519-based coins in the same way of Exodus wallet. Basically, the Exodus wallet uses the secp256k1 curve to derive the complete BIP44 path for all coins, even if they are not based on the secp256k1 curve. Then, for the coins based on the ed25519 curve (e.g. Algorand, Solana, Stellar, ...), it uses the last derived private key as a ed25519 master key to compute the public key and address. It's not the only wallet doing this (Atomic Wallet does the same), because in this way the developers don't have to implement other derivation schemes beside secp256k1. """ from bip_utils import Bip39SeedGenerator, Bip32Secp256k1, Bip44Coins, Bip44ConfGetter, Bip44 # Coin that we want coin_type = Bip44Coins.SOLANA # Mnemonic mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Get coin index from configuration coin_idx = Bip44ConfGetter.GetConfig(coin_type).CoinIndex() # Derive the standard BIP44 path using secp256k1 bip32_ctx = Bip32Secp256k1.FromSeed(seed_bytes).DerivePath( f"m/44'/{coin_idx}'/0'/0/0") priv_key_bytes = bip32_ctx.PrivateKey().Raw().ToBytes() # Use the last private key as a ed25519 master key, we can use Bip44 to simplify the address computation bip44_ctx = Bip44.FromPrivateKey(priv_key_bytes, coin_type) # Same address of Exodus print(f"Address: {bip44_ctx.PublicKey().ToAddress()}")
from bip_utils import Bip39SeedGenerator, Bip44, Bip44Changes, Bip44Coins mnemonic = "disorder list exit unveil ski hand subject hen clean life sponsor praise expand nature tobacco orange actress when lion begin dash luxury found convince" # noqa passphrase = "mega-secret" seed_bytes = Bip39SeedGenerator(mnemonic).Generate(passphrase) bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN) bip_obj_acc = bip_obj_mst.Purpose().Coin().Account(0) # Generate BIP44 chain keys: m/44'/0'/0'/0 bip_obj_chain = bip_obj_acc.Change(Bip44Changes.CHAIN_EXT) # Generate the address pool (first 20 addresses): m/44'/0'/0'/0/i for i in range(20): bip_obj_addr = bip_obj_chain.AddressIndex(i) address = bip_obj_addr.PublicKey().ToAddress() private = bip_obj_addr.PrivateKey().ToWif() print(f"{address} / {private}")
"""Example of SPL token account address generation for Solana.""" from bip_utils import ( Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44Coins, Bip44, SplToken ) # Generate random mnemonic mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_24) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Construct from seed bip44_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.SOLANA).DeriveDefaultPath() # Print default address addr = bip44_ctx.PublicKey().ToAddress() print(f"Default address: {addr}") # Get address for USDC token usdc_addr = SplToken.GetAssociatedTokenAddress(addr, "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v") print(f"USDC account address: {usdc_addr}") # Get address for Serum token srm_addr = SplToken.GetAssociatedTokenAddress(addr, "SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt") print(f"SRM account address: {srm_addr}")
def migrateWallet(): os.system('cls' if os.name == 'nt' else 'clear') print(" ╔╦╗┬┌─┐┬─┐┌─┐┌┬┐┌─┐ ╦ ╦┌─┐┬ ┬ ┌─┐┌┬┐") print(" ║║║││ ┬├┬┘├─┤ │ ├┤ ║║║├─┤│ │ ├┤ │ ") print(" ╩ ╩┴└─┘┴└─┴ ┴ ┴ └─┘ ╚╩╝┴ ┴┴─┘┴─┘└─┘ ┴ ") print("") print(" #######################################") print("") print(" 1: Migrate Through Private Key") print("") print(" 2: Migrate Through 12 Word Phrase") print("") userInput = input(" > ") print("") if userInput == "1": print(" Type Private Key:") print("") privKey = input(" > ") privKey = int(privKey, 16) print("") print(" Type Strong Password:"******"") password = input(" > ") PublicKey = EccMultiply(GPoint, privKey) PublicKey = hex(PublicKey[0])[2:] + hex(PublicKey[1])[2:] address = Web3.keccak(hexstr = PublicKey).hex() address = "0x" + address[-40:] address = Web3.toChecksumAddress(address) time.sleep(2) print("") print("> Encrypting Wallet") salt = get_random_bytes(16) key = scrypt(password, salt, 32, N=2**20, r = 8, p = 1) privKey = hex(privKey)[2:] data = str(privKey).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data, AES.block_size)) salt = salt.hex() iv = cipher.iv.hex() ct = ct_bytes.hex() output = {"salt" : salt, "initialization vector" : iv, "encrypted private key" : ct} with open("wallets/" + address + '.txt', 'w') as json_file: json.dump(output, json_file) print("") print("> Wallet Created") time.sleep(2) startWallet() elif userInput == "2": print(" Type 12 Words:") mnemonic = input(" > ") seed_bytes = Bip39SeedGenerator(mnemonic).Generate() bip_obj_mst = Bip44.FromSeed(seed_bytes, Bip44Coins.ETHEREUM) bip_obj_acc = bip_obj_mst.Purpose().Coin().Account(0) bip_obj_chain = bip_obj_acc.Change(Bip44Changes.CHAIN_EXT) accountFound = False accountNumber = 0 while accountFound == False: bip_obj_addr = bip_obj_chain.AddressIndex(accountNumber) checkAddress = getEth(bip_obj_addr.PublicKey().ToAddress()) if checkAddress > 0: accountFound = True privKey = bip_obj_addr.PrivateKey().Raw().ToHex() privKey = int(privKey, 16) print("") print(" > Found Wallet!") time.sleep(2) print("") print(" Type Strong Password:"******"") password = input(" > ") PublicKey = EccMultiply(GPoint, privKey) PublicKey = hex(PublicKey[0])[2:] + hex(PublicKey[1])[2:] address = Web3.keccak(hexstr = PublicKey).hex() address = "0x" + address[-40:] address = Web3.toChecksumAddress(address) time.sleep(2) print("") print("> Encrypting Wallet") salt = get_random_bytes(16) key = scrypt(password, salt, 32, N=2**20, r = 8, p = 1) privKey = hex(privKey)[2:] data = str(privKey).encode('utf-8') cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data, AES.block_size)) salt = salt.hex() iv = cipher.iv.hex() ct = ct_bytes.hex() output = {"salt" : salt, "initialization vector" : iv, "encrypted private key" : ct} with open("wallets/" + address + '.txt', 'w') as json_file: json.dump(output, json_file) print("") print("> Wallet Created") time.sleep(2) startWallet()
"""Example of key derivation using BIP44.""" from bip_utils import (Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44Changes, Bip44Coins, Bip44) ADDR_NUM: int = 5 # Generate random mnemonic mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_24) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Construct from seed bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN) # Print master key print(f"Master key (bytes): {bip44_mst_ctx.PrivateKey().Raw().ToHex()}") print(f"Master key (extended): {bip44_mst_ctx.PrivateKey().ToExtended()}") print(f"Master key (WIF): {bip44_mst_ctx.PrivateKey().ToWif()}") # Generate BIP44 account keys: m/44'/0'/0' bip44_acc_ctx = bip44_mst_ctx.Purpose().Coin().Account(0) # Generate BIP44 chain keys: m/44'/0'/0'/0 bip44_chg_ctx = bip44_acc_ctx.Change(Bip44Changes.CHAIN_EXT) # Generate addresses: m/44'/0'/0'/0/i print("Addresses:") for i in range(ADDR_NUM): bip44_addr_ctx = bip44_chg_ctx.AddressIndex(i) print( f" {i}. Address public key (extended): {bip44_addr_ctx.PublicKey().ToExtended()}"
"""Example of key derivation using Monero based on BIP44.""" import binascii from bip_utils import (Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44Coins, Bip44, Monero) # Generate random mnemonic mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_24) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Construct from seed bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.MONERO_ED25519_SLIP) # Print master key print(f"Master key (bytes): {bip44_mst_ctx.PrivateKey().Raw().ToHex()}") print(f"Master key (extended): {bip44_mst_ctx.PrivateKey().ToExtended()}") # Derive default path bip44_def_ctx = bip44_mst_ctx.DeriveDefaultPath() # Create Monero object from the BIP44 private key monero = Monero.FromBip44PrivateKey(bip44_def_ctx.PrivateKey().Raw().ToBytes()) # Print keys print(f"Monero private spend key: {monero.PrivateSpendKey().Raw().ToHex()}") print(f"Monero private view key: {monero.PrivateViewKey().Raw().ToHex()}") print( f"Monero public spend key: {monero.PublicSpendKey().RawCompressed().ToHex()}" ) print(
def get_coin(self, private_key): key_pair = Bip44.FromAddressPrivKey(bytes.fromhex(private_key), Bip44Coins.BINANCE_CHAIN) address = key_pair.PublicKey().ToAddress() return CryptoCoin(address, private_key)
""" Example of key derivation with 24-words mnemonic phrase in the same way of Brave crypto wallets extension (legacy). The old version of Brave crypto wallets extension (now referred as "legacy") worked differently from BIP39 when a 24-words mnemonic phrase was used. In fact, instead of computing the seed from the mnemonic as described in BIP39, it used the initial entropy directly as seed. Therefore, the derived keys and addresses were completely different to other wallets. """ from bip_utils import Bip39MnemonicDecoder, Bip44Changes, Bip44Coins, Bip44 # Mnemonic mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon " \ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art" # Get back entropy bytes from mnemonic entropy_bytes = Bip39MnemonicDecoder().Decode(mnemonic) # Use the entropy bytes directly as seed bip44_mst_ctx = Bip44.FromSeed(entropy_bytes, Bip44Coins.ETHEREUM) # Derive the key of the first address bip44_addr_ctx = bip44_mst_ctx.Purpose().Coin().Account(0).Change( Bip44Changes.CHAIN_EXT).AddressIndex(0) # Same address of Brave crypto wallets extension print(f"Address: {bip44_addr_ctx.PublicKey().ToAddress()}")
"""Example of key derivation using Substrate based on BIP44.""" from bip_utils import ( Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44Coins, Bip44 ) # Generate random mnemonic mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_24) print(f"Mnemonic string: {mnemonic}") # Generate seed from mnemonic seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # Construct from seed bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.POLKADOT_ED25519_SLIP) # Print master key print(f"Master key (bytes): {bip44_mst_ctx.PrivateKey().Raw().ToHex()}") # Derive default path bip_obj_def = bip44_mst_ctx.DeriveDefaultPath() # Print default keys and address print(f"Default public key (hex): {bip_obj_def.PublicKey().RawCompressed().ToHex()}") print(f"Default private key (hex): {bip_obj_def.PrivateKey().Raw().ToHex()}") print(f"Default address: {bip_obj_def.PublicKey().ToAddress()}")