timp bill
timp bill

Reputation: 67

Not converting correctly in base58 check format

I tried to encode a integer to base58 encode using algorithm present at Wiki but it converted to a string but when i decoded it gave error of invalid check sum The integer i tried it 111383925596674021496745350149385052040158942814438962455769092527167857754112

Encoding way of converting a integer

import hashlib
import base58

code_string = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def convert_bytes_to_base58check(hash_result, num_leading_zero_bytes):
    x = int.from_bytes(hash_result, byteorder="big")
    output_string = ""
    while x > 0:
        x, remainder = divmod(x, 58)
        output_string += code_string[remainder]
    output_string += code_string[0] * num_leading_zero_bytes
    return output_string[::-1]

my_integer = 111383925596674021496745350149385052040158942814438962455769092527167857754112
my_hex_string = hex(my_integer)[2:]
if len(my_hex_string) % 2 != 0:
    my_hex_string = "0" + my_hex_string
my_bytes = bytes.fromhex(my_hex_string)
my_hash = hashlib.sha256(hashlib.sha256(my_bytes).digest()).digest()
output_string = convert_bytes_to_base58check(my_hash, 0)
print(output_string)

And i tried to decode it like

import base58
code_string = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def convert_bytes_to_big_integer(data):
    return int.from_bytes(data, byteorder='big')

def encode_base58check(hash_result, num_leading_zero_bytes):
    x = convert_bytes_to_big_integer(hash_result)
    output_string = ""
    
    while x > 0:
        x, remainder = divmod(x, 58)
        output_string += code_string[remainder]
    
    output_string += code_string[0] * num_leading_zero_bytes
    return output_string[::-1]

my_string = 'GTbisRUFDyw71dQcDXfMbYK6hMQ1EcnTvTmvGa5LodBp'
my_bytes = base58.b58decode_check(my_string)
my_hash = my_bytes[:-4]
num_leading_zero_bytes = my_bytes[-1]
output_string = encode_base58check(my_hash, num_leading_zero_bytes)
print(output_string)

I also tried my own way but same it converted to a string but gave error of invalid check sum the code was

from bitcoin import *
import base58
def getPrivateKey(my_integer):
    print(type(my_integer))
    print("number = ",my_integer)
    public_key = privtopub(my_integer)
    uncompressed_address = pubtoaddr(public_key)
    compressed_public_key = compress(public_key)
    compressed_address = pubtoaddr(compressed_public_key)

    my_hex_string = hex(my_integer)[2:]
    print("hex_string = ",my_hex_string)

    if len(my_hex_string) % 2 != 0:
        my_hex_string = "0" + my_hex_string
    my_bytes = bytes.fromhex(my_hex_string)
    my_bytes_with_prefix = b"\x80" + my_bytes
    my_bytes_with_prefix_and_checksum = my_bytes_with_prefix + b"\x01" + bin_sha256(bin_sha256(my_bytes_with_prefix))[:4]
    my_private_key = base58.b58encode(my_bytes_with_prefix_and_checksum)
    print(my_private_key)

Upvotes: 0

Views: 235

Answers (0)

Related Questions