kandi background
Explore Kits

bip_utils | public keys and addresses for different types | Cryptography library

 by   ebellocchia Python Version: v2.2.1 License: MIT

 by   ebellocchia Python Version: v2.2.1 License: MIT

Download this library from

kandi X-RAY | bip_utils Summary

bip_utils is a Python library typically used in Financial Services, Fintech, Security, Cryptography, Ethereum, Bitcoin applications. bip_utils has no bugs, it has build file available, it has a Permissive License and it has low support. However bip_utils has 2 vulnerabilities. You can install using 'pip install bip_utils' or download it from GitHub, PyPI.
This package allows generating mnemonics, seeds, private/public keys and addresses for different types of cryptocurrencies. In particular:. Please note that, for the py-sr25519-bindings library, Rust is required to be installed.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • bip_utils has a low active ecosystem.
  • It has 133 star(s) with 49 fork(s). There are 11 watchers for this library.
  • There were 6 major release(s) in the last 12 months.
  • There are 0 open issues and 34 have been closed. On average issues are closed in 4 days. There are no pull requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of bip_utils is v2.2.1
bip_utils Support
Best in #Cryptography
Average in #Cryptography
bip_utils Support
Best in #Cryptography
Average in #Cryptography

quality kandi Quality

  • bip_utils has 0 bugs and 548 code smells.
bip_utils Quality
Best in #Cryptography
Average in #Cryptography
bip_utils Quality
Best in #Cryptography
Average in #Cryptography

securitySecurity

  • bip_utils has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • bip_utils code analysis shows 2 unresolved vulnerabilities (0 blocker, 2 critical, 0 major, 0 minor).
  • There are 14 security hotspots that need review.
bip_utils Security
Best in #Cryptography
Average in #Cryptography
bip_utils Security
Best in #Cryptography
Average in #Cryptography

license License

  • bip_utils is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
bip_utils License
Best in #Cryptography
Average in #Cryptography
bip_utils License
Best in #Cryptography
Average in #Cryptography

buildReuse

  • bip_utils releases are available to install and integrate.
  • Deployable package is available in PyPI.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • It has 18336 lines of code, 1162 functions and 279 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
bip_utils Reuse
Best in #Cryptography
Average in #Cryptography
bip_utils Reuse
Best in #Cryptography
Average in #Cryptography
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

bip_utils Key Features

Mnemonic and seed generation as defined by BIP-0039

Private key encryption/decryption as defined by BIP-0038

Keys derivation as defined by BIP-0032 and SLIP-0010

Derivation of a hierarchy of keys as defined by BIP-0044, BIP-0049 and BIP-0084

Mnemonic and seed generation for Substrate (Polkadot/Kusama ecosystem)

Keys derivation for Substrate (Polkadot/Kusama ecosystem, same of Polkadot-JS)

Mnemonic and seed generation for Monero

Keys and addresses/subaddresses generation for Monero (same of official Monero wallet)

Parse BIP-0032 derivation paths

Parse Substrate derivation paths

Encode/Decode addresses for all the supported coins

Encode/Decode WIF

Encode/Decode base58

Encode/Decode ss58

Encode/Decode segwit bech32

Encode/Decode Bitcoin Cash bech32

crcmod for CRC computation

pycryptodome for keccak256 and SHA512/256

coincurve for secp256k1 curve

ecdsa for nist256p1 and secp256k1 curves

ed25519-blake2b for ed25519-blake2b curve

pynacl for ed25519 curve

py-sr25519-bindings for sr25519 curve

scalecodec for SCALE encoding

Install the package

copy iconCopydownload iconDownload
  python setup.py install

Mnemonic generation

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip39EntropyBitLen, Bip39EntropyGenerator, Bip39MnemonicGenerator, Bip39WordsNum, Bip39Languages

# Generate a random mnemonic string of 12 words with default language (English)
# A Mnemonic object will be returned
mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)

# Get words count
print(mnemonic.WordsCount())
# Get as string
print(mnemonic.ToStr())
print(str(mnemonic))
# Get as list of strings
print(mnemonic.ToList())

# Generate a random mnemonic string of 15 words by specifying the language
mnemonic = Bip39MnemonicGenerator(Bip39Languages.ITALIAN).FromWordsNumber(Bip39WordsNum.WORDS_NUM_15)

# Generate the mnemonic string from entropy bytes
entropy_bytes = binascii.unhexlify(b"00000000000000000000000000000000")
mnemonic = Bip39MnemonicGenerator().FromEntropy(entropy_bytes)
mnemonic = Bip39MnemonicGenerator(Bip39Languages.FRENCH).FromEntropy(entropy_bytes)

# Generate mnemonic from random 192-bit entropy
entropy_bytes = Bip39EntropyGenerator(Bip39EntropyBitLen.BIT_LEN_192).Generate()
mnemonic = Bip39MnemonicGenerator().FromEntropy(entropy_bytes)

Mnemonic validation

copy iconCopydownload iconDownload
from bip_utils import (
    Bip39ChecksumError, Bip39Languages, Bip39WordsNum, Bip39MnemonicGenerator, Bip39MnemonicValidator, Bip39MnemonicDecoder
)

# Mnemonic can be generated with Bip39MnemonicGenerator
mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_15)
# Or it can be a string
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"

# Get if a mnemonic is valid, return bool
is_valid = Bip39MnemonicValidator().IsValid(mnemonic)
# Validate a mnemonic, raise exceptions
try:
    Bip39MnemonicValidator().Validate(mnemonic)
    # Valid...
except Bip39ChecksumError:
    # Invalid checksum...
    pass
except ValueError:
    # Invalid length or language...
    pass

# Use Bip39MnemonicDecoder to get back the entropy bytes from a mnemonic, specifying the language
entropy_bytes = Bip39MnemonicDecoder(Bip39Languages.ENGLISH).Decode(mnemonic)
# Like before with automatic language detection
entropy_bytes = Bip39MnemonicDecoder().Decode(mnemonic)

# Alternatively, it's possible to get back the entropy bytes with the computed checksum
entropy_chksum_bytes = Bip39MnemonicDecoder(Bip39Languages.ENGLISH).DecodeWithChecksum(mnemonic)

Seed generation

copy iconCopydownload iconDownload
from bip_utils import Bip39Languages, Bip39WordsNum, Bip39MnemonicGenerator, Bip39SeedGenerator

# Mnemonic can be generated with Bip39MnemonicGenerator
mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_24)
# Or it can be a string
mnemonic = "branka dorost klam slanina omezit cuketa kazeta cizost rozchod tvaroh majetek kyvadlo"

# Generate with automatic language detection and passphrase (empty)
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
# Generate with automatic language detection and custom passphrase
seed_bytes = Bip39SeedGenerator(mnemonic).Generate("my_passphrase")
# Generate specifying the language
seed_bytes = Bip39SeedGenerator(mnemonic, Bip39Languages.CZECH).Generate()

Substrate seed generation

copy iconCopydownload iconDownload
from bip_utils import Bip39Languages, Bip39WordsNum, Bip39MnemonicGenerator, SubstrateBip39SeedGenerator

# Mnemonic can be generated with Bip39MnemonicGenerator
mnemonic = Bip39MnemonicGenerator().FromWordsNumber(Bip39WordsNum.WORDS_NUM_12)
# Or it can be a string
mnemonic = "branka dorost klam slanina omezit cuketa kazeta cizost rozchod tvaroh majetek kyvadlo"

# Generate with automatic language detection and passphrase (empty)
seed_bytes = SubstrateBip39SeedGenerator(mnemonic).Generate()
# Generate with automatic language detection and custom passphrase
seed_bytes = SubstrateBip39SeedGenerator(mnemonic).Generate("my_passphrase")
# Generate specifying the language
seed_bytes = SubstrateBip39SeedGenerator(mnemonic, Bip39Languages.CZECH).Generate()

Mnemonic generation

copy iconCopydownload iconDownload
import binascii
from bip_utils import MoneroEntropyBitLen, MoneroEntropyGenerator, MoneroMnemonicGenerator, MoneroWordsNum, MoneroLanguages

# Generate a random mnemonic string of 25 words with default language (English)
# A Mnemonic object will be returned
mnemonic = MoneroMnemonicGenerator().FromWordsNumber(MoneroWordsNum.WORDS_NUM_25)

# Get words count
print(mnemonic.WordsCount())
# Get as string
print(mnemonic.ToStr())
print(str(mnemonic))
# Get as list of strings
print(mnemonic.ToList())

# Generate a random mnemonic string of 13 words by specifying the language
mnemonic = MoneroMnemonicGenerator(MoneroLanguages.ITALIAN).FromWordsNumber(MoneroWordsNum.WORDS_NUM_13)

# Generate the mnemonic string from entropy bytes
entropy_bytes = binascii.unhexlify(b"00000000000000000000000000000000")
mnemonic = MoneroMnemonicGenerator().FromEntropyNoChecksum(entropy_bytes)
mnemonic = MoneroMnemonicGenerator(MoneroLanguages.FRENCH).FromEntropyWithChecksum(entropy_bytes)

# Generate mnemonic from random 256-bit entropy (with and without checksum)
entropy_bytes = MoneroEntropyGenerator(MoneroEntropyBitLen.BIT_LEN_256).Generate()
mnemonic = MoneroMnemonicGenerator().FromEntropyNoChecksum(entropy_bytes)
mnemonic = MoneroMnemonicGenerator().FromEntropyWithChecksum(entropy_bytes)

Mnemonic validation

copy iconCopydownload iconDownload
from bip_utils import (
    MoneroChecksumError, MoneroLanguages, MoneroWordsNum, MoneroMnemonicGenerator, MoneroMnemonicValidator, MoneroMnemonicDecoder
)

# Mnemonic can be generated with MoneroMnemonicGenerator
mnemonic = MoneroMnemonicGenerator().FromWordsNumber(MoneroWordsNum.WORDS_NUM_25)
# Or it can be a string
mnemonic = "calamity atlas buzzer tyrant natural bumper taboo nozzle puck obtains acoustic aphid decay jittery evicted cuddled love educated koala puddle tarnished necklace anvil axis calamity"

# Get if a mnemonic is valid, return bool
is_valid = MoneroMnemonicValidator().IsValid(mnemonic)
# Validate a mnemonic, raise exceptions
try:
    MoneroMnemonicValidator().Validate(mnemonic)
    # Valid...
except MoneroChecksumError:
    # Invalid checksum...
    pass
except ValueError:
    # Invalid length or language...
    pass

# Use MoneroMnemonicDecoder to get back the entropy bytes from a mnemonic, specifying the language
entropy_bytes = MoneroMnemonicDecoder(MoneroLanguages.ENGLISH).Decode(mnemonic)
# Like before with automatic language detection
entropy_bytes = MoneroMnemonicDecoder().Decode(mnemonic)

Seed generation

copy iconCopydownload iconDownload
from bip_utils import MoneroLanguages, MoneroWordsNum, MoneroMnemonicGenerator, MoneroSeedGenerator

# Mnemonic can be generated with MoneroMnemonicGenerator
mnemonic = MoneroMnemonicGenerator().FromWordsNumber(MoneroWordsNum.WORDS_NUM_25)
# Or it can be a string
mnemonic = "fianza dedo mosca bufón bello amable amigo lamer narrar elixir mejilla peine libertad payaso orgullo obtener ganga morder editor orilla gen ocre abuelo anemia editor"

# Generate with automatic language detection and passphrase (empty)
seed_bytes = MoneroSeedGenerator(mnemonic).Generate()
# Generate specifying the language
seed_bytes = MoneroSeedGenerator(mnemonic, MoneroLanguages.SPANISH).Generate()

BIP-0038 library

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip38PubKeyModes, Bip38Decrypter, Bip38Encrypter, Bip38EcKeysGenerator, Secp256k1PrivateKey

passphrase = "DummyPassphrase"

# Private key bytes or a private key object can be used
priv_key = binascii.unhexlify(b'1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67')
priv_key = Secp256k1PrivateKey.FromBytes(
    binascii.unhexlify(b'1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67'))

# Encrypt without EC multiplication (compressed public key)
enc = Bip38Encrypter.EncryptNoEc(priv_key, passphrase, Bip38PubKeyModes.COMPRESSED)
print(enc)

# Decrypt without EC multiplication
dec, pub_key_mode = Bip38Decrypter.DecryptNoEc(enc, passphrase)
print(binascii.hexlify(dec))

# Encrypt without EC multiplication (uncompressed public key)
enc = Bip38Encrypter.EncryptNoEc(priv_key, passphrase, Bip38PubKeyModes.UNCOMPRESSED)
print(enc)

# Decrypt without EC multiplication
dec, pub_key_mode = Bip38Decrypter.DecryptNoEc(enc, passphrase)
print(binascii.hexlify(dec))


# Use EC multiplication to generate an intermediate passphrase without lot and sequence numbers
int_pass = Bip38EcKeysGenerator.GenerateIntermediatePassphrase(passphrase)
print(int_pass)
# Use EC multiplication to generate an encrypted private key from the intermediate passphrase
enc = Bip38EcKeysGenerator.GeneratePrivateKey(int_pass, Bip38PubKeyModes.COMPRESSED)
print(enc)

# Decrypt with EC multiplication
dec, pub_key_mode = Bip38Decrypter.DecryptEc(enc, passphrase)
print(binascii.hexlify(dec))

# Use EC multiplication to generate an intermediate passphrase with lot and sequence numbers
int_pass = Bip38EcKeysGenerator.GenerateIntermediatePassphrase(passphrase,
                                                               lot_num=100000,
                                                               sequence_num=1)
print(int_pass)
# Use EC multiplication to generate an encrypted private key from the intermediate passphrase
enc = Bip38EcKeysGenerator.GeneratePrivateKey(int_pass, Bip38PubKeyModes.UNCOMPRESSED)
print(enc)

# Decrypt with EC multiplication
dec, pub_key_mode = Bip38Decrypter.DecryptEc(enc, passphrase)
print(binascii.hexlify(dec))

# Or, you can use Bip38Encrypter for generating keys with EC multiplication in one-shot
enc = Bip38Encrypter.GeneratePrivateKeyEc(passphrase,
                                          Bip38PubKeyModes.COMPRESSED,
                                          lot_num=100000,
                                          sequence_num=1)
print(enc)

Construction from seed

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip39SeedGenerator, Bip32Secp256k1

# Generate from mnemonic
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
# Specify seed manually
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")

# Construct from seed, derivation path returned: m
bip32_ctx = Bip32Secp256k1.FromSeed(seed_bytes)
# Print master key in extended format
print(bip32_ctx.PrivateKey().ToExtended())

Construction from extended key

copy iconCopydownload iconDownload
from bip_utils import Bip32Secp256k1

# Private extended key from derivation path m/0'/1 (depth 2)
key_str = "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs"
# Construct from key (return object has depth 2)
bip32_ctx = Bip32Secp256k1.FromExtendedKey(key_str)
# Return false
print(bip32_ctx.IsPublicOnly())
# Print keys
print(bip32_ctx.PrivateKey().ToExtended())
print(bip32_ctx.PublicKey().ToExtended())

# Public extended key from derivation path m/0'/1 (depth 2)
key_str = "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"
# Construct from key (return object has depth 2)
# The object will be public-only and support only public derivation
bip32_ctx = Bip32Secp256k1.FromExtendedKey(key_str)
# Return true
print(bip32_ctx.IsPublicOnly())
# Print public key
print(bip32_ctx.PublicKey().ToExtended())

Construction from private key

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip32Secp256k1, Secp256k1PrivateKey

# Construct from private key bytes
priv_key_bytes = binascii.unhexlify(b"e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
bip32_ctx = Bip32Secp256k1.FromPrivateKey(priv_key_bytes)
# Or key object directly (the curve shall match the one of the Bip32 class, otherwise a Bip32KeyError will be raised)
bip32_ctx = Bip32Secp256k1.FromPrivateKey(Secp256k1PrivateKey.FromBytes(priv_key_bytes))
# Print keys and data
print(bip32_ctx.PrivateKey().Raw().ToHex())
print(bip32_ctx.PublicKey().RawCompressed().ToHex())
print(bip32_ctx.Depth().ToInt())
print(bip32_ctx.ChainCode().ToBytes())
print(bip32_ctx.ParentFingerPrint().ToBytes())

Construction from public key

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip32KeyError, Bip32Secp256k1, Secp256k1PublicKey

# Construct from public key bytes
pub_key_bytes = binascii.unhexlify(b"0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2")
bip32_ctx = Bip32Secp256k1.FromPublicKey(pub_key_bytes)
# Or key object directly (the curve shall match the one of the Bip32 class, otherwise a Bip32KeyError will be raised)
bip32_ctx = Bip32Secp256k1.FromPublicKey(Secp256k1PublicKey.FromBytes(pub_key_bytes))
# Print keys and data
print(bip32_ctx.PublicKey().RawCompressed().ToHex())
print(bip32_ctx.Depth().ToInt())
print(bip32_ctx.ChainCode().ToBytes())
print(bip32_ctx.ParentFingerPrint().ToBytes())

# Return true
print(bip32_ctx.IsPublicOnly())
# Getting the private key will raise a Bip32KeyError
try:
    print(bip32_ctx.PrivateKey().Raw().ToHex())
except Bip32KeyError as ex:
    print(ex)

Keys derivation

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip32Secp256k1, Bip32Utils

# Seed bytes
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")
# Path: m
bip32_ctx = Bip32Secp256k1.FromSeed(seed_bytes)
# Derivation path: m/0'/1'/2/3
bip32_ctx = bip32_ctx.ChildKey(Bip32Utils.HardenIndex(0)) \
                     .ChildKey(Bip32Utils.HardenIndex(1)) \
                     .ChildKey(2)                         \
                     .ChildKey(3)
# Print keys in extended format
print(bip32_ctx.PrivateKey().ToExtended())
print(bip32_ctx.PublicKey().ToExtended())

# Print keys bytes
print(bip32_ctx.PrivateKey().Raw().ToBytes())
print(bytes(bip32_ctx.PrivateKey().Raw()))
print(bip32_ctx.PublicKey().RawCompressed().ToBytes())
print(bytes(bip32_ctx.PublicKey().RawCompressed()))
print(bip32_ctx.PublicKey().RawUncompressed().ToBytes())
print(bytes(bip32_ctx.PublicKey().RawUncompressed()))

# Print keys in hex format
print(bip32_ctx.PrivateKey().Raw().ToHex())
print(str(bip32_ctx.PrivateKey().Raw()))
print(bip32_ctx.PublicKey().RawCompressed().ToHex())
print(str(bip32_ctx.PublicKey().RawCompressed()))
print(bip32_ctx.PublicKey().RawUncompressed().ToHex())
print(str(bip32_ctx.PublicKey().RawUncompressed()))

# Print other BIP32 data
print(bip32_ctx.Index().IsHardened())
print(bip32_ctx.Index().ToInt())
print(int(bip32_ctx.Index()))
print(bip32_ctx.Index().ToBytes())
print(bytes(bip32_ctx.Index()))

print(bip32_ctx.Depth().ToInt())
print(int(bip32_ctx.Depth()))
print(bip32_ctx.Depth().ToBytes())
print(bytes(bip32_ctx.Depth()))

print(bip32_ctx.ChainCode().ToHex())
print(str(bip32_ctx.ChainCode()))
print(bip32_ctx.ChainCode().ToBytes())
print(bytes(bip32_ctx.ChainCode()))

print(bip32_ctx.FingerPrint().IsMasterKey())
print(str(bip32_ctx.FingerPrint()))
print(bip32_ctx.FingerPrint().ToBytes())
print(bytes(bip32_ctx.FingerPrint()))

print(bip32_ctx.ParentFingerPrint().IsMasterKey())
print(bip32_ctx.ParentFingerPrint().ToBytes())
print(bytes(bip32_ctx.ParentFingerPrint()))

# Alternative: use DerivePath method
bip32_ctx = Bip32Secp256k1.FromSeed(seed_bytes)
bip32_ctx = bip32_ctx.DerivePath("0'/1'/2/3")

# DerivePath derives from the current depth, so it can be split
bip32_ctx = Bip32Secp256k1.FromSeed(seed_bytes)
bip32_ctx = bip32_ctx.DerivePath("0'/1'")   # Derivation path: m/0'/1'
bip32_ctx = bip32_ctx.DerivePath("2/3")     # Derivation path: m/0'/1'/2/3

Parse path

copy iconCopydownload iconDownload
from bip_utils import Bip32Path, Bip32PathParser, Bip32Utils

# Parse path, Bip32PathError is raised in case of errors
path = Bip32PathParser.Parse("0'/1'/2")
# 'p' can be used as an alternative character instead of '
path = Bip32PathParser.Parse("0p/1p/2")
# "m" can be added at the beginning
path = Bip32PathParser.Parse("m/0'/1'/2")
# Or construct directly from a list of indexes
path = Bip32Path([0, 1, Bip32Utils.HardenIndex(2)])

# Get length
print(path.Length())
# Get as string
print(path.ToStr())
print(str(path))
# Print elements info and value
for elem in path:
    print(elem.IsHardened())
    print(elem.ToBytes())
    print(bytes(elem))
    print(elem.ToInt())
    print(int(elem))
# Get as list of integers
path_list = path.ToList()
for elem in path_list:
    print(elem)

Construction from seed

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip39SeedGenerator, Bip44Coins, Bip44

# Generate from mnemonic
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
# Specify seed manually
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")
# Derivation path returned: m
bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.BITCOIN)

Construction from extended key

copy iconCopydownload iconDownload
from bip_utils import Bip44Coins, Bip44

# Private extended key
key_str = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"
# Construct from extended key
bip44_mst_ctx = Bip44.FromExtendedKey(key_str, Bip44Coins.BITCOIN)

Construction from private key

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip44Coins, Bip44, Secp256k1PrivateKey

# Construct from private key bytes
priv_key_bytes = binascii.unhexlify(b"e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
bip44_mst_ctx = Bip44.FromPrivateKey(priv_key_bytes, Bip44Coins.BITCOIN)
# Or key object directly (the key type shall match the curve used by the coin, otherwise Bip32KeyError will be raised)
bip44_mst_ctx = Bip44.FromPrivateKey(Secp256k1PrivateKey.FromBytes(priv_key_bytes), Bip44Coins.BITCOIN)

Keys derivation

copy iconCopydownload iconDownload
m / purpose' / coin_type' / account' / change / address_index

Default derivation paths

copy iconCopydownload iconDownload
m / purpose' / coin_type' / account' / change / address_index

Monero addresses generation

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip44Coins, Bip44, Monero

# Seed bytes
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4")

# Create BIP44 object and derive default path
bip44_def_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.MONERO_ED25519_SLIP).DeriveDefaultPath()

# Create Monero object from the BIP44 private key -> monero_priv_spend_key = sc_reduce(kekkak256(bip44_priv_key))
monero = Monero.FromBip44PrivateKey(bip44_def_ctx.PrivateKey().Raw().ToBytes())

# Print keys
print(monero.PrivateSpendKey().Raw().ToHex())
print(monero.PrivateViewKey().Raw().ToHex())
print(monero.PublicSpendKey().RawCompressed().ToHex())
print(monero.PublicViewKey().RawCompressed().ToHex())

# Print primary address
print(monero.PrimaryAddress())
# Print subaddresses
print(monero.Subaddress(0))         # Account 0 (default), Subaddress 0 (same as primary address)
print(monero.Subaddress(1))         # Account 0 (default), Subaddress 1
print(monero.Subaddress(0, 1))      # Account 1, Subaddress 0
print(monero.Subaddress(1, 1))      # Account 1, Subaddress 1

Construction from seed

copy iconCopydownload iconDownload
import binascii
from bip_utils import SubstrateBip39SeedGenerator, SubstrateCoins, Substrate

# Generate from mnemonic
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
seed_bytes = SubstrateBip39SeedGenerator(mnemonic).Generate()
# Specify seed manually. The seed is required to be 32-byte long. If longer, only the first 32-byte will be considered.
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc1")

# Construction from seed
substrate_ctx = Substrate.FromSeed(seed_bytes, SubstrateCoins.POLKADOT)
# Construction from seed by specifying the path
substrate_ctx = Substrate.FromSeedAndPath(seed_bytes, "//hard/soft", SubstrateCoins.POLKADOT)

Construction from private/public key

copy iconCopydownload iconDownload
import binascii
from bip_utils import SubstrateCoins, Substrate, Sr25519PublicKey, Sr25519PrivateKey

# Construction from private key bytes
priv_key_bytes = binascii.unhexlify(b"2ec306fc1c5bc2f0e3a2c7a6ec6014ca4a0823a7d7d42ad5e9d7f376a1c36c0d14a2ddb1ef1df4adba49f3a4d8c0f6205117907265f09a53ccf07a4e8616dfd8")
substrate_ctx = Substrate.FromPrivateKey(priv_key_bytes, SubstrateCoins.POLKADOT)
# Or key object directly
substrate_ctx = Substrate.FromPrivateKey(Sr25519PrivateKey.FromBytes(priv_key_bytes), SubstrateCoins.POLKADOT)
# Return false
print(substrate_ctx.IsPublicOnly())

# Construction from public key bytes
# The object will be public-only and support only public derivation
pub_key_bytes = binascii.unhexlify(b"66933bd1f37070ef87bd1198af3dacceb095237f803f3d32b173e6b425ed7972")
substrate_ctx = Substrate.FromPublicKey(pub_key_bytes, SubstrateCoins.POLKADOT)
# Or key object directly
substrate_ctx = Substrate.FromPublicKey(Sr25519PublicKey.FromBytes(pub_key_bytes), SubstrateCoins.POLKADOT)
# Return true
print(substrate_ctx.IsPublicOnly())

Keys derivation

copy iconCopydownload iconDownload
import binascii
from bip_utils import SubstrateCoins, Substrate

# Seed bytes
seed_bytes = binascii.unhexlify(b"5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc1")
# Construction from seed
substrate_ctx = Substrate.FromSeed(seed_bytes, SubstrateCoins.POLKADOT)
# Print master keys and address
print(substrate_ctx.PrivateKey().Raw().ToBytes())
print(bytes(substrate_ctx.PrivateKey().Raw()))
print(substrate_ctx.PrivateKey().Raw().ToHex())
print(substrate_ctx.PublicKey().RawCompressed().ToBytes())
print(bytes(substrate_ctx.PublicKey().RawCompressed()))
print(substrate_ctx.PublicKey().RawCompressed().ToHex())
print(substrate_ctx.PublicKey().ToAddress())

# Derive a child key
substrate_ctx = substrate_ctx.ChildKey("//hard")
# Print derived keys and address
print(substrate_ctx.PrivateKey().Raw().ToHex())
print(substrate_ctx.PublicKey().RawCompressed().ToHex())
print(substrate_ctx.PublicKey().ToAddress())
# Print path
print(substrate_ctx.Path().ToStr())

# Derive a path
substrate_ctx = substrate_ctx.DerivePath("//hard/soft") # Path: //hard/soft
substrate_ctx = substrate_ctx.DerivePath("//0/1")       # Path: //hard/soft//0/1
# Print derived keys and address
print(substrate_ctx.PrivateKey().Raw().ToHex())
print(substrate_ctx.PublicKey().RawCompressed().ToHex())
print(substrate_ctx.PublicKey().ToAddress())
# Print path
print(substrate_ctx.Path().ToStr())

Parse path

copy iconCopydownload iconDownload
from bip_utils import SubstratePath, SubstratePathParser

# Parse path, SubstratePathError is raised in case of errors
path = SubstratePathParser.Parse("//hard/soft")
# Or construct directly from a list of indexes
path = SubstratePath(["//hard", "/soft"])

# Get length
print(path.Length())
# Get as string
print(path.ToStr())
print(str(path))
# Print elements info and value
for elem in path:
    print(elem.IsHard())
    print(elem.IsSoft())
    print(elem.ToStr())
    print(str(elem))
    print(elem.ChainCode())
# Get as list of strings
path_list = path.ToList()
for elem in path_list:
    print(elem)

Construction from seed

copy iconCopydownload iconDownload
import binascii
from bip_utils import MoneroCoins, Monero

# Seed bytes
seed_bytes = binascii.unhexlify(b"851466f170f7d1dd88325d9f6b89328166fa23e3af712e74aa27cb16837ac10d")
# Create from seed (default: Monero main net)
monero = Monero.FromSeed(seed_bytes)
# Return false
print(monero.IsWatchOnly())

# Create from seed for Monero stage net
monero = Monero.FromSeed(seed_bytes, MoneroCoins.MONERO_STAGENET)
# Create from seed for Monero test net
monero = Monero.FromSeed(seed_bytes, MoneroCoins.MONERO_TESTNET)

Construction from private spend key

copy iconCopydownload iconDownload
import binascii
from bip_utils import MoneroCoins, Monero, Ed25519MoneroPrivateKey

# Create from private spend key bytes (default: Monero main net)
key_bytes = binascii.unhexlify(b"2c9623882df4940a734b009e0732ce5a8de7a62c4c1a2a53767a8f6c04874107")
monero = Monero.FromPrivateSpendKey(key_bytes)
# Or key object directly
monero = Monero.FromPrivateSpendKey(Ed25519MoneroPrivateKey.FromBytes(key_bytes))
# Return false
print(monero.IsWatchOnly())

# Create from private spend key bytes for Monero test net
key_bytes = binascii.unhexlify(b"2c9623882df4940a734b009e0732ce5a8de7a62c4c1a2a53767a8f6c04874107")
monero = Monero.FromPrivateSpendKey(key_bytes, MoneroCoins.MONERO_TESTNET)

Watch-only class

copy iconCopydownload iconDownload
import binascii
from bip_utils import MoneroKeyError, MoneroCoins, Monero, Ed25519MoneroPrivateKey, Ed25519MoneroPublicKey

# Keys
priv_vkey_bytes = binascii.unhexlify(b"14467d1b9bb8d1fcfb5b7ae08cc9994367e917efd7e08cf94f9882ffa0629e09")
pub_skey_bytes = binascii.unhexlify(b"a95d2eb7e157f0a169df0a9c490dcd8e0feefb31bbf1328ca4938592a9d02422")

# Create from watch-only keys (default: Monero main net)
monero = Monero.FromWatchOnly(priv_vkey_bytes, pub_skey_bytes)
# Or key object directly
monero = Monero.FromWatchOnly(Ed25519MoneroPrivateKey.FromBytes(priv_vkey_bytes),
                              Ed25519MoneroPublicKey.FromBytes(pub_skey_bytes))
# Return true
print(monero.IsWatchOnly())
# Getting the private spend key will raise a MoneroKeyError
try:
    print(monero.PrivateSpendKey().Raw().ToHex())
except MoneroKeyError as ex:
    print(ex)


# Create from watch-only keys for Monero test net
monero = Monero.FromWatchOnly(priv_vkey_bytes, pub_skey_bytes, MoneroCoins.MONERO_TESTNET)

Example of usage

copy iconCopydownload iconDownload
import binascii
from bip_utils import Monero

# Create from seed bytes
seed_bytes = binascii.unhexlify(b"851466f170f7d1dd88325d9f6b89328166fa23e3af712e74aa27cb16837ac10d")
monero = Monero.FromSeed(seed_bytes)
# Print if watch-only
print(monero.IsWatchOnly())

# Print keys
print(monero.PrivateSpendKey().Raw().ToHex())
print(monero.PrivateSpendKey().Raw().ToBytes())
print(monero.PrivateViewKey().Raw().ToHex())
print(monero.PrivateViewKey().Raw().ToBytes())
print(monero.PublicSpendKey().RawCompressed().ToHex())
print(monero.PublicSpendKey().RawCompressed().ToBytes())
print(monero.PublicViewKey().RawCompressed().ToHex())
print(monero.PublicViewKey().RawCompressed().ToBytes())

# Print primary address
print(monero.PrimaryAddress())
# Print integrated address
payment_id = binascii.unhexlify(b"ccc172c2ffcac9d8")
print(monero.IntegratedAddress(payment_id))
# Print subaddresses
print(monero.Subaddress(0))         # Account 0 (default), Subaddress 0 (same as primary address)
print(monero.Subaddress(1))         # Account 0 (default), Subaddress 1
print(monero.Subaddress(0, 1))      # Account 1, Subaddress 0
print(monero.Subaddress(1, 1))      # Account 1, Subaddress 1

Addresses encoding/decoding

copy iconCopydownload iconDownload
import binascii
from bip_utils import *

#
# Addresses that require a secp256k1 curve
#

# Public key bytes or a public key object can be used
pub_key = binascii.unhexlify(b"022f469a1b5498da2bc2f1e978d1e4af2ce21dd10ae5de64e4081e062f6fc6dca2")
pub_key = Secp256k1PublicKey.FromBytes(
    binascii.unhexlify(b"022f469a1b5498da2bc2f1e978d1e4af2ce21dd10ae5de64e4081e062f6fc6dca2")
)

# P2PKH address with parameters from generic configuration
addr = P2PKHAddrEncoder.EncodeKey(pub_key,
                                  net_ver=CoinsConf.BitcoinMainNet.Params("p2pkh_net_ver"))
# Or with custom parameters
addr = P2PKHAddrEncoder.EncodeKey(pub_key,
                                  net_ver=b"\x01")
# Or simply with the default parameters from BIP:
addr = P2PKHAddrEncoder.EncodeKey(pub_key,
                                  **Bip44Conf.BitcoinMainNet.AddrParams())
# Same as before for decoding
pub_key_hash = P2PKHAddrDecoder.DecodeAddr(addr,
                                           net_ver=CoinsConf.BitcoinMainNet.Params("p2pkh_net_ver"))

# Same for P2SH
addr = P2SHAddrEncoder.EncodeKey(pub_key,
                                 net_ver=CoinsConf.BitcoinMainNet.Params("p2sh_net_ver"))
addr = P2SHAddrEncoder.EncodeKey(pub_key,
                                 net_ver=b"\x01")
addr = P2SHAddrEncoder.EncodeKey(pub_key,
                                 **Bip49Conf.BitcoinMainNet.AddrParams())
pub_key_hash = P2SHAddrDecoder.DecodeAddr(addr,
                                          net_ver=CoinsConf.BitcoinMainNet.Params("p2sh_net_ver"))
# Same for P2WPKH
addr = P2WPKHAddrEncoder.EncodeKey(pub_key,
                                   hrp=CoinsConf.BitcoinMainNet.Params("p2wpkh_hrp"),
                                   wit_ver=CoinsConf.BitcoinMainNet.Params("p2wpkh_wit_ver"))
addr = P2WPKHAddrEncoder.EncodeKey(pub_key,
                                   hrp="hrp",
                                   wit_ver=0)
addr = P2WPKHAddrEncoder.EncodeKey(pub_key,
                                   **Bip84Conf.BitcoinMainNet.AddrParams())
pub_key_hash = P2WPKHAddrDecoder.DecodeAddr(addr,
                                            hrp=CoinsConf.BitcoinMainNet.Params("p2wpkh_hrp"),
                                            wit_ver=CoinsConf.BitcoinMainNet.Params("p2wpkh_wit_ver"))

# P2PKH address in Bitcoin Cash format with parameters from generic configuration
addr = BchP2PKHAddrEncoder.EncodeKey(pub_key,
                                     hrp=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_hrp"),
                                     net_ver=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_net_ver"))
# Or with custom parameters
addr = BchP2PKHAddrEncoder.EncodeKey(pub_key,
                                     hrp="hrp",
                                     net_ver=b"\x01")
# Or with the default parameters from BIP configuration:
addr = BchP2PKHAddrEncoder.EncodeKey(pub_key,
                                     **Bip44Conf.BitcoinCashMainNet.AddrParams())
# Same as before for decoding
pub_key_hash = BchP2PKHAddrDecoder.DecodeAddr(addr,
                                              hrp=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_hrp"),
                                              net_ver=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_net_ver"))
# Same for P2SH
addr = BchP2SHAddrEncoder.EncodeKey(pub_key,
                                    hrp=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_hrp"),
                                    net_ver=CoinsConf.BitcoinCashMainNet.Params("p2pkh_std_net_ver"))
addr = BchP2SHAddrEncoder.EncodeKey(pub_key,
                                    hrp="hrp",
                                    net_ver=b"\x01")
addr = BchP2SHAddrEncoder.EncodeKey(pub_key,
                                    **Bip49Conf.BitcoinCashMainNet.AddrParams())
pub_key_hash = BchP2SHAddrDecoder.DecodeAddr(addr,
                                             hrp=CoinsConf.BitcoinCashMainNet.Params("p2sh_std_hrp"),
                                             net_ver=CoinsConf.BitcoinCashMainNet.Params("p2sh_std_net_ver"))

# Ethereum address
# Checksum encoding can be skipped to get a lower case address
addr = EthAddrEncoder.EncodeKey(pub_key)
pub_key_hash = EthAddrDecoder.DecodeAddr(addr)
addr = EthAddrEncoder.EncodeKey(pub_key, skip_chksum_enc=True)
pub_key_hash = EthAddrDecoder.DecodeAddr(addr, skip_chksum_enc=True)
# Tron address
addr = TrxAddrEncoder.EncodeKey(pub_key)
pub_key_hash = TrxAddrDecoder.DecodeAddr(addr)
# AVAX address
addr = AvaxPChainAddrEncoder.EncodeKey(pub_key)
pub_key_hash = AvaxPChainAddrDecoder.DecodeAddr(addr)
addr = AvaxXChainAddrEncoder.EncodeKey(pub_key)
pub_key_hash = AvaxXChainAddrDecoder.DecodeAddr(addr)
# Atom addresses with parameters from generic configuration
addr = AtomAddrEncoder.EncodeKey(pub_key,
                                 hrp=CoinsConf.Cosmos.Params("addr_hrp"))
addr = AtomAddrEncoder.EncodeKey(pub_key,
                                 hrp=CoinsConf.BinanceChain.Params("addr_hrp"))
# Or with custom parameters
addr = AtomAddrEncoder.EncodeKey(pub_key,
                                 hrp="custom")
# Or with the default parameters from BIP configuration:
addr = AtomAddrEncoder.EncodeKey(pub_key,
                                 **Bip44Conf.Cosmos.AddrParams())
addr = AtomAddrEncoder.EncodeKey(pub_key,
                                 **Bip44Conf.Kava.AddrParams())
# Same as before for decoding
pub_key_hash = AtomAddrDecoder.DecodeAddr(addr,
                                          hrp=CoinsConf.Kava.Params("addr_hrp"))

# Filecoin address
addr = FilSecp256k1AddrEncoder.EncodeKey(pub_key)
pub_key_hash = FilSecp256k1AddrDecoder.DecodeAddr(addr)
# OKEx Chain address
addr = OkexAddrEncoder.EncodeKey(pub_key)
pub_key_hash = OkexAddrDecoder.DecodeAddr(addr)
# Harmony One address
addr = OneAddrEncoder.EncodeKey(pub_key)
pub_key_hash = OneAddrDecoder.DecodeAddr(addr)
# Ripple address
addr = XrpAddrEncoder.EncodeKey(pub_key)
pub_key_hash = XrpAddrDecoder.DecodeAddr(addr)
# Zilliqa address
addr = ZilAddrEncoder.EncodeKey(pub_key)
pub_key_hash = ZilAddrDecoder.DecodeAddr(addr)

#
# Addresses that require a ed25519 curve
#

# Public key bytes or a public key object can be used
pub_key = binascii.unhexlify(b"00dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832")
pub_key = Ed25519PublicKey.FromBytes(
    binascii.unhexlify(b"00dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832"))

# Algorand address
addr = AlgoAddrEncoder.EncodeKey(pub_key)
pub_key_bytes = AlgoAddrDecoder.DecodeAddr(addr)
# Elrond address
addr = EgldAddrEncoder.EncodeKey(pub_key)
pub_key_bytes = EgldAddrDecoder.DecodeAddr(addr)

# Solana address
addr = SolAddrEncoder.EncodeKey(pub_key)
pub_key_bytes = SolAddrDecoder.DecodeAddr(addr)

# Stellar address with custom parameters
addr = XlmAddrEncoder.EncodeKey(pub_key,
                                addr_type=XlmAddrTypes.PUB_KEY)
# Or with the default parameters from BIP configuration:
addr = XlmAddrEncoder.EncodeKey(pub_key,
                                **Bip44Conf.Stellar.AddrParams())
# Same as before for decoding
pub_key_bytes = XlmAddrDecoder.DecodeAddr(addr,
                                          addr_type=XlmAddrTypes.PUB_KEY)

# Substrate address with parameters from generic configuration
addr = SubstrateEd25519AddrEncoder.EncodeKey(pub_key,
                                             ss58_format=CoinsConf.Polkadot.Params("addr_ss58_format"))
# Or with custom parameters
addr = SubstrateEd25519AddrEncoder.EncodeKey(pub_key,
                                             ss58_format=5)

# Or with the default parameters from BIP/Substrate:
addr = SubstrateEd25519AddrEncoder.EncodeKey(pub_key,
                                             **Bip44Conf.PolkadotEd25519Slip.AddrParams())
addr = SubstrateEd25519AddrEncoder.EncodeKey(pub_key,
                                             **SubstrateConf.Polkadot.AddrParams())
# Same as before for decoding
pub_key_bytes = SubstrateEd25519AddrDecoder.DecodeAddr(addr,
                                                       ss58_format=CoinsConf.Polkadot.Params("addr_ss58_format"))

# Tezos address with custom parameters
addr = XtzAddrEncoder.EncodeKey(pub_key,
                                prefix=XtzAddrPrefixes.TZ1)
# Or with the default parameters from BIP configuration:
addr = XtzAddrEncoder.EncodeKey(pub_key,
                                **Bip44Conf.Tezos.AddrParams())
# Same as before for decoding
pub_key_hash = XtzAddrDecoder.DecodeAddr(addr,
                                         prefix=XtzAddrPrefixes.TZ1)

#
# Addresses that require a ed25519-blake2b curve
#

# Public key bytes or a public key object can be used
pub_key = binascii.unhexlify(b"00dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832")
pub_key = Ed25519Blake2bPublicKey.FromBytes(
    binascii.unhexlify(b"00dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832")
)

# Nano address
addr = NanoAddrEncoder.EncodeKey(pub_key)
pub_key_bytes = NanoAddrDecoder.DecodeAddr(addr)

#
# Addresses that require a ed25519-monero curve
#

# Public key bytes or a public key object can be used
pub_skey = binascii.unhexlify(b"a95d2eb7e157f0a169df0a9c490dcd8e0feefb31bbf1328ca4938592a9d02422")
pub_skey = Ed25519MoneroPublicKey.FromBytes(
    binascii.unhexlify(b"a95d2eb7e157f0a169df0a9c490dcd8e0feefb31bbf1328ca4938592a9d02422")
)
pub_vkey = binascii.unhexlify(b"dc2a1b478b8cc0ee655324fb8299c8904f121ab113e4216fbad6fe6d000758f5")
pub_vkey = Ed25519MoneroPublicKey.FromBytes(
    binascii.unhexlify(b"dc2a1b478b8cc0ee655324fb8299c8904f121ab113e4216fbad6fe6d000758f5")
)

# Monero address
addr = XmrAddrEncoder.EncodeKey(pub_skey,
                                pub_vkey=pub_vkey,
                                net_ver=CoinsConf.MoneroMainNet.Params("addr_net_ver"))
# Equivalent
addr = XmrAddrEncoder.EncodeKey(pub_skey,
                                pub_vkey=pub_vkey,
                                net_ver=MoneroConf.MainNet.AddrNetVersion())
# Decoding
pub_key_bytes = XmrAddrDecoder.DecodeAddr(addr,
                                          net_ver=CoinsConf.MoneroMainNet.Params("addr_net_ver"))

# Monero integrated address
addr = XmrIntegratedAddrEncoder.EncodeKey(pub_skey,
                                          pub_vkey=pub_vkey,
                                          net_ver=CoinsConf.MoneroMainNet.Params("addr_int_net_ver"),
                                          payment_id=binascii.unhexlify(b"d7af025ab223b74e"))
# Equivalent
addr = XmrIntegratedAddrEncoder.EncodeKey(pub_skey,
                                          pub_vkey=pub_vkey,
                                          net_ver=MoneroConf.MainNet.IntegratedAddrNetVersion(),
                                          payment_id=binascii.unhexlify(b"d7af025ab223b74e"))
# Decoding
pub_key_bytes = XmrIntegratedAddrDecoder.DecodeAddr(addr,
                                                    net_ver=CoinsConf.MoneroMainNet.Params("addr_int_net_ver"),
                                                    payment_id=binascii.unhexlify(b"d7af025ab223b74e"))

#
# Addresses that require a nist256p1 curve
#

# Public key bytes or a public key object can be used
pub_key = binascii.unhexlify(b"038ea003d38b3f2043e681f06f56b3864d28d73b4f243aee90ed04a28dbc058c5b")
pub_key = Nist256p1PublicKey.FromBytes(
    binascii.unhexlify(b"038ea003d38b3f2043e681f06f56b3864d28d73b4f243aee90ed04a28dbc058c5b"))

# NEO address with parameters from generic configuration
addr = NeoAddrEncoder.EncodeKey(pub_key,
                                ver=CoinsConf.Neo.Params("addr_ver"))
# Or with custom parameters
addr = NeoAddrEncoder.EncodeKey(pub_key,
                                ver=b"\x10")
# Or with the default parameters from BIP configuration:
addr = NeoAddrEncoder.EncodeKey(pub_key,
                                **Bip44Conf.Neo.AddrParams())
# Same as before for decoding
pub_key_hash = NeoAddrDecoder.DecodeAddr(addr,
                                         ver=CoinsConf.Neo.Params("addr_ver"))

#
# Addresses that require a sr25519 curve
#

# Public key bytes or a public key object can be used
pub_key = binascii.unhexlify(b"dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832")
pub_key = Sr25519PublicKey.FromBytes(
    binascii.unhexlify(b"dff41688eadfb8574c8fbfeb8707e07ecf571e96e929c395cc506839cc3ef832"))

# Substrate address (like before)
addr = SubstrateSr25519AddrEncoder.EncodeKey(pub_key,
                                             ss58_format=CoinsConf.Kusama.Params("addr_ss58_format"))
addr = SubstrateSr25519AddrEncoder.EncodeKey(pub_key,
                                             ss58_format=3)
addr = SubstrateSr25519AddrEncoder.EncodeKey(pub_key,
                                             **SubstrateConf.Kusama.AddrParams())
pub_key_bytes = SubstrateSr25519AddrDecoder.DecodeAddr(addr,
                                                       ss58_format=CoinsConf.Kusama.Params("addr_ss58_format"))

WIF

copy iconCopydownload iconDownload
import binascii
from bip_utils import Bip44Conf, CoinsConf, Secp256k1PrivateKey, WifPubKeyModes, WifDecoder, WifEncoder

# Private key bytes or a private key object can be used
priv_key = binascii.unhexlify(b'1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67')
priv_key = Secp256k1PrivateKey.FromBytes(binascii.unhexlify(b'1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67'))

# Encode/Decode with default parameters (Bitcoin main net, compressed public key)
enc = WifEncoder.Encode(priv_key)
dec, pub_key_mode = WifDecoder.Decode(enc)
# Specify the public key mode (it's returned by the decoding method as second element)
enc = WifEncoder.Encode(priv_key, pub_key_mode=WifPubKeyModes.COMPRESSED)
enc = WifEncoder.Encode(priv_key, pub_key_mode=WifPubKeyModes.UNCOMPRESSED)
dec, pub_key_mode = WifDecoder.Decode(enc)
# Encode/Decode with net version from configuration
enc = WifEncoder.Encode(priv_key,
                        CoinsConf.BitcoinMainNet.Params("wif_net_ver"))
dec, pub_key_mode = WifDecoder.Decode(enc,
                                      CoinsConf.BitcoinMainNet.Params("wif_net_ver"))
# Encode/Decode with net version from BIP
enc = WifEncoder.Encode(priv_key,
                        Bip44Conf.BitcoinMainNet.WifNetVersion())
dec, pub_key_mode = WifDecoder.Decode(enc,
                                      Bip44Conf.BitcoinMainNet.WifNetVersion())
# Encode/Decode with custom net version
enc = WifEncoder.Encode(priv_key,
                        b"\x00")
dec, pub_key_mode = WifDecoder.Decode(enc,
                                      b"\x00")

# Specify public key mode
enc = WifEncoder.Encode(priv_key,
                        CoinsConf.BitcoinMainNet.Params("wif_net_ver"))
dec, pub_key_mode = WifDecoder.Decode(enc,
                                      CoinsConf.BitcoinMainNet.Params("wif_net_ver"))

Base58

copy iconCopydownload iconDownload
import binascii
from bip_utils import Base58Alphabets, Base58Decoder, Base58Encoder, Base58XmrDecoder, Base58XmrEncoder

data_bytes = binascii.unhexlify(b"636363")

# Normal encode
enc = Base58Encoder.Encode(data_bytes)
# Check encode
chk_enc = Base58Encoder.CheckEncode(data_bytes)

# Normal decode
dec = Base58Decoder.Decode(enc)
# Check decode
# Base58ChecksumError is raised if checksum verification fails
# ValueError is raised in case of encoding errors
chk_dec = Base58Decoder.CheckDecode(chk_enc)

# Same as before with Ripple alphabet
enc = Base58Encoder.Encode(data_bytes, Base58Alphabets.RIPPLE)
chk_enc = Base58Encoder.CheckEncode(data_bytes, Base58Alphabets.RIPPLE)
dec = Base58Decoder.Decode(enc, Base58Alphabets.RIPPLE)
chk_dec = Base58Decoder.CheckDecode(chk_enc, Base58Alphabets.RIPPLE)

# Encode/Decode using Monero variation
enc = Base58XmrEncoder.Encode(data_bytes)
dec = Base58XmrDecoder.Decode(enc)

SS58

copy iconCopydownload iconDownload
import binascii
from bip_utils import SS58Decoder, SS58Encoder

data_bytes = binascii.unhexlify(b"e92b4b43a62fa66293f315486d66a67076e860e2aad76acb8e54f9bb7c925cd9")

# Encode
enc = SS58Encoder.Encode(data_bytes, ss58_format=0)
# Decode
ss58_format, dec = SS58Decoder.Decode(enc)

Bech32

copy iconCopydownload iconDownload
import binascii
from bip_utils import (
    Bech32Decoder, Bech32Encoder, BchBech32Encoder, BchBech32Decoder, SegwitBech32Decoder, SegwitBech32Encoder
)

data_bytes = binascii.unhexlify(b'9c90f934ea51fa0f6504177043e0908da6929983')

# Encode with bech32
enc = Bech32Encoder.Encode("cosmos", data_bytes)
# Decode with bech32
# Bech32ChecksumError is raised if checksum verification fails
# ValueError is raised  in case of encoding errors
dec = Bech32Decoder.Decode("cosmos", enc)

# Encode with segwit bech32
enc = SegwitBech32Encoder.Encode("bc", 0, data_bytes)
# Decode with segwit bech32
wit_ver, wit_prog = SegwitBech32Decoder.Decode("bc", enc)

# Encode with BCH bech32
enc = BchBech32Encoder.Encode("bitcoincash", b"\x00", data_bytes)
# Decode with BCH bech32
net_ver, dec = BchBech32Decoder.Decode("bitcoincash", enc)

How to fix error with pyinstaller after compilation in exe

copy iconCopydownload iconDownload
a = Analysis(['C:\\path\\to\\your\\main\\py file.py'],
             pathex=['C:\\path\\to\\search\\for\\imports'],  
             binaries=[],
             datas=[('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package\\xxxx\\yyyyy\\*', '.\\package\\xxxx\\yyyyy'),
             ('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package2\\zzz\\*', '.\\package2\\zzz'),
             ],
             hiddenimports=["a_package"], #A list of module names (relative or absolute) that should be part of the bundled app
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=None,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=None)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='nameOfExe',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False,
          icon='icon.ico') # specify icon
python -m PyInstaller -F main.spec --clean
-----------------------
a = Analysis(['C:\\path\\to\\your\\main\\py file.py'],
             pathex=['C:\\path\\to\\search\\for\\imports'],  
             binaries=[],
             datas=[('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package\\xxxx\\yyyyy\\*', '.\\package\\xxxx\\yyyyy'),
             ('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package2\\zzz\\*', '.\\package2\\zzz'),
             ],
             hiddenimports=["a_package"], #A list of module names (relative or absolute) that should be part of the bundled app
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=None,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=None)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='nameOfExe',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False,
          icon='icon.ico') # specify icon
python -m PyInstaller -F main.spec --clean

Community Discussions

Trending Discussions on bip_utils
  • How to fix error with pyinstaller after compilation in exe
Trending Discussions on bip_utils

QUESTION

How to fix error with pyinstaller after compilation in exe

Asked 2021-Oct-22 at 21:40

I compiled a Python script into an exe file, but after opening the exe, the console opens and an error occurs, then the console immediately closes. Perhaps this is due to the fact that I am using downloaded libraries (web3, bs4, hdwallet, bip_utils)

Traceback (most recent call last):
  File "CryptoWallet.py", line 11, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\__init__.py", line 21, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\wif\__init__.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\wif\wif.py", line 27, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\ecc\__init__.py", line 2, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\ecc\elliptic_curve_getter.py", line 31, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\ecc\secp256k1.py", line 39, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "bip_utils\ecc\secp256k1_keys_coincurve.py", line 25, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "coincurve\__init__.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "coincurve\context.py", line 4, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "coincurve\flags.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
  File "coincurve\_libsecp256k1.py", line 239, in <module>
  File "cffi\api.py", line 150, in dlopen
  File "cffi\api.py", line 832, in _make_ffi_library
  File "cffi\api.py", line 827, in _load_backend_lib
OSError: cannot load library 'C:\CryptoWallet\dist\CryptoWallet\coincurve\libsecp256k1.dll': error 0x7e.  Additionally, ctypes.util.find_library() did not manage to locate a library called 'C:\\\CryptoWallet\\dist\\CryptoWallet\\coincurve\\libsecp256k1.dll'
[21180] Failed to execute script 'CryptoWallet' due to unhandled exception!

ANSWER

Answered 2021-Oct-22 at 21:40

It seems like you need to copy the files that your project uses in to the exe. To do this you need to add-data when running pyinstaller. You can use pyinstaller spec files to configure the settings of your compilation.

Here is a example of spec file (you need to modify it for your use):

a = Analysis(['C:\\path\\to\\your\\main\\py file.py'],
             pathex=['C:\\path\\to\\search\\for\\imports'],  
             binaries=[],
             datas=[('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package\\xxxx\\yyyyy\\*', '.\\package\\xxxx\\yyyyy'),
             ('C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\package2\\zzz\\*', '.\\package2\\zzz'),
             ],
             hiddenimports=["a_package"], #A list of module names (relative or absolute) that should be part of the bundled app
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=None,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=None)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='nameOfExe',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False,
          icon='icon.ico') # specify icon

You can check other parameters and what they do from Pyinstaller docs.

This file can be run using:

python -m PyInstaller -F main.spec --clean

Source https://stackoverflow.com/questions/69682748

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install bip_utils

For the secp256k1 curve, it's possible to use either the coincurve or the ecdsa library. coincurve is much faster since it's a Python wrapper to the secp256k1 C library, while ecdsa is a pure Python implementation. By default, coincurve will be used but it's possible to disable it when installing.
Default installation (coincurve will be used for secp256k1) Using setuptools: python setup.py install Using pip, from this directory (local): pip install . Using pip, from PyPI: pip install bip_utils
Alternative installation (ecdsa will be used for secp256k1) Using setuptools: python setup.py install --coincurve=0 Using pip, from this directory (local): pip install . --install-option="--coincurve=0" Using pip, from PyPI: pip install bip_utils --install-option="--coincurve=0"
Run tests using pytest (it includes code coverage and report): tox -e pytest
Run tests using coverage (it includes code coverage and report): tox -e coverage

Support

For what regards Monero, it's also possible to generate the same addresses of the official wallets without using BIP44 derivation. Clearly, for those coins that support Smart Contracts (e.g. Ethereum, Tron, ...), the generated keys and addresses are valid for all the related tokens.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Cryptography Libraries
Compare Cryptography Libraries with Highest Support
Compare Cryptography Libraries with Permissive License
Compare Cryptography Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.