Skip to content

Commit c49c131

Browse files
committed
Moved decodeWalletImportFormat() from shared to highlevelcrypto,
not addresses, where it's supposed to be because it uses pyelliptic.arithmetic, addresses.decodeBase58() returns int which needs to be encoded. Defined encodeWalletImportFormat() and replaced all uses.
1 parent f7cabe9 commit c49c131

File tree

4 files changed

+97
-100
lines changed

4 files changed

+97
-100
lines changed

src/class_addressGenerator.py

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from bmconfigparser import BMConfigParser
1616
from fallback import RIPEMD160Hash
1717
from network import StoppableThread
18-
from pyelliptic import arithmetic
1918
from pyelliptic.openssl import OpenSSL
2019

2120

@@ -164,20 +163,10 @@ def run(self):
164163
address = encodeAddress(
165164
addressVersionNumber, streamNumber, ripe)
166165

167-
# An excellent way for us to store our keys
168-
# is in Wallet Import Format. Let us convert now.
169-
# https://en.bitcoin.it/wiki/Wallet_import_format
170-
privSigningKey = '\x80' + potentialPrivSigningKey
171-
checksum = hashlib.sha256(hashlib.sha256(
172-
privSigningKey).digest()).digest()[0:4]
173-
privSigningKeyWIF = arithmetic.changebase(
174-
privSigningKey + checksum, 256, 58)
175-
176-
privEncryptionKey = '\x80' + potentialPrivEncryptionKey
177-
checksum = hashlib.sha256(hashlib.sha256(
178-
privEncryptionKey).digest()).digest()[0:4]
179-
privEncryptionKeyWIF = arithmetic.changebase(
180-
privEncryptionKey + checksum, 256, 58)
166+
privSigningKeyWIF = highlevelcrypto.encodeWalletImportFormat(
167+
potentialPrivSigningKey)
168+
privEncryptionKeyWIF = highlevelcrypto.encodeWalletImportFormat(
169+
potentialPrivEncryptionKey)
181170

182171
BMConfigParser().add_section(address)
183172
BMConfigParser().set(address, 'label', label)
@@ -301,21 +290,12 @@ def run(self):
301290
saveAddressToDisk = False
302291

303292
if saveAddressToDisk and live:
304-
# An excellent way for us to store our keys is
305-
# in Wallet Import Format. Let us convert now.
306-
# https://en.bitcoin.it/wiki/Wallet_import_format
307-
privSigningKey = '\x80' + potentialPrivSigningKey
308-
checksum = hashlib.sha256(hashlib.sha256(
309-
privSigningKey).digest()).digest()[0:4]
310-
privSigningKeyWIF = arithmetic.changebase(
311-
privSigningKey + checksum, 256, 58)
312-
313-
privEncryptionKey = '\x80' + \
314-
potentialPrivEncryptionKey
315-
checksum = hashlib.sha256(hashlib.sha256(
316-
privEncryptionKey).digest()).digest()[0:4]
317-
privEncryptionKeyWIF = arithmetic.changebase(
318-
privEncryptionKey + checksum, 256, 58)
293+
privSigningKeyWIF = \
294+
highlevelcrypto.encodeWalletImportFormat(
295+
potentialPrivSigningKey)
296+
privEncryptionKeyWIF = \
297+
highlevelcrypto.encodeWalletImportFormat(
298+
potentialPrivEncryptionKey)
319299

320300
try:
321301
BMConfigParser().add_section(address)

src/class_singleWorker.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,9 @@ def _getKeysForAddress(self, address):
197197
privEncryptionKeyBase58 = BMConfigParser().get(
198198
address, 'privencryptionkey')
199199

200-
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
200+
privSigningKeyHex = hexlify(highlevelcrypto.decodeWalletImportFormat(
201201
privSigningKeyBase58))
202-
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
202+
privEncryptionKeyHex = hexlify(highlevelcrypto.decodeWalletImportFormat(
203203
privEncryptionKeyBase58))
204204

205205
# The \x04 on the beginning of the public keys are not sent.
@@ -267,14 +267,17 @@ def doPOWForMyV2Pubkey(self, adressHash):
267267

268268
try:
269269
# privSigningKeyHex, privEncryptionKeyHex
270-
_, _, pubSigningKey, pubEncryptionKey = \
271-
self._getKeysForAddress(myAddress)
272-
except Exception as err:
270+
pubSigningKey, pubEncryptionKey = self._getKeysForAddress(
271+
myAddress)[2:]
272+
except ValueError:
273+
self.logger.error(
274+
'Could not read decode privkey for address %s', myAddress)
275+
return
276+
except Exception:
273277
self.logger.error(
274278
'Error within doPOWForMyV2Pubkey. Could not read'
275279
' the keys from the keys.dat file for a requested'
276-
' address. %s\n', err
277-
)
280+
' address. %s\n', exc_info=True)
278281
return
279282

280283
payload += pubSigningKey + pubEncryptionKey
@@ -343,12 +346,15 @@ def sendOutOrStoreMyV3Pubkey(self, adressHash):
343346
# , privEncryptionKeyHex
344347
privSigningKeyHex, _, pubSigningKey, pubEncryptionKey = \
345348
self._getKeysForAddress(myAddress)
346-
except Exception as err:
349+
except ValueError:
350+
self.logger.error(
351+
'Could not read decode privkey for address %s', myAddress)
352+
return
353+
except Exception:
347354
self.logger.error(
348355
'Error within sendOutOrStoreMyV3Pubkey. Could not read'
349356
' the keys from the keys.dat file for a requested'
350-
' address. %s\n', err
351-
)
357+
' address. %s\n', exc_info=True)
352358
return
353359

354360
payload += pubSigningKey + pubEncryptionKey
@@ -414,12 +420,15 @@ def sendOutOrStoreMyV4Pubkey(self, myAddress):
414420
# , privEncryptionKeyHex
415421
privSigningKeyHex, _, pubSigningKey, pubEncryptionKey = \
416422
self._getKeysForAddress(myAddress)
417-
except Exception as err:
423+
except ValueError:
424+
self.logger.error(
425+
'Could not read decode privkey for address %s', myAddress)
426+
return
427+
except Exception:
418428
self.logger.error(
419429
'Error within sendOutOrStoreMyV4Pubkey. Could not read'
420430
' the keys from the keys.dat file for a requested'
421-
' address. %s\n', err
422-
)
431+
' address. %s\n', exc_info=True)
423432
return
424433

425434
dataToEncrypt += pubSigningKey + pubEncryptionKey
@@ -1088,8 +1097,9 @@ def sendMsg(self):
10881097
' from the keys.dat file for our own address. %s\n',
10891098
err)
10901099
continue
1091-
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
1092-
privEncryptionKeyBase58))
1100+
privEncryptionKeyHex = hexlify(
1101+
highlevelcrypto.decodeWalletImportFormat(
1102+
privEncryptionKeyBase58))
10931103
pubEncryptionKeyBase256 = unhexlify(highlevelcrypto.privToPub(
10941104
privEncryptionKeyHex))[1:]
10951105
requiredAverageProofOfWorkNonceTrialsPerByte = \

src/highlevelcrypto.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,35 @@ def calculateInventoryHash(data):
3636
return double_sha512(data)[:32]
3737

3838

39+
# WIF (uses arithmetic ):
40+
def decodeWalletImportFormat(WIFstring):
41+
"""
42+
Convert private key from base58 that's used in the config file to
43+
8-bit binary string.
44+
"""
45+
fullString = a.changebase(WIFstring, 58, 256)
46+
privkey = fullString[:-4]
47+
if fullString[-4:] != \
48+
hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
49+
raise ValueError('Checksum failed')
50+
elif privkey[0:1] == b'\x80': # checksum passed
51+
return privkey[1:]
52+
53+
raise ValueError('No hex 80 prefix')
54+
55+
56+
# An excellent way for us to store our keys
57+
# is in Wallet Import Format. Let us convert now.
58+
# https://en.bitcoin.it/wiki/Wallet_import_format
59+
def encodeWalletImportFormat(privKey):
60+
"""
61+
Convert private key from binary 8-bit string into base58check WIF string.
62+
"""
63+
privKey = b'\x80' + privKey
64+
checksum = hashlib.sha256(hashlib.sha256(privKey).digest()).digest()[0:4]
65+
return a.changebase(privKey + checksum, 256, 58)
66+
67+
3968
def makeCryptor(privkey):
4069
"""Return a private `.pyelliptic.ECC` instance"""
4170
private_key = a.changebase(privkey, 16, 256, minlen=32)

src/shared.py

Lines changed: 33 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@
2323
from debug import logger
2424
from helper_sql import sqlQuery
2525

26-
from pyelliptic import arithmetic
27-
2826

2927
myECCryptorObjects = {}
3028
MyECSubscriptionCryptorObjects = {}
@@ -76,35 +74,6 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
7674
return False
7775

7876

79-
def decodeWalletImportFormat(WIFstring):
80-
# pylint: disable=inconsistent-return-statements
81-
"""
82-
Convert private key from base58 that's used in the config file to
83-
8-bit binary string
84-
"""
85-
fullString = arithmetic.changebase(WIFstring, 58, 256)
86-
privkey = fullString[:-4]
87-
if fullString[-4:] != \
88-
hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
89-
logger.critical(
90-
'Major problem! When trying to decode one of your'
91-
' private keys, the checksum failed. Here are the first'
92-
' 6 characters of the PRIVATE key: %s',
93-
str(WIFstring)[:6]
94-
)
95-
os._exit(0) # pylint: disable=protected-access
96-
# return ""
97-
elif privkey[0] == '\x80': # checksum passed
98-
return privkey[1:]
99-
100-
logger.critical(
101-
'Major problem! When trying to decode one of your private keys,'
102-
' the checksum passed but the key doesn\'t begin with hex 80.'
103-
' Here is the PRIVATE key: %s', WIFstring
104-
)
105-
os._exit(0) # pylint: disable=protected-access
106-
107-
10877
def reloadMyAddressHashes():
10978
"""Reload keys for user's addresses from the config file"""
11079
logger.debug('reloading keys from keys.dat file')
@@ -118,30 +87,39 @@ def reloadMyAddressHashes():
11887
hasEnabledKeys = False
11988
for addressInKeysFile in BMConfigParser().addresses():
12089
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
121-
if isEnabled:
122-
hasEnabledKeys = True
123-
# status
124-
addressVersionNumber, streamNumber, hashobj = decodeAddress(
125-
addressInKeysFile)[1:]
126-
if addressVersionNumber in (2, 3, 4):
127-
# Returns a simple 32 bytes of information encoded
128-
# in 64 Hex characters, or null if there was an error.
129-
privEncryptionKey = hexlify(decodeWalletImportFormat(
130-
BMConfigParser().get(addressInKeysFile, 'privencryptionkey')))
131-
# It is 32 bytes encoded as 64 hex characters
132-
if len(privEncryptionKey) == 64:
133-
myECCryptorObjects[hashobj] = \
134-
highlevelcrypto.makeCryptor(privEncryptionKey)
135-
myAddressesByHash[hashobj] = addressInKeysFile
136-
tag = highlevelcrypto.double_sha512(
137-
encodeVarint(addressVersionNumber)
138-
+ encodeVarint(streamNumber) + hashobj)[32:]
139-
myAddressesByTag[tag] = addressInKeysFile
140-
else:
141-
logger.error(
142-
'Error in reloadMyAddressHashes: Can\'t handle'
143-
' address versions other than 2, 3, or 4.\n'
144-
)
90+
if not isEnabled:
91+
continue
92+
93+
hasEnabledKeys = True
94+
95+
addressVersionNumber, streamNumber, hashobj = decodeAddress(
96+
addressInKeysFile)[1:]
97+
if addressVersionNumber not in (2, 3, 4):
98+
logger.error(
99+
'Error in reloadMyAddressHashes: Can\'t handle'
100+
' address versions other than 2, 3, or 4.\n')
101+
continue
102+
103+
# Returns a simple 32 bytes of information encoded in 64 Hex characters.
104+
try:
105+
privEncryptionKey = hexlify(
106+
highlevelcrypto.decodeWalletImportFormat(
107+
BMConfigParser().get(addressInKeysFile, 'privencryptionkey')
108+
))
109+
except ValueError:
110+
logger.error(
111+
'Error in reloadMyAddressHashes: failed to decode'
112+
' one of the private keys for address %s', addressInKeysFile)
113+
continue
114+
# It is 32 bytes encoded as 64 hex characters
115+
if len(privEncryptionKey) == 64:
116+
myECCryptorObjects[hashobj] = \
117+
highlevelcrypto.makeCryptor(privEncryptionKey)
118+
myAddressesByHash[hashobj] = addressInKeysFile
119+
tag = highlevelcrypto.double_sha512(
120+
encodeVarint(addressVersionNumber)
121+
+ encodeVarint(streamNumber) + hashobj)[32:]
122+
myAddressesByTag[tag] = addressInKeysFile
145123

146124
if not keyfileSecure:
147125
fixSensitiveFilePermissions(os.path.join(

0 commit comments

Comments
 (0)