def test_encodeDecode(self): # get 32 random bytes text = self.randomBytesString(32) print("\nRandom Bytes: %s" % text.hex()) # encode base58 encoded_text = b58encode(text) print("\nEncoded Text: %s\n" % encoded_text) # verify self.assertEqual(b58decode(encoded_text), text)
def test_decodeEncode(self): # get 10 random base58 chars text = self.randomB58String(10) print("\nRandom Text: %s" % text) # decode base58 decoded_text = b58decode(text) print("\nDecoded Text: %s\n" % decoded_text) # verify self.assertEqual(b58encode(decoded_text), text)
def test_generate_privkey(self): # generate random private key randomKey = generate_privkey() # check length self.assertEqual(len(randomKey), 51) # check leading char '8' self.assertEqual(randomKey[0], '8') # decode and verify checksum randomKey_bin = bytes.fromhex(b58decode(randomKey).hex()) randomKey_bin_check = bitcoin.bin_dbl_sha256(randomKey_bin[0:-4])[0:4] self.assertEqual(randomKey_bin[-4:], randomKey_bin_check)
def test_pubkey_to_address(self): # generate random private key and convert to public randomPubKey = bitcoin.privkey_to_pubkey(generate_privkey()) # compute address randomQmcAddr = pubkey_to_address(randomPubKey) # check leading char 'D' self.assertEqual(randomQmcAddr[0], 'D') # decode and verify checksum randomQmcAddr_bin = bytes.fromhex(b58decode(randomQmcAddr).hex()) randomQmcAddr_bin_check = bitcoin.bin_dbl_sha256( randomQmcAddr_bin[0:-4])[0:4] self.assertEqual(randomQmcAddr_bin[-4:], randomQmcAddr_bin_check)
def checkQmcAddr(address): try: # check leading char 'D' if address[0] != 'D': return False # decode and verify checksum addr_bin = bytes.fromhex(b58decode(address).hex()) addr_bin_check = bin_dbl_sha256(addr_bin[0:-4])[0:4] if addr_bin[-4:] != addr_bin_check: return False return True except Exception: return False
def wif_to_privkey(string): wif_compressed = 52 == len(string) pvkeyencoded = b58decode(string).hex() wifversion = pvkeyencoded[:2] checksum = pvkeyencoded[-8:] vs = bytes.fromhex(pvkeyencoded[:-8]) check = double_sha256(vs)[0:4] if (wifversion == WIF_PREFIX.to_bytes(1, byteorder='big').hex() and checksum == check.hex()) \ or (wifversion == TESTNET_WIF_PREFIX.to_bytes(1, byteorder='big').hex() and checksum == check.hex()): if wif_compressed: privkey = pvkeyencoded[2:-10] else: privkey = pvkeyencoded[2:-8] return privkey else: return None