def ComputeChecksum(data_bytes): """ Compute Base58 checksum. Args: data_bytes (bytes): Data bytes Returns: bytes: Computed checksum """ return CryptoUtils.Sha256( CryptoUtils.Sha256(data_bytes))[:Base58Const.CHECKSUM_BYTE_LEN]
def FromEntropy(entropy_bytes: bytes) -> str: """ Generate mnemonic from the specified entropy bytes. Args: entropy_bytes (bytes): Entropy bytes (accepted lengths in bits: 128, 160, 192, 224, 256) Returns: str: Generated mnemonic from specified entropy Raises: ValueError: If entropy length is not valid """ # Check entropy length in bits entropy_bit_len = len(entropy_bytes) * 8 if entropy_bit_len not in Bip39Const.ENTROPY_BIT_LEN: raise ValueError("Entropy length in bits (%d) is not valid" % entropy_bit_len) # Compute entropy hash entropy_hash_bytes = CryptoUtils.Sha256(entropy_bytes) # Convert entropy to binary string entropy_bin = ConvUtils.BytesToBinaryStr(entropy_bytes, len(entropy_bytes) * 8) # Convert entropy hash to binary string entropy_hash_bin = ConvUtils.BytesToBinaryStr( entropy_hash_bytes, CryptoUtils.Sha256DigestSize() * 8) # Get checksum binary string checksum_bin = entropy_hash_bin[:len(entropy_bytes) // 4] # Create mnemonic entropy binary string by concatenating entropy and checksum, as specified in BIP39 mnemonic_entropy_bin = entropy_bin + checksum_bin # Create mnemonic reader mnemonic_reader = MnemonicFileReader() # Empty mnemonic mnemonic = [] # Get mnemonic from entropy for i in range(len(mnemonic_entropy_bin) // Bip39Const.WORD_BITS): # Get current word index word_idx = int( mnemonic_entropy_bin[i * Bip39Const.WORD_BITS:(i + 1) * Bip39Const.WORD_BITS], 2) # Get word at given index mnemonic.append(mnemonic_reader.GetWordAtIdx(word_idx)) # Join to string return " ".join(mnemonic)
def AddScriptSig(pub_key_bytes): """ Add script signature to public key and get address bytes. Args: pub_key_bytes (bytes) : Public key bytes Returns: bytes: Address bytes """ # Key hash: Hash160(public_key) key_hash = CryptoUtils.Hash160(pub_key_bytes) # Script signature: 0x0014 | Hash160(public_key) script_sig = binascii.unhexlify(P2SHConst.SCRIPT_BYTES) + key_hash # Address bytes = Hash160(script_signature) return CryptoUtils.Hash160(script_sig)
def KeyIdentifier(self): """ Get key identifier. Returns: bytes: Key identifier bytes """ return CryptoUtils.Hash160(self.PublicKey().RawCompressed().ToBytes())
def FromSeed(seed_bytes, key_net_ver=Bip32Conf.KEY_NET_VER.Main()): """ Create a Bip32 object from the specified seed (e.g. BIP39 seed). Args: seed_bytes (bytes) : Seed bytes key_net_ver (KeyNetVersions object, optional): Key net version object (Bip32 main net version by default) Returns: Bip32 object: Bip32 object Raises: ValueError: If the seed is too short Bip32KeyError: If the seed is not suitable for master key generation """ # Check seed length if len(seed_bytes) * 8 < Bip32Const.SEED_MIN_BIT_LEN: raise ValueError( "Seed length is too small, it shall be at least %d bit" % Bip32Const.SEED_MIN_BIT_LEN) # Compute HMAC hmac = CryptoUtils.HmacSha512(Bip32Const.MASTER_KEY_HMAC_KEY, seed_bytes) # Create BIP32 by splitting the HMAC into two 32-byte sequences return Bip32(secret=hmac[:32], chain=hmac[32:], key_net_ver=key_net_ver)
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 __ComputeChecksum(self, mnemonic_bin_str: str) -> str: """ Compute checksum from mnemonic binary string. Args: mnemonic_bin_str (str): Mnemonic binary string Returns: str: Computed checksum binary string """ # Get entropy bytes entropy_bytes = self.__GetEntropyBytes(mnemonic_bin_str) # Convert entropy hash to binary string entropy_hash_bin = ConvUtils.BytesToBinaryStr(CryptoUtils.Sha256(entropy_bytes), CryptoUtils.Sha256DigestSize() * 8) # Compute checksum checksum_bin = entropy_hash_bin[:self.__GetChecksumLen(mnemonic_bin_str)] return checksum_bin
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 __HmacHalves(self, data_bytes): """ Calculate the HMAC-SHA512 of input data using the chain code as key and returns a tuple of the left and right halves of the HMAC. Args: data_bytes (bytes): Data bytes Returns: tuple: Left and right halves of the HMAC """ # Use chain as HMAC key hmac = CryptoUtils.HmacSha512(self.m_chain, data_bytes) return (hmac[:32], hmac[32:])
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 Generate(self, passphrase = ""): """ Generate the seed using the specified passphrase. Args: passphrase (str, optional): Passphrase, empty if not specified Returns: bytes: Generated seed """ # Get salt salt = Bip39Const.SEED_SALT_MOD + passphrase # Compute key key = CryptoUtils.Pbkdf2HmacSha512(AlgoUtils.StringEncode(self.m_mnemonic), AlgoUtils.StringEncode(salt), Bip39Const.SEED_PBKDF2_ROUNDS) return key[:Bip39Const.SEED_LEN]
def ToAddress(pub_key_bytes: bytes) -> str: """ Get address in Atom format. Args: pub_key_bytes (bytes) : Public key bytes Returns: str: Address string Raises: ValueError: If key is not a public compressed key """ if not KeyUtils.IsPublicCompressed(pub_key_bytes): raise ValueError( "Public compressed key is required for Avax address") return AvaxBech32Encoder.Encode(CryptoUtils.Hash160(pub_key_bytes), AvaxChainTypes.AVAX_P_CHAIN)
def ToAddress(pub_key_bytes: bytes, net_addr_ver: str = BitcoinConf.P2WPKH_NET_VER.Main()) -> str: """ Get address in P2WPKH format. Args: pub_key_bytes (bytes) : Public key bytes net_addr_ver (str, optional): Net address version, default is Bitcoin main network Returns: str: Address string Raises: ValueError: If key is not a public compressed key """ if not KeyUtils.IsPublicCompressed(pub_key_bytes): raise ValueError("Public compressed key is required for P2WPKH") return SegwitBech32Encoder.Encode(net_addr_ver, P2WPKHConst.WITNESS_VER, CryptoUtils.Hash160(pub_key_bytes))
def ToAddress(pub_key_bytes: bytes, hrp: str) -> str: """ Get address in Atom format. Args: pub_key_bytes (bytes): Public key bytes hrp (str) : HRP Returns: str: Address string Raises: ValueError: If key is not a public compressed key """ if not KeyUtils.IsPublicCompressed(pub_key_bytes): raise ValueError( "Public compressed key is required for Atom address") return AtomBech32Encoder.Encode(hrp, CryptoUtils.Hash160(pub_key_bytes))
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 ToAddress(pub_key_bytes: bytes, hrp: str, net_addr_ver: bytes) -> str: """ Get address in Bitcoin Cash P2PKH format. Args: pub_key_bytes (bytes): Public key bytes hrp (str) : HRP net_addr_ver (bytes) : Net address version Returns: str: Address string Raises: ValueError: If key is not a public compressed key """ if not KeyUtils.IsPublicCompressed(pub_key_bytes): raise ValueError( "Public compressed key is required for Bitcoin Cash") return BchBech32Encoder.Encode(hrp, net_addr_ver, CryptoUtils.Hash160(pub_key_bytes))
def ToAddress(pub_key_bytes, net_addr_ver=BitcoinConf.P2PKH_NET_VER.Main(), base58_alph=Base58Alphabets.BITCOIN): """ Get address in P2PKH format. Args: pub_key_bytes (bytes) : Public key bytes net_addr_ver (bytes, optional) : Net address version, default is Bitcoin main network base58_alph (Base58Alphabets, optional): Base58 alphabet, Bitcoin by default Returns: str: Address string Raises: ValueError: If the key is not a public compressed key """ if not KeyUtils.IsPublicCompressed(pub_key_bytes): raise ValueError("Public compressed key is required for P2PKH") return Base58Encoder.CheckEncode( net_addr_ver + CryptoUtils.Hash160(pub_key_bytes), base58_alph)