Solved encode-decode, pack-unpack, new address creation issues

This commit is contained in:
jai.s 2019-10-22 13:07:54 +05:30
parent b18ed5e80f
commit f4d14c11e9
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
6 changed files with 21 additions and 34 deletions

View File

@ -157,13 +157,13 @@ class addressGenerator(StoppableThread):
# An excellent way for us to store our keys # An excellent way for us to store our keys
# is in Wallet Import Format. Let us convert now. # is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80'.encode('utf-8') + potentialPrivSigningKey privSigningKey = '\x80'.encode('utf-8')[1:] + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4] privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase( privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58) privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80'.encode('utf-8') + potentialPrivEncryptionKey privEncryptionKey = '\x80'.encode('utf-8')[1:] + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4] privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKeyWIF = arithmetic.changebase(

View File

@ -15,8 +15,8 @@ def makeCryptor(privkey):
"""Return a private pyelliptic.ECC() instance""" """Return a private pyelliptic.ECC() instance"""
private_key = a.changebase(privkey, 16, 256, minlen=32) private_key = a.changebase(privkey, 16, 256, minlen=32)
public_key = pointMult(private_key) public_key = pointMult(private_key)
privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key privkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + private_key
pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] pubkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:]
cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin)
return cryptor return cryptor

View File

@ -1,4 +1,4 @@
# pylint: disable=missing-docstring,too-many-function-args 0# pylint: disable=missing-docstring,too-many-function-args
import hashlib import hashlib
import re import re
@ -26,33 +26,27 @@ def get_code_string(base):
elif base == 10: elif base == 10:
return '0123456789' return '0123456789'
elif base == 16: elif base == 16:
return "0123456789abcdef" return ("0123456789abcdef").encode()
elif base == 58: elif base == 58:
return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
elif base == 256: elif base == 256:
'''raw_unicode_escape is used because in the python3 after range(161) its genreate the' '''raw_unicode_escape is used because in the python3 after range(161) its genreate the'
the speical character so avoiding that function we have used the raw_unicode method ''' the speical character so avoiding that function we have used the raw_unicode method '''
return ''.join([chr(x) for x in range(256)]).encode('raw_unicode_escape') return bytes(range(0, 256))
else: else:
raise ValueError("Invalid base!") raise ValueError("Invalid base!")
def encode(val, base, minlen=0): def encode(val, base, minlen=0):
code_string = get_code_string(base) code_string = get_code_string(base)
result = '' result = str.encode('') if type(code_string) == bytes else ''
# result = str.encode(result)
count = 0
while val > 0: while val > 0:
count += 1 result = code_string[val % base:val % base + 1] + result
print(f'code_string[int(val) % base:int(val) % base + 1] -{code_string[int(val) % base:int(val) % base + 1]}') val = val // base
print(f'result-{result}')
result = code_string[int(val) % base:int(val) % base + 1] + result
val = int(val / base)
if len(result) < minlen: if len(result) < minlen:
result = code_string[0] * (minlen - len(result)) + result result = code_string[0] * (minlen - len(result)) + result
return result return result
def decode(string, base): def decode(string, base):
code_string = get_code_string(base) code_string = get_code_string(base)
result = 0 result = 0
@ -60,7 +54,7 @@ def decode(string, base):
string = string.lower() string = string.lower()
while string: while string:
result *= base result *= base
result += code_string.find(string[0]) result += code_string.find(string[0:1])
string = string[1:] string = string[1:]
return result return result

View File

@ -64,7 +64,6 @@ class ECC(object):
self.curve = OpenSSL.get_curve(curve) self.curve = OpenSSL.get_curve(curve)
else: else:
self.curve = curve self.curve = curve
if pubkey_x is not None and pubkey_y is not None: if pubkey_x is not None and pubkey_y is not None:
self._set_keys(pubkey_x, pubkey_y, raw_privkey) self._set_keys(pubkey_x, pubkey_y, raw_privkey)
elif pubkey is not None: elif pubkey is not None:
@ -114,7 +113,7 @@ class ECC(object):
pack('!H', len(self.pubkey_x)), pack('!H', len(self.pubkey_x)),
self.pubkey_x, self.pubkey_x,
pack('!H', len(self.pubkey_y)), pack('!H', len(self.pubkey_y)),
self.pubkey_y, self.pubkey_y,
)) ))
def get_privkey(self): def get_privkey(self):
@ -137,19 +136,18 @@ class ECC(object):
i += 2 i += 2
pubkey_x = pubkey[i:i + tmplen] pubkey_x = pubkey[i:i + tmplen]
i += tmplen i += tmplen
i += int(tmplen / 3)
tmplen = unpack('!H', pubkey[i:i + 2])[0] tmplen = unpack('!H', pubkey[i:i + 2])[0]
i += 2 i += 2
pubkey_y = pubkey[i:i + tmplen] pubkey_y = pubkey[i:i + tmplen]
i += tmplen i += tmplen
return curve, pubkey_x, pubkey_y, int(i) return curve, pubkey_x, pubkey_y, i
@staticmethod @staticmethod
def _decode_privkey(privkey): def _decode_privkey(privkey):
i = 0 i = 0
curve = unpack('!H', privkey[i:i + 2])[0] curve = unpack('!H', privkey[i:i + 2])[0]
i += 2 i += 2
tmplen = pack('!s', privkey[i:i + 1])[0] tmplen = unpack('!H', privkey[i:i + 2])[0]
i += 2 i += 2
privkey = privkey[i:i + tmplen] privkey = privkey[i:i + tmplen]
i += tmplen i += tmplen
@ -297,7 +295,6 @@ class ECC(object):
if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0:
raise Exception( raise Exception(
"[OpenSSL] EC_KEY_set_private_key FAIL ...") "[OpenSSL] EC_KEY_set_private_key FAIL ...")
group = OpenSSL.EC_KEY_get0_group(key) group = OpenSSL.EC_KEY_get0_group(key)
pub_key = OpenSSL.EC_POINT_new(group) pub_key = OpenSSL.EC_POINT_new(group)

View File

@ -674,13 +674,12 @@ def loadOpenSSL():
elif 'win32' in sys.platform or 'win64' in sys.platform: elif 'win32' in sys.platform or 'win64' in sys.platform:
libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) libdir.append(path.join(sys._MEIPASS, 'libeay32.dll'))
else: else:
libdir.extend([ libdir.extend([
path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libcrypto.so'),
path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libssl.so'),
path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'), path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'),
path.join(sys._MEIPASS, 'libssl.so.1.1.0'), path.join(sys._MEIPASS, 'libssl.so.1.1.0'),
path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'),
path.join(sys._MEIPASS, 'libssl.so.1.0.2'), path.join(sys._MEIPASS, 'libssl.so.1.0.2'),
path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'),
path.join(sys._MEIPASS, 'libssl.so.1.0.1'), path.join(sys._MEIPASS, 'libssl.so.1.0.1'),
@ -703,6 +702,7 @@ def loadOpenSSL():
libdir.append('libssl.so') libdir.append('libssl.so')
libdir.append('libcrypto.so.1.0.0') libdir.append('libcrypto.so.1.0.0')
libdir.append('libssl.so.1.0.0') libdir.append('libssl.so.1.0.0')
libdir.append('libcrypto.so.1.0.2')
if 'linux' in sys.platform or 'darwin' in sys.platform or 'bsd' in sys.platform: if 'linux' in sys.platform or 'darwin' in sys.platform or 'bsd' in sys.platform:
try: try:
libdir.append(find_library('ssl')) libdir.append(find_library('ssl'))
@ -710,7 +710,7 @@ def loadOpenSSL():
pass pass
elif 'win32' in sys.platform or 'win64' in sys.platform: elif 'win32' in sys.platform or 'win64' in sys.platform:
libdir.append(find_library('libeay32')) libdir.append(find_library('libeay32'))
for library in libdir: for library in libdir:
try: try:
OpenSSL = _OpenSSL(library) OpenSSL = _OpenSSL(library)
return return

View File

@ -89,27 +89,23 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
return True return True
return False return False
def decodeWalletImportFormat(WIFstring): def decodeWalletImportFormat(WIFstring):
fullString = arithmetic.changebase(WIFstring, 58, 256) fullString = arithmetic.changebase(WIFstring, 58, 256)
privkey = fullString[:-4] privkey = fullString[:-4]
if fullString[-4:] != \ if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
logger.critical( logger.critical(
'Major problem! When trying to decode one of your' 'Major problem! When trying to decode one of your'
' private keys, the checksum failed. Here are the first' ' private keys, the checksum failed. Here are the first'
' 6 characters of the PRIVATE key: %s', ' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6])
str(WIFstring)[:6]
) )
os._exit(0) os._exit(0)
# return "" if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed
elif privkey[0] == '\x80': # checksum passed
return privkey[1:] return privkey[1:]
logger.critical( logger.critical(
'Major problem! When trying to decode one of your private keys,' 'Major problem! When trying to decode one of your private keys,'
' the checksum passed but the key doesn\'t begin with hex 80.' ' the checksum passed but the key doesn\'t begin with hex 80.'
' Here is the PRIVATE key: %s', WIFstring ' Here is the PRIVATE key: {}'.format(WIFstring)
) )
os._exit(0) os._exit(0)