Skip to content

Commit e7fffe7

Browse files
committed
Seperated out class_addressGenerator - not perfectly
1 parent 0b258be commit e7fffe7

2 files changed

Lines changed: 292 additions & 263 deletions

File tree

src/bitmessagemain.py

Lines changed: 16 additions & 263 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
from class_singleListener import *
5353
from class_sqlThread import *
5454
from class_singleCleaner import *
55+
from class_addressGenerator import *
5556

5657
# Helper Functions
5758
import helper_startup
@@ -2434,34 +2435,6 @@ def connectToStream(streamNumber):
24342435
a.setup(streamNumber)
24352436
a.start()
24362437

2437-
# Does an EC point multiplication; turns a private key into a public key.
2438-
2439-
2440-
def pointMult(secret):
2441-
# ctx = OpenSSL.BN_CTX_new() #This value proved to cause Seg Faults on
2442-
# Linux. It turns out that it really didn't speed up EC_POINT_mul anyway.
2443-
k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1'))
2444-
priv_key = OpenSSL.BN_bin2bn(secret, 32, 0)
2445-
group = OpenSSL.EC_KEY_get0_group(k)
2446-
pub_key = OpenSSL.EC_POINT_new(group)
2447-
2448-
OpenSSL.EC_POINT_mul(group, pub_key, priv_key, None, None, None)
2449-
OpenSSL.EC_KEY_set_private_key(k, priv_key)
2450-
OpenSSL.EC_KEY_set_public_key(k, pub_key)
2451-
# print 'priv_key',priv_key
2452-
# print 'pub_key',pub_key
2453-
2454-
size = OpenSSL.i2o_ECPublicKey(k, 0)
2455-
mb = ctypes.create_string_buffer(size)
2456-
OpenSSL.i2o_ECPublicKey(k, ctypes.byref(ctypes.pointer(mb)))
2457-
# print 'mb.raw', mb.raw.encode('hex'), 'length:', len(mb.raw)
2458-
# print 'mb.raw', mb.raw, 'length:', len(mb.raw)
2459-
2460-
OpenSSL.EC_POINT_free(pub_key)
2461-
# OpenSSL.BN_CTX_free(ctx)
2462-
OpenSSL.BN_free(priv_key)
2463-
OpenSSL.EC_KEY_free(k)
2464-
return mb.raw
24652438

24662439

24672440
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
@@ -3350,241 +3323,6 @@ def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime):
33503323
return headerData + payload
33513324

33523325

3353-
class addressGenerator(threading.Thread):
3354-
3355-
def __init__(self):
3356-
# QThread.__init__(self, parent)
3357-
threading.Thread.__init__(self)
3358-
3359-
def run(self):
3360-
while True:
3361-
queueValue = shared.addressGeneratorQueue.get()
3362-
nonceTrialsPerByte = 0
3363-
payloadLengthExtraBytes = 0
3364-
if len(queueValue) == 7:
3365-
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
3366-
elif len(queueValue) == 9:
3367-
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
3368-
else:
3369-
sys.stderr.write(
3370-
'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % queueValue)
3371-
if addressVersionNumber < 3 or addressVersionNumber > 3:
3372-
sys.stderr.write(
3373-
'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber)
3374-
if nonceTrialsPerByte == 0:
3375-
nonceTrialsPerByte = shared.config.getint(
3376-
'bitmessagesettings', 'defaultnoncetrialsperbyte')
3377-
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
3378-
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
3379-
if payloadLengthExtraBytes == 0:
3380-
payloadLengthExtraBytes = shared.config.getint(
3381-
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
3382-
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
3383-
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
3384-
if addressVersionNumber == 3: # currently the only one supported.
3385-
if command == 'createRandomAddress':
3386-
shared.UISignalQueue.put((
3387-
'updateStatusBar', _translate("MainWindow", "Generating one new address")))
3388-
# This next section is a little bit strange. We're going to generate keys over and over until we
3389-
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
3390-
# we won't store the \x00 or \x00\x00 bytes thus making the
3391-
# address shorter.
3392-
startTime = time.time()
3393-
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
3394-
potentialPrivSigningKey = OpenSSL.rand(32)
3395-
potentialPubSigningKey = pointMult(potentialPrivSigningKey)
3396-
while True:
3397-
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
3398-
potentialPrivEncryptionKey = OpenSSL.rand(32)
3399-
potentialPubEncryptionKey = pointMult(
3400-
potentialPrivEncryptionKey)
3401-
# print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex')
3402-
# print 'potentialPubEncryptionKey',
3403-
# potentialPubEncryptionKey.encode('hex')
3404-
ripe = hashlib.new('ripemd160')
3405-
sha = hashlib.new('sha512')
3406-
sha.update(
3407-
potentialPubSigningKey + potentialPubEncryptionKey)
3408-
ripe.update(sha.digest())
3409-
# print 'potential ripe.digest',
3410-
# ripe.digest().encode('hex')
3411-
if eighteenByteRipe:
3412-
if ripe.digest()[:2] == '\x00\x00':
3413-
break
3414-
else:
3415-
if ripe.digest()[:1] == '\x00':
3416-
break
3417-
print 'Generated address with ripe digest:', ripe.digest().encode('hex')
3418-
print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.'
3419-
address = encodeAddress(3, streamNumber, ripe.digest())
3420-
3421-
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
3422-
# https://en.bitcoin.it/wiki/Wallet_import_format
3423-
privSigningKey = '\x80' + potentialPrivSigningKey
3424-
checksum = hashlib.sha256(hashlib.sha256(
3425-
privSigningKey).digest()).digest()[0:4]
3426-
privSigningKeyWIF = arithmetic.changebase(
3427-
privSigningKey + checksum, 256, 58)
3428-
# print 'privSigningKeyWIF',privSigningKeyWIF
3429-
3430-
privEncryptionKey = '\x80' + potentialPrivEncryptionKey
3431-
checksum = hashlib.sha256(hashlib.sha256(
3432-
privEncryptionKey).digest()).digest()[0:4]
3433-
privEncryptionKeyWIF = arithmetic.changebase(
3434-
privEncryptionKey + checksum, 256, 58)
3435-
# print 'privEncryptionKeyWIF',privEncryptionKeyWIF
3436-
3437-
shared.config.add_section(address)
3438-
shared.config.set(address, 'label', label)
3439-
shared.config.set(address, 'enabled', 'true')
3440-
shared.config.set(address, 'decoy', 'false')
3441-
shared.config.set(address, 'noncetrialsperbyte', str(
3442-
nonceTrialsPerByte))
3443-
shared.config.set(address, 'payloadlengthextrabytes', str(
3444-
payloadLengthExtraBytes))
3445-
shared.config.set(
3446-
address, 'privSigningKey', privSigningKeyWIF)
3447-
shared.config.set(
3448-
address, 'privEncryptionKey', privEncryptionKeyWIF)
3449-
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
3450-
shared.config.write(configfile)
3451-
3452-
# It may be the case that this address is being generated
3453-
# as a result of a call to the API. Let us put the result
3454-
# in the necessary queue.
3455-
apiAddressGeneratorReturnQueue.put(address)
3456-
3457-
shared.UISignalQueue.put((
3458-
'updateStatusBar', _translate("MainWindow", "Done generating address. Doing work necessary to broadcast it...")))
3459-
shared.UISignalQueue.put(('writeNewAddressToTable', (
3460-
label, address, streamNumber)))
3461-
shared.reloadMyAddressHashes()
3462-
shared.workerQueue.put((
3463-
'doPOWForMyV3Pubkey', ripe.digest()))
3464-
3465-
elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress':
3466-
if len(deterministicPassphrase) == 0:
3467-
sys.stderr.write(
3468-
'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.')
3469-
if command == 'createDeterministicAddresses':
3470-
statusbar = 'Generating ' + str(
3471-
numberOfAddressesToMake) + ' new addresses.'
3472-
shared.UISignalQueue.put((
3473-
'updateStatusBar', statusbar))
3474-
signingKeyNonce = 0
3475-
encryptionKeyNonce = 1
3476-
listOfNewAddressesToSendOutThroughTheAPI = [
3477-
] # We fill out this list no matter what although we only need it if we end up passing the info to the API.
3478-
3479-
for i in range(numberOfAddressesToMake):
3480-
# This next section is a little bit strange. We're going to generate keys over and over until we
3481-
# find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them
3482-
# into a Bitmessage address, we won't store the \x00 or
3483-
# \x00\x00 bytes thus making the address shorter.
3484-
startTime = time.time()
3485-
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
3486-
while True:
3487-
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
3488-
potentialPrivSigningKey = hashlib.sha512(
3489-
deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32]
3490-
potentialPrivEncryptionKey = hashlib.sha512(
3491-
deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32]
3492-
potentialPubSigningKey = pointMult(
3493-
potentialPrivSigningKey)
3494-
potentialPubEncryptionKey = pointMult(
3495-
potentialPrivEncryptionKey)
3496-
# print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex')
3497-
# print 'potentialPubEncryptionKey',
3498-
# potentialPubEncryptionKey.encode('hex')
3499-
signingKeyNonce += 2
3500-
encryptionKeyNonce += 2
3501-
ripe = hashlib.new('ripemd160')
3502-
sha = hashlib.new('sha512')
3503-
sha.update(
3504-
potentialPubSigningKey + potentialPubEncryptionKey)
3505-
ripe.update(sha.digest())
3506-
# print 'potential ripe.digest',
3507-
# ripe.digest().encode('hex')
3508-
if eighteenByteRipe:
3509-
if ripe.digest()[:2] == '\x00\x00':
3510-
break
3511-
else:
3512-
if ripe.digest()[:1] == '\x00':
3513-
break
3514-
3515-
print 'ripe.digest', ripe.digest().encode('hex')
3516-
print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'keys per second.'
3517-
address = encodeAddress(3, streamNumber, ripe.digest())
3518-
3519-
if command == 'createDeterministicAddresses':
3520-
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
3521-
# https://en.bitcoin.it/wiki/Wallet_import_format
3522-
privSigningKey = '\x80' + potentialPrivSigningKey
3523-
checksum = hashlib.sha256(hashlib.sha256(
3524-
privSigningKey).digest()).digest()[0:4]
3525-
privSigningKeyWIF = arithmetic.changebase(
3526-
privSigningKey + checksum, 256, 58)
3527-
3528-
privEncryptionKey = '\x80' + \
3529-
potentialPrivEncryptionKey
3530-
checksum = hashlib.sha256(hashlib.sha256(
3531-
privEncryptionKey).digest()).digest()[0:4]
3532-
privEncryptionKeyWIF = arithmetic.changebase(
3533-
privEncryptionKey + checksum, 256, 58)
3534-
3535-
try:
3536-
shared.config.add_section(address)
3537-
print 'label:', label
3538-
shared.config.set(address, 'label', label)
3539-
shared.config.set(address, 'enabled', 'true')
3540-
shared.config.set(address, 'decoy', 'false')
3541-
shared.config.set(address, 'noncetrialsperbyte', str(
3542-
nonceTrialsPerByte))
3543-
shared.config.set(address, 'payloadlengthextrabytes', str(
3544-
payloadLengthExtraBytes))
3545-
shared.config.set(
3546-
address, 'privSigningKey', privSigningKeyWIF)
3547-
shared.config.set(
3548-
address, 'privEncryptionKey', privEncryptionKeyWIF)
3549-
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
3550-
shared.config.write(configfile)
3551-
3552-
shared.UISignalQueue.put(('writeNewAddressToTable', (
3553-
label, address, str(streamNumber))))
3554-
listOfNewAddressesToSendOutThroughTheAPI.append(
3555-
address)
3556-
# if eighteenByteRipe:
3557-
# shared.reloadMyAddressHashes()#This is
3558-
# necessary here (rather than just at the end)
3559-
# because otherwise if the human generates a
3560-
# large number of new addresses and uses one
3561-
# before they are done generating, the program
3562-
# will receive a getpubkey message and will
3563-
# ignore it.
3564-
shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor(
3565-
potentialPrivEncryptionKey.encode('hex'))
3566-
shared.myAddressesByHash[
3567-
ripe.digest()] = address
3568-
shared.workerQueue.put((
3569-
'doPOWForMyV3Pubkey', ripe.digest()))
3570-
except:
3571-
print address, 'already exists. Not adding it again.'
3572-
3573-
# Done generating addresses.
3574-
if command == 'createDeterministicAddresses':
3575-
# It may be the case that this address is being
3576-
# generated as a result of a call to the API. Let us
3577-
# put the result in the necessary queue.
3578-
apiAddressGeneratorReturnQueue.put(
3579-
listOfNewAddressesToSendOutThroughTheAPI)
3580-
shared.UISignalQueue.put((
3581-
'updateStatusBar', _translate("MainWindow", "Done generating address")))
3582-
# shared.reloadMyAddressHashes()
3583-
elif command == 'getDeterministicAddress':
3584-
apiAddressGeneratorReturnQueue.put(address)
3585-
else:
3586-
raise Exception(
3587-
"Error in the addressGenerator thread. Thread was given a command it could not understand: " + command)
35883326

35893327
# This is one of several classes that constitute the API
35903328
# This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros).
@@ -4341,6 +4079,21 @@ def _translate(context, text): # A QT version of _translate is defined above.
43414079
while True:
43424080
time.sleep(20)
43434081

4082+
def translateText(context, text):
4083+
if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
4084+
try:
4085+
from PyQt4 import QtCore, QtGui
4086+
except Exception as err:
4087+
print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
4088+
print 'Error message:', err
4089+
os._exit(0)
4090+
return QtGui.QApplication.translate(context, text)
4091+
else:
4092+
if '%' in text:
4093+
return translateClass(context, text.replace('%','',1))
4094+
else:
4095+
return text
4096+
43444097

43454098
# So far, the creation of and management of the Bitmessage protocol and this
43464099
# client is a one-man operation. Bitcoin tips are quite appreciated.

0 commit comments

Comments
 (0)