Python base58.b58decode_check() Examples
The following are 23
code examples of base58.b58decode_check().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
base58
, or try the search function
.
Example #1
Source File: bip38.py From moneywagon with MIT License | 6 votes |
def __init__(self, b58check): self.lot = None self.sequence = None self.b58check = b58check if not b58check.startswith('passphrase'): raise Exception("Invalid intermediate point. Must start wth 'passphrase'.") payload = b58decode_check(str(b58check)) self.ownerentropy = payload[8:16] # 8 bytes self.passpoint = payload[16:49] # 33 bytes flag = payload[7:8] if flag == b'\x51': self.has_lot_and_sequence = True self.ownersalt = self.ownerentropy[:4] # 4 bytes lotsequence = bytes_to_int(self.ownerentropy[4:]) # 4 bytes self.lot = lotsequence // self.lotseq_constant self.sequence = lotsequence % self.lot elif flag == b'\x53': self.has_lot_and_sequence = False self.ownersalt = self.ownerentropy # 8 bytes else: raise Exception("Unknown flag byte: %s, should be either \\x51 or \\x53" % flag)
Example #2
Source File: __init__.py From moneywagon with MIT License | 6 votes |
def change_version_byte(address, new_version=None, new_crypto=None): """ Convert the passed in address (or any base58 encoded string), and change the version byte to `new_version`. """ if not new_version and new_crypto: try: new_version = crypto_data[new_crypto]['address_version_byte'] except KeyError: raise CurrencyNotSupported("Unknown currency symbol: " + new_crypto) if not new_version: raise CurrencyNotSupported("Can't yet make %s addresses." % new_crypto) payload = b58decode_check(address)[1:] if is_py2: byte = chr(new_version) else: byte = bytes(chr(new_version), 'ascii') return b58encode_check(byte + payload)
Example #3
Source File: __init__.py From moneywagon with MIT License | 6 votes |
def guess_currency_from_address(address): """ Given a crypto address, find which currency it likely belongs to. Raises an exception if it can't find a match. Raises exception if address is invalid. """ if is_py2: fixer = lambda x: int(x.encode('hex'), 16) else: fixer = lambda x: x # does nothing first_byte = fixer(b58decode_check(address)[0]) double_first_byte = fixer(b58decode_check(address)[:2]) hits = [] for currency, data in crypto_data.items(): if hasattr(data, 'get'): # skip incomplete data listings version = data.get('address_version_byte', None) if version is not None and version in [double_first_byte, first_byte]: hits.append([currency, data['name']]) if hits: return hits raise ValueError("Unknown Currency with first byte: %s" % first_byte)
Example #4
Source File: hd_private_key.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 5 votes |
def b58decode(cls, key): """ Decodes a Base58Check encoding private-key. """ return cls.from_bytes(base58.b58decode_check(key))
Example #5
Source File: Utils.py From neo-python-core with MIT License | 5 votes |
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch valid = False return valid
Example #6
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def __init__(self, b58check): if not b58check.startswith('cfrm38'): raise Exception("Invalid Confirm code, must start with 'cfrm38'") self.b58check = b58check payload = b58decode_check(b58check) flagbyte = payload[5:6] if flagbyte == b'\x20': self.compressed = True self.sequence_and_lot = False elif flagbyte == b'\x00': self.compressed = False self.sequence_and_lot = False elif flagbyte == b'\x04': self.compressed = False self.sequence_and_lot = True elif flagbyte == b'\x24': self.compressed = True self.sequence_and_lot = True else: raise Exception("Unknown flagbyte: %s" % flagbyte) self.addresshash = payload[6:10] # 4 bytes self.ownerentropy = payload[10:18] # 8 bytes encryptedpointb = payload[18:] # 33 bytes self.pointbprefix = encryptedpointb[0:1] # 1 byte self.pointbx1 = encryptedpointb[1:17] # 16 bytes self.pointbx2 = encryptedpointb[17:] # 16 bytes if self.sequence_and_lot: self.ownersalt = self.ownerentropy[:4] lotsequence = bytes_to_int(self.ownerentropy[4:]) # 4 bytes self.lot = lotsequence // Bip38IntermediatePoint.lotseq_constant self.sequence = lotsequence % self.lot else: self.sequence, self.lot = None, None self.ownersalt = self.ownerentropy
Example #7
Source File: bip38.py From moneywagon with MIT License | 5 votes |
def __init__(self, crypto, b58check): if not b58check.startswith('6P'): raise Exception("Invalid encrypted private key. Must start wth 6P.") self.b58check = b58check self.payload = b58decode_check(b58check) second_byte = self.payload[1:2] self.flagbyte = self.payload[2:3] if second_byte == b'\x42': self.ec_multiply = False if self.flagbyte == b'\xC0': self.compressed = False elif self.flagbyte == b'\xE0': self.compressed = True else: raise Exception("Unknown flagbyte: %x" % flagbyte) self.addresshash = self.payload[3:7] # 4 bytes self.encryptedhalf1 = self.payload[7:23] # 16 bytes self.encryptedhalf2 = self.payload[23:39] # 16 bytes elif second_byte == b'\x43': self.ec_multiply = True if self.flagbyte == b'\x00': self.compressed = False elif self.flagbyte == b'\x20': self.compressed = True else: raise Exception("Unknown flagbyte: %x" % flagbyte) self.addresshash = self.payload[3:7] # 4 bytes self.ownerentropy = self.payload[7:15] # 8 bytes self.encryptedpart1 = self.payload[15:23] # 8 bytes self.encryptedpart2 = self.payload[23:] # 16 bytes else: raise Exception("Unknown second base58check byte: %x" % second_byte) self.pub_byte, self.priv_byte = get_magic_bytes(crypto)
Example #8
Source File: __init__.py From moneywagon with MIT License | 5 votes |
def wif_to_address(crypto, wif): if is_py2: wif_byte = int(hexlify(b58decode_check(wif)[0]), 16) else: wif_byte = b58decode_check(wif)[0] if not wif_byte == crypto_data[crypto.lower()]['private_key_prefix']: msg = 'WIF encoded with wrong prefix byte. Are you sure this is a %s address?' % crypto.upper() raise Exception(msg) address_byte = crypto_data[crypto.lower()]['address_version_byte'] return privkey_to_address(wif, address_byte)
Example #9
Source File: __init__.py From moneywagon with MIT License | 5 votes |
def wif_to_hex(wif): """ Convert a WIF encded private key and return the raw hex encoded private key This function works for all bitcoin-API compatable coins. """ return hexlify(b58decode_check(wif)[1:]).upper()
Example #10
Source File: Utils.py From neo-python with MIT License | 5 votes |
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch valid = False return valid
Example #11
Source File: JsonRpcApi.py From neo-python with MIT License | 5 votes |
def validateaddress(self, params): # check for [] parameter or [""] if not params or params[0] == '': raise JsonRpcError(-100, "Missing argument") isValid = False try: data = base58.b58decode_check(params[0]) if len(data) == 21 and data[0] == settings.ADDRESS_VERSION: isValid = True except Exception as e: pass return {"address": params[0], "isvalid": isValid}
Example #12
Source File: encoding.py From pytezos with MIT License | 5 votes |
def base58_decode(v: bytes) -> bytes: try: prefix_len = next( len(encoding[2]) for encoding in base58_encodings if len(v) == encoding[1] and v.startswith(encoding[0]) ) except StopIteration: raise ValueError('Invalid encoding, prefix or length mismatch.') return base58.b58decode_check(v)[prefix_len:]
Example #13
Source File: ethereum.py From pywallet with MIT License | 5 votes |
def from_b58check(key): """ Decodes a Base58Check encoded key. The encoding must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format Args: key (str): A Base58Check encoded key. Returns: HDPrivateKey or HDPublicKey: Either an HD private or public key object, depending on what was serialized. """ return HDKey.from_bytes(base58.b58decode_check(key))
Example #14
Source File: ethereum.py From pywallet with MIT License | 5 votes |
def from_b58check(private_key): """ Decodes a Base58Check encoded private-key. Args: private_key (str): A Base58Check encoded private key. Returns: PrivateKey: A PrivateKey object """ b58dec = base58.b58decode_check(private_key) version = b58dec[0] assert version in [PrivateKey.TESTNET_VERSION, PrivateKey.MAINNET_VERSION] return PrivateKey(int.from_bytes(b58dec[1:], 'big'))
Example #15
Source File: account.py From tron-api-python with MIT License | 5 votes |
def to_hex(address): """Helper function that will convert a generic value to hex""" if is_hex(address): return address.lower().replace('0x', '41', 2) return base58.b58decode_check(address).hex().upper()
Example #16
Source File: utils.py From blockchain-py with Apache License 2.0 | 5 votes |
def address_to_pubkey_hash(address): # return base58.b58decode_check(encode(address))[1:] return base58.base58CheckDecode(address)
Example #17
Source File: hd_public_key.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 5 votes |
def b58decode(cls, key: Union[str, bytes]): """ Decodes a Base58Check encoded key. The encoding must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format """ return cls.from_bytes(base58.b58decode_check(key))
Example #18
Source File: coinbase_txn.py From bitcoin_in_a_nutshell with MIT License | 4 votes |
def coinbaseMessage(previous_output, receiver_address, my_address, private_key): receiver_hashed_pubkey= base58.b58decode_check(receiver_address)[1:].encode("hex") my_hashed_pubkey = base58.b58decode_check(my_address)[1:].encode("hex") # Transaction stuff version = struct.pack("<L", 1) lock_time = struct.pack("<L", 0) hash_code = struct.pack("<L", 1) # Transactions input tx_in_count = struct.pack("<B", 1) tx_in = {} tx_in["outpoint_hash"] = previous_output.decode('hex')[::-1] tx_in["outpoint_index"] = struct.pack("<L", 4294967295) tx_in["script"] = ("76a914%s88ac" % my_hashed_pubkey).decode("hex") tx_in["script_bytes"] = struct.pack("<B", (len(tx_in["script"]))) tx_in["sequence"] = "ffffffff".decode("hex") # Transaction output tx_out_count = struct.pack("<B", 1) tx_out = {} tx_out["value"]= struct.pack("<Q", 100000000 * 12.50033629) tx_out["pk_script"]= ("76a914%s88ac" % receiver_hashed_pubkey).decode("hex") tx_out["pk_script_bytes"]= struct.pack("<B", (len(tx_out["pk_script"]))) tx_to_sign = (version + tx_in_count + tx_in["outpoint_hash"] + tx_in["outpoint_index"] + tx_in["script_bytes"] + tx_in["script"] + tx_in["sequence"] + tx_out_count + tx_out["value"] + tx_out["pk_script_bytes"] + tx_out["pk_script"] + lock_time + hash_code) # Signing txn hashed_raw_tx = hashlib.sha256(hashlib.sha256(tx_to_sign).digest()).digest() sk = ecdsa.SigningKey.from_string(private_key.decode("hex"), curve = ecdsa.SECP256k1) vk = sk.verifying_key public_key = ('\04' + vk.to_string()).encode("hex") sign = sk.sign_digest(hashed_raw_tx, sigencode=ecdsa.util.sigencode_der) # Complete txn sigscript = sign + "\01" + struct.pack("<B", len(public_key.decode("hex"))) + public_key.decode("hex") real_tx = (version + tx_in_count + tx_in["outpoint_hash"] + tx_in["outpoint_index"] + struct.pack("<B", (len(sigscript) + 1)) + struct.pack("<B", len(sign) + 1) + sigscript + tx_in["sequence"] + tx_out_count + tx_out["value"] + tx_out["pk_script_bytes"] + tx_out["pk_script"] + lock_time) return real_tx
Example #19
Source File: KeyPair.py From neo-python with MIT License | 4 votes |
def PrivateKeyFromNEP2(nep2_key, passphrase): """ Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: bytes: The private key Raises: ValueError: if the input `nep2_key` length != 58 if the input `nep2_key` is invalid if the input `passphrase` is wrong """ if not nep2_key or len(nep2_key) != 58: raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key))) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER) try: decoded_key = base58.b58decode_check(nep2_key) except Exception: raise ValueError("Invalid nep2_key") address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE] encrypted = decoded_key[-32:] pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) derived1 = derived[:32] derived2 = derived[32:] cipher = AES.new(derived2, AES.MODE_ECB) decrypted = cipher.decrypt(encrypted) private_key = xor_bytes(decrypted, derived1) # Now check that the address hashes match. If they don't, the password was wrong. kp_new = KeyPair(priv_key=private_key) kp_new_address = kp_new.GetAddress() kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest() kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest() kp_new_address_hash = kp_new_address_hash_tmp2[:4] if (kp_new_address_hash != address_hash): raise ValueError("Wrong passphrase") return private_key
Example #20
Source File: keys.py From pywallet with MIT License | 4 votes |
def from_wif(cls, wif, network=BitcoinMainNet): """Import a key in WIF format. WIF is Wallet Import Format. It is a base58 encoded checksummed key. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. This supports compressed WIFs - see this for an explanation: http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8 (specifically http://bitcoin.stackexchange.com/a/7958) """ # Decode the base58 string and ensure the checksum is valid wif = ensure_str(wif) try: extended_key_bytes = base58.b58decode_check(wif) except ValueError as e: # Invalid checksum! raise ChecksumException(e) # Verify we're on the right network network_bytes = extended_key_bytes[0] # py3k interprets network_byte as an int already if not isinstance(network_bytes, six.integer_types): network_bytes = ord(network_bytes) if (network_bytes != network.SECRET_KEY): raise incompatible_network_exception_factory( network_name=network.NAME, expected_prefix=network.SECRET_KEY, given_prefix=network_bytes) # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] # Check for comprssed public key # This only affects the way in which addresses are generated. compressed = False if len(extended_key_bytes) == 33: # We are supposed to use compressed form! extended_key_bytes = extended_key_bytes[:-1] compressed = True # And we should finally have a valid key return cls(long_or_int(hexlify(extended_key_bytes), 16), network, compressed=compressed)
Example #21
Source File: keys.py From bitmerchant with MIT License | 4 votes |
def from_wif(cls, wif, network=BitcoinMainNet): """Import a key in WIF format. WIF is Wallet Import Format. It is a base58 encoded checksummed key. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. This supports compressed WIFs - see this for an explanation: http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8 (specifically http://bitcoin.stackexchange.com/a/7958) """ # Decode the base58 string and ensure the checksum is valid wif = ensure_str(wif) try: extended_key_bytes = base58.b58decode_check(wif) except ValueError as e: # Invalid checksum! raise ChecksumException(e) # Verify we're on the right network network_bytes = extended_key_bytes[0] # py3k interprets network_byte as an int already if not isinstance(network_bytes, six.integer_types): network_bytes = ord(network_bytes) if (network_bytes != network.SECRET_KEY): raise incompatible_network_exception_factory( network_name=network.NAME, expected_prefix=network.SECRET_KEY, given_prefix=network_bytes) # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] # Check for comprssed public key # This only affects the way in which addresses are generated. compressed = False if len(extended_key_bytes) == 33: # We are supposed to use compressed form! extended_key_bytes = extended_key_bytes[:-1] compressed = True # And we should finally have a valid key return cls(long_or_int(hexlify(extended_key_bytes), 16), network, compressed=compressed)
Example #22
Source File: keys.py From multimerchant-python with MIT License | 4 votes |
def from_wif(cls, wif, network=BitcoinMainNet): """Import a key in WIF format. WIF is Wallet Import Format. It is a base58 encoded checksummed key. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. This supports compressed WIFs - see this for an explanation: http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8 (specifically http://bitcoin.stackexchange.com/a/7958) """ # Decode the base58 string and ensure the checksum is valid wif = ensure_str(wif) try: extended_key_bytes = base58.b58decode_check(wif) except ValueError as e: # Invalid checksum! raise ChecksumException(e) # Verify we're on the right network network_bytes = extended_key_bytes[0] # py3k interprets network_byte as an int already if not isinstance(network_bytes, six.integer_types): network_bytes = ord(network_bytes) if (network_bytes != network.SECRET_KEY): raise incompatible_network_exception_factory( network_name=network.NAME, expected_prefix=network.SECRET_KEY, given_prefix=network_bytes) # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] # Check for comprssed public key # This only affects the way in which addresses are generated. compressed = False if len(extended_key_bytes) == 33: # We are supposed to use compressed form! extended_key_bytes = extended_key_bytes[:-1] compressed = True # And we should finally have a valid key return cls(long_or_int(hexlify(extended_key_bytes), 16), network, compressed=compressed)
Example #23
Source File: KeyPair.py From neo-python-core with MIT License | 4 votes |
def PrivateKeyFromNEP2(nep2_key, passphrase): """ Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: bytes: The private key """ if not nep2_key or len(nep2_key) != 58: raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key))) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER) try: decoded_key = base58.b58decode_check(nep2_key) except Exception as e: raise ValueError("Invalid nep2_key") address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE] encrypted = decoded_key[-32:] pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8') derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES) derived1 = derived[:32] derived2 = derived[32:] cipher = AES.new(derived2, AES.MODE_ECB) decrypted = cipher.decrypt(encrypted) private_key = xor_bytes(decrypted, derived1) # Now check that the address hashes match. If they don't, the password was wrong. kp_new = KeyPair(priv_key=private_key) kp_new_address = kp_new.GetAddress() kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest() kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest() kp_new_address_hash = kp_new_address_hash_tmp2[:4] if (kp_new_address_hash != address_hash): raise ValueError("Wrong passphrase") return private_key