Address operations: flake8
This commit is contained in:
parent
cbb228db8b
commit
006b98389b
244
src/addresses.py
244
src/addresses.py
|
@ -1,11 +1,12 @@
|
|||
import hashlib
|
||||
from struct import *
|
||||
from struct import pack, unpack
|
||||
from pyelliptic import arithmetic
|
||||
from binascii import hexlify, unhexlify
|
||||
|
||||
#from debug import logger
|
||||
from debug import logger
|
||||
|
||||
#There is another copy of this function in Bitmessagemain.py
|
||||
|
||||
# There is another copy of this function in Bitmessagemain.py
|
||||
def convertIntToString(n):
|
||||
a = __builtins__.hex(n)
|
||||
if a[-1:] == 'L':
|
||||
|
@ -17,6 +18,7 @@ def convertIntToString(n):
|
|||
|
||||
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
|
||||
|
||||
def encodeBase58(num, alphabet=ALPHABET):
|
||||
"""Encode a number in Base X
|
||||
|
||||
|
@ -29,12 +31,13 @@ def encodeBase58(num, alphabet=ALPHABET):
|
|||
base = len(alphabet)
|
||||
while num:
|
||||
rem = num % base
|
||||
#print 'num is:', num
|
||||
# print 'num is:', num
|
||||
num = num // base
|
||||
arr.append(alphabet[rem])
|
||||
arr.reverse()
|
||||
return ''.join(arr)
|
||||
|
||||
|
||||
def decodeBase58(string, alphabet=ALPHABET):
|
||||
"""Decode a Base X encoded string into the number
|
||||
|
||||
|
@ -44,73 +47,91 @@ def decodeBase58(string, alphabet=ALPHABET):
|
|||
"""
|
||||
base = len(alphabet)
|
||||
num = 0
|
||||
|
||||
|
||||
try:
|
||||
for char in string:
|
||||
num *= base
|
||||
num += alphabet.index(char)
|
||||
except:
|
||||
#character not found (like a space character or a 0)
|
||||
# character not found (like a space character or a 0)
|
||||
return 0
|
||||
return num
|
||||
|
||||
|
||||
def encodeVarint(integer):
|
||||
if integer < 0:
|
||||
logger.error('varint cannot be < 0')
|
||||
raise SystemExit
|
||||
if integer < 253:
|
||||
return pack('>B',integer)
|
||||
return pack('>B', integer)
|
||||
if integer >= 253 and integer < 65536:
|
||||
return pack('>B',253) + pack('>H',integer)
|
||||
return pack('>B', 253) + pack('>H', integer)
|
||||
if integer >= 65536 and integer < 4294967296:
|
||||
return pack('>B',254) + pack('>I',integer)
|
||||
return pack('>B', 254) + pack('>I', integer)
|
||||
if integer >= 4294967296 and integer < 18446744073709551616:
|
||||
return pack('>B',255) + pack('>Q',integer)
|
||||
return pack('>B', 255) + pack('>Q', integer)
|
||||
if integer >= 18446744073709551616:
|
||||
logger.error('varint cannot be >= 18446744073709551616')
|
||||
raise SystemExit
|
||||
|
||||
|
||||
|
||||
class varintDecodeError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def decodeVarint(data):
|
||||
"""
|
||||
Decodes an encoded varint to an integer and returns it.
|
||||
Per protocol v3, the encoded value must be encoded with
|
||||
the minimum amount of data possible or else it is malformed.
|
||||
Decodes an encoded varint to an integer and returns it.
|
||||
Per protocol v3, the encoded value must be encoded with
|
||||
the minimum amount of data possible or else it is malformed.
|
||||
Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
|
||||
"""
|
||||
|
||||
|
||||
if len(data) == 0:
|
||||
return (0,0)
|
||||
firstByte, = unpack('>B',data[0:1])
|
||||
return (0, 0)
|
||||
firstByte, = unpack('>B', data[0:1])
|
||||
if firstByte < 253:
|
||||
# encodes 0 to 252
|
||||
return (firstByte,1) #the 1 is the length of the varint
|
||||
return (firstByte, 1) # the 1 is the length of the varint
|
||||
if firstByte == 253:
|
||||
# encodes 253 to 65535
|
||||
if len(data) < 3:
|
||||
raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 3.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>H',data[1:3])
|
||||
raise varintDecodeError(
|
||||
'The first byte of this varint as an integer is %s'
|
||||
' but the total length is only %s. It needs to be'
|
||||
' at least 3.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>H', data[1:3])
|
||||
if encodedValue < 253:
|
||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
||||
return (encodedValue,3)
|
||||
raise varintDecodeError(
|
||||
'This varint does not encode the value with the lowest'
|
||||
' possible number of bytes.')
|
||||
return (encodedValue, 3)
|
||||
if firstByte == 254:
|
||||
# encodes 65536 to 4294967295
|
||||
if len(data) < 5:
|
||||
raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 5.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>I',data[1:5])
|
||||
raise varintDecodeError(
|
||||
'The first byte of this varint as an integer is %s'
|
||||
' but the total length is only %s. It needs to be'
|
||||
' at least 5.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>I', data[1:5])
|
||||
if encodedValue < 65536:
|
||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
||||
return (encodedValue,5)
|
||||
raise varintDecodeError(
|
||||
'This varint does not encode the value with the lowest'
|
||||
' possible number of bytes.')
|
||||
return (encodedValue, 5)
|
||||
if firstByte == 255:
|
||||
# encodes 4294967296 to 18446744073709551615
|
||||
if len(data) < 9:
|
||||
raise varintDecodeError('The first byte of this varint as an integer is %s but the total length is only %s. It needs to be at least 9.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>Q',data[1:9])
|
||||
raise varintDecodeError(
|
||||
'The first byte of this varint as an integer is %s'
|
||||
' but the total length is only %s. It needs to be'
|
||||
' at least 9.' % (firstByte, len(data)))
|
||||
encodedValue, = unpack('>Q', data[1:9])
|
||||
if encodedValue < 4294967296:
|
||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
||||
return (encodedValue,9)
|
||||
raise varintDecodeError(
|
||||
'This varint does not encode the value with the lowest'
|
||||
' possible number of bytes.')
|
||||
return (encodedValue, 9)
|
||||
|
||||
|
||||
def calculateInventoryHash(data):
|
||||
|
@ -120,21 +141,27 @@ def calculateInventoryHash(data):
|
|||
sha2.update(sha.digest())
|
||||
return sha2.digest()[0:32]
|
||||
|
||||
def encodeAddress(version,stream,ripe):
|
||||
|
||||
def encodeAddress(version, stream, ripe):
|
||||
if version >= 2 and version < 4:
|
||||
if len(ripe) != 20:
|
||||
raise Exception("Programming error in encodeAddress: The length of a given ripe hash was not 20.")
|
||||
raise Exception(
|
||||
'Programming error in encodeAddress: The length of'
|
||||
' a given ripe hash was not 20.'
|
||||
)
|
||||
if ripe[:2] == '\x00\x00':
|
||||
ripe = ripe[2:]
|
||||
elif ripe[:1] == '\x00':
|
||||
ripe = ripe[1:]
|
||||
elif version == 4:
|
||||
if len(ripe) != 20:
|
||||
raise Exception("Programming error in encodeAddress: The length of a given ripe hash was not 20.")
|
||||
raise Exception(
|
||||
'Programming error in encodeAddress: The length of'
|
||||
' a given ripe hash was not 20.')
|
||||
ripe = ripe.lstrip('\x00')
|
||||
|
||||
storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe
|
||||
|
||||
|
||||
# Generate the checksum
|
||||
sha = hashlib.new('sha512')
|
||||
sha.update(storedBinaryData)
|
||||
|
@ -143,11 +170,13 @@ def encodeAddress(version,stream,ripe):
|
|||
sha.update(currentHash)
|
||||
checksum = sha.digest()[0:4]
|
||||
|
||||
asInt = int(hexlify(storedBinaryData) + hexlify(checksum),16)
|
||||
return 'BM-'+ encodeBase58(asInt)
|
||||
asInt = int(hexlify(storedBinaryData) + hexlify(checksum), 16)
|
||||
return 'BM-' + encodeBase58(asInt)
|
||||
|
||||
|
||||
def decodeAddress(address):
|
||||
#returns (status, address version number, stream number, data (almost certainly a ripe hash))
|
||||
# returns (status, address version number, stream number,
|
||||
# data (almost certainly a ripe hash))
|
||||
|
||||
address = str(address).strip()
|
||||
|
||||
|
@ -157,14 +186,15 @@ def decodeAddress(address):
|
|||
integer = decodeBase58(address)
|
||||
if integer == 0:
|
||||
status = 'invalidcharacters'
|
||||
return status,0,0,""
|
||||
#after converting to hex, the string will be prepended with a 0x and appended with a L
|
||||
return status, 0, 0, ''
|
||||
# after converting to hex, the string will be prepended
|
||||
# with a 0x and appended with a L
|
||||
hexdata = hex(integer)[2:-1]
|
||||
|
||||
if len(hexdata) % 2 != 0:
|
||||
hexdata = '0' + hexdata
|
||||
|
||||
#print 'hexdata', hexdata
|
||||
# print 'hexdata', hexdata
|
||||
|
||||
data = unhexlify(hexdata)
|
||||
checksum = data[-4:]
|
||||
|
@ -172,15 +202,15 @@ def decodeAddress(address):
|
|||
sha = hashlib.new('sha512')
|
||||
sha.update(data[:-4])
|
||||
currentHash = sha.digest()
|
||||
#print 'sha after first hashing: ', sha.hexdigest()
|
||||
# print 'sha after first hashing: ', sha.hexdigest()
|
||||
sha = hashlib.new('sha512')
|
||||
sha.update(currentHash)
|
||||
#print 'sha after second hashing: ', sha.hexdigest()
|
||||
# print 'sha after second hashing: ', sha.hexdigest()
|
||||
|
||||
if checksum != sha.digest()[0:4]:
|
||||
status = 'checksumfailed'
|
||||
return status,0,0,""
|
||||
#else:
|
||||
return status, 0, 0, ''
|
||||
# else:
|
||||
# print 'checksum PASSED'
|
||||
|
||||
try:
|
||||
|
@ -188,55 +218,64 @@ def decodeAddress(address):
|
|||
except varintDecodeError as e:
|
||||
logger.error(str(e))
|
||||
status = 'varintmalformed'
|
||||
return status,0,0,""
|
||||
#print 'addressVersionNumber', addressVersionNumber
|
||||
#print 'bytesUsedByVersionNumber', bytesUsedByVersionNumber
|
||||
return status, 0, 0, ''
|
||||
# print 'addressVersionNumber', addressVersionNumber
|
||||
# print 'bytesUsedByVersionNumber', bytesUsedByVersionNumber
|
||||
|
||||
if addressVersionNumber > 4:
|
||||
logger.error('cannot decode address version numbers this high')
|
||||
status = 'versiontoohigh'
|
||||
return status,0,0,""
|
||||
return status, 0, 0, ''
|
||||
elif addressVersionNumber == 0:
|
||||
logger.error('cannot decode address version numbers of zero.')
|
||||
status = 'versiontoohigh'
|
||||
return status,0,0,""
|
||||
return status, 0, 0, ''
|
||||
|
||||
try:
|
||||
streamNumber, bytesUsedByStreamNumber = decodeVarint(data[bytesUsedByVersionNumber:])
|
||||
streamNumber, bytesUsedByStreamNumber = \
|
||||
decodeVarint(data[bytesUsedByVersionNumber:])
|
||||
except varintDecodeError as e:
|
||||
logger.error(str(e))
|
||||
status = 'varintmalformed'
|
||||
return status,0,0,""
|
||||
#print streamNumber
|
||||
return status, 0, 0, ''
|
||||
# print streamNumber
|
||||
status = 'success'
|
||||
if addressVersionNumber == 1:
|
||||
return status,addressVersionNumber,streamNumber,data[-24:-4]
|
||||
return status, addressVersionNumber, streamNumber, data[-24:-4]
|
||||
elif addressVersionNumber == 2 or addressVersionNumber == 3:
|
||||
embeddedRipeData = data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]
|
||||
embeddedRipeData = \
|
||||
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||
if len(embeddedRipeData) == 19:
|
||||
return status,addressVersionNumber,streamNumber,'\x00'+embeddedRipeData
|
||||
return status, addressVersionNumber, streamNumber, \
|
||||
'\x00'+embeddedRipeData
|
||||
elif len(embeddedRipeData) == 20:
|
||||
return status,addressVersionNumber,streamNumber,embeddedRipeData
|
||||
return status, addressVersionNumber, streamNumber, \
|
||||
embeddedRipeData
|
||||
elif len(embeddedRipeData) == 18:
|
||||
return status,addressVersionNumber,streamNumber,'\x00\x00'+embeddedRipeData
|
||||
return status, addressVersionNumber, streamNumber, \
|
||||
'\x00\x00' + embeddedRipeData
|
||||
elif len(embeddedRipeData) < 18:
|
||||
return 'ripetooshort',0,0,""
|
||||
return 'ripetooshort', 0, 0, ''
|
||||
elif len(embeddedRipeData) > 20:
|
||||
return 'ripetoolong',0,0,""
|
||||
return 'ripetoolong', 0, 0, ''
|
||||
else:
|
||||
return 'otherproblem',0,0,""
|
||||
return 'otherproblem', 0, 0, ''
|
||||
elif addressVersionNumber == 4:
|
||||
embeddedRipeData = data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]
|
||||
embeddedRipeData = \
|
||||
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||
if embeddedRipeData[0:1] == '\x00':
|
||||
# In order to enforce address non-malleability, encoded RIPE data must have NULL bytes removed from the front
|
||||
return 'encodingproblem',0,0,""
|
||||
# In order to enforce address non-malleability, encoded
|
||||
# RIPE data must have NULL bytes removed from the front
|
||||
return 'encodingproblem', 0, 0, ''
|
||||
elif len(embeddedRipeData) > 20:
|
||||
return 'ripetoolong',0,0,""
|
||||
return 'ripetoolong', 0, 0, ''
|
||||
elif len(embeddedRipeData) < 4:
|
||||
return 'ripetooshort',0,0,""
|
||||
return 'ripetooshort', 0, 0, ''
|
||||
else:
|
||||
x00string = '\x00' * (20 - len(embeddedRipeData))
|
||||
return status,addressVersionNumber,streamNumber,x00string+embeddedRipeData
|
||||
return status, addressVersionNumber, streamNumber, \
|
||||
x00string + embeddedRipeData
|
||||
|
||||
|
||||
def addBMIfNotPresent(address):
|
||||
address = str(address).strip()
|
||||
|
@ -245,38 +284,65 @@ def addBMIfNotPresent(address):
|
|||
else:
|
||||
return address
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print 'Let us make an address from scratch. Suppose we generate two random 32 byte values and call the first one the signing key and the second one the encryption key:'
|
||||
privateSigningKey = '93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665'
|
||||
privateEncryptionKey = '4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a'
|
||||
print 'privateSigningKey =', privateSigningKey
|
||||
print 'privateEncryptionKey =', privateEncryptionKey
|
||||
print 'Now let us convert them to public keys by doing an elliptic curve point multiplication.'
|
||||
print(
|
||||
'\nLet us make an address from scratch. Suppose we generate two'
|
||||
' random 32 byte values and call the first one the signing key'
|
||||
' and the second one the encryption key:'
|
||||
)
|
||||
privateSigningKey = \
|
||||
'93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665'
|
||||
privateEncryptionKey = \
|
||||
'4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a'
|
||||
print(
|
||||
'\nprivateSigningKey = %s\nprivateEncryptionKey = %s' %
|
||||
(privateSigningKey, privateEncryptionKey)
|
||||
)
|
||||
print(
|
||||
'\nNow let us convert them to public keys by doing'
|
||||
' an elliptic curve point multiplication.'
|
||||
)
|
||||
publicSigningKey = arithmetic.privtopub(privateSigningKey)
|
||||
publicEncryptionKey = arithmetic.privtopub(privateEncryptionKey)
|
||||
print 'publicSigningKey =', publicSigningKey
|
||||
print 'publicEncryptionKey =', publicEncryptionKey
|
||||
print(
|
||||
'\npublicSigningKey = %s\npublicEncryptionKey = %s' %
|
||||
(publicSigningKey, publicEncryptionKey)
|
||||
)
|
||||
|
||||
print 'Notice that they both begin with the \\x04 which specifies the encoding type. This prefix is not send over the wire. You must strip if off before you send your public key across the wire, and you must add it back when you receive a public key.'
|
||||
print(
|
||||
'\nNotice that they both begin with the \\x04 which specifies'
|
||||
' the encoding type. This prefix is not send over the wire.'
|
||||
' You must strip if off before you send your public key across'
|
||||
' the wire, and you must add it back when you receive a public key.'
|
||||
)
|
||||
|
||||
publicSigningKeyBinary = arithmetic.changebase(publicSigningKey,16,256,minlen=64)
|
||||
publicEncryptionKeyBinary = arithmetic.changebase(publicEncryptionKey,16,256,minlen=64)
|
||||
publicSigningKeyBinary = \
|
||||
arithmetic.changebase(publicSigningKey, 16, 256, minlen=64)
|
||||
publicEncryptionKeyBinary = \
|
||||
arithmetic.changebase(publicEncryptionKey, 16, 256, minlen=64)
|
||||
|
||||
ripe = hashlib.new('ripemd160')
|
||||
sha = hashlib.new('sha512')
|
||||
sha.update(publicSigningKeyBinary+publicEncryptionKeyBinary)
|
||||
sha.update(publicSigningKeyBinary + publicEncryptionKeyBinary)
|
||||
|
||||
ripe.update(sha.digest())
|
||||
addressVersionNumber = 2
|
||||
streamNumber = 1
|
||||
print 'Ripe digest that we will encode in the address:', hexlify(ripe.digest())
|
||||
returnedAddress = encodeAddress(addressVersionNumber,streamNumber,ripe.digest())
|
||||
print 'Encoded address:', returnedAddress
|
||||
status,addressVersionNumber,streamNumber,data = decodeAddress(returnedAddress)
|
||||
print '\nAfter decoding address:'
|
||||
print 'Status:', status
|
||||
print 'addressVersionNumber', addressVersionNumber
|
||||
print 'streamNumber', streamNumber
|
||||
print 'length of data(the ripe hash):', len(data)
|
||||
print 'ripe data:', hexlify(data)
|
||||
|
||||
print(
|
||||
'\nRipe digest that we will encode in the address: %s' %
|
||||
hexlify(ripe.digest())
|
||||
)
|
||||
returnedAddress = \
|
||||
encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
|
||||
print('Encoded address: %s' % returnedAddress)
|
||||
status, addressVersionNumber, streamNumber, data = \
|
||||
decodeAddress(returnedAddress)
|
||||
print(
|
||||
'\nAfter decoding address:\n\tStatus: %s'
|
||||
'\n\taddressVersionNumber %s'
|
||||
'\n\tstreamNumber %s'
|
||||
'\n\tlength of data (the ripe hash): %s'
|
||||
'\n\tripe data: %s' %
|
||||
(status, addressVersionNumber, streamNumber, len(data), hexlify(data))
|
||||
)
|
||||
|
|
|
@ -1,21 +1,22 @@
|
|||
import shared
|
||||
import threading
|
||||
|
||||
import time
|
||||
import sys
|
||||
from pyelliptic.openssl import OpenSSL
|
||||
import ctypes
|
||||
import threading
|
||||
import hashlib
|
||||
import highlevelcrypto
|
||||
from addresses import *
|
||||
from bmconfigparser import BMConfigParser
|
||||
from debug import logger
|
||||
import defaults
|
||||
from helper_threading import *
|
||||
from pyelliptic import arithmetic
|
||||
import tr
|
||||
from binascii import hexlify
|
||||
from pyelliptic import arithmetic
|
||||
from pyelliptic.openssl import OpenSSL
|
||||
|
||||
import tr
|
||||
import queues
|
||||
import state
|
||||
import shared
|
||||
import defaults
|
||||
import highlevelcrypto
|
||||
from bmconfigparser import BMConfigParser
|
||||
from debug import logger
|
||||
from addresses import decodeAddress, encodeAddress, encodeVarint
|
||||
from helper_threading import StoppableThread
|
||||
|
||||
|
||||
class addressGenerator(threading.Thread, StoppableThread):
|
||||
|
||||
|
@ -23,7 +24,7 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
# QThread.__init__(self, parent)
|
||||
threading.Thread.__init__(self, name="addressGenerator")
|
||||
self.initStop()
|
||||
|
||||
|
||||
def stopThread(self):
|
||||
try:
|
||||
queues.addressGeneratorQueue.put(("stopThread", "data"))
|
||||
|
@ -38,66 +39,95 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
payloadLengthExtraBytes = 0
|
||||
live = True
|
||||
if queueValue[0] == 'createChan':
|
||||
command, addressVersionNumber, streamNumber, label, deterministicPassphrase, live = queueValue
|
||||
command, addressVersionNumber, streamNumber, label, \
|
||||
deterministicPassphrase, live = queueValue
|
||||
eighteenByteRipe = False
|
||||
numberOfAddressesToMake = 1
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||
elif queueValue[0] == 'joinChan':
|
||||
command, chanAddress, label, deterministicPassphrase, live = queueValue
|
||||
command, chanAddress, label, deterministicPassphrase, \
|
||||
live = queueValue
|
||||
eighteenByteRipe = False
|
||||
addressVersionNumber = decodeAddress(chanAddress)[1]
|
||||
streamNumber = decodeAddress(chanAddress)[2]
|
||||
numberOfAddressesToMake = 1
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||
elif len(queueValue) == 7:
|
||||
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
|
||||
command, addressVersionNumber, streamNumber, label, \
|
||||
numberOfAddressesToMake, deterministicPassphrase, \
|
||||
eighteenByteRipe = queueValue
|
||||
try:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
|
||||
'bitmessagesettings', 'numberofnullbytesonaddress')
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = \
|
||||
BMConfigParser().getint(
|
||||
'bitmessagesettings',
|
||||
'numberofnullbytesonaddress'
|
||||
)
|
||||
except:
|
||||
if eighteenByteRipe:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
||||
else:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # the default
|
||||
# the default
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||
elif len(queueValue) == 9:
|
||||
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
|
||||
command, addressVersionNumber, streamNumber, label, \
|
||||
numberOfAddressesToMake, deterministicPassphrase, \
|
||||
eighteenByteRipe, nonceTrialsPerByte, \
|
||||
payloadLengthExtraBytes = queueValue
|
||||
try:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
|
||||
'bitmessagesettings', 'numberofnullbytesonaddress')
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = \
|
||||
BMConfigParser().getint(
|
||||
'bitmessagesettings',
|
||||
'numberofnullbytesonaddress'
|
||||
)
|
||||
except:
|
||||
if eighteenByteRipe:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
||||
else:
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # the default
|
||||
# the default
|
||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||
elif queueValue[0] == 'stopThread':
|
||||
break
|
||||
else:
|
||||
sys.stderr.write(
|
||||
'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % repr(queueValue))
|
||||
logger.error(
|
||||
'Programming error: A structure with the wrong number'
|
||||
' of values was passed into the addressGeneratorQueue.'
|
||||
' Here is the queueValue: %r\n', queueValue)
|
||||
if addressVersionNumber < 3 or addressVersionNumber > 4:
|
||||
sys.stderr.write(
|
||||
'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)
|
||||
logger.error(
|
||||
'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)
|
||||
if nonceTrialsPerByte == 0:
|
||||
nonceTrialsPerByte = BMConfigParser().getint(
|
||||
'bitmessagesettings', 'defaultnoncetrialsperbyte')
|
||||
if nonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
|
||||
nonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||
if nonceTrialsPerByte < \
|
||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
|
||||
nonceTrialsPerByte = \
|
||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||
if payloadLengthExtraBytes == 0:
|
||||
payloadLengthExtraBytes = BMConfigParser().getint(
|
||||
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
|
||||
if payloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes:
|
||||
payloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
|
||||
if payloadLengthExtraBytes < \
|
||||
defaults.networkDefaultPayloadLengthExtraBytes:
|
||||
payloadLengthExtraBytes = \
|
||||
defaults.networkDefaultPayloadLengthExtraBytes
|
||||
if command == 'createRandomAddress':
|
||||
queues.UISignalQueue.put((
|
||||
'updateStatusBar', tr._translate("MainWindow", "Generating one new address")))
|
||||
# This next section is a little bit strange. We're going to generate keys over and over until we
|
||||
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
|
||||
# we won't store the \x00 or \x00\x00 bytes thus making the
|
||||
# address shorter.
|
||||
'updateStatusBar',
|
||||
tr._translate(
|
||||
"MainWindow", "Generating one new address")
|
||||
))
|
||||
# This next section is a little bit strange. We're going
|
||||
# to generate keys over and over until we find one
|
||||
# that starts with either \x00 or \x00\x00. Then when
|
||||
# we pack them into a Bitmessage address, we won't store
|
||||
# the \x00 or \x00\x00 bytes thus making the address shorter.
|
||||
startTime = time.time()
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
||||
potentialPrivSigningKey = OpenSSL.rand(32)
|
||||
potentialPubSigningKey = highlevelcrypto.pointMult(potentialPrivSigningKey)
|
||||
potentialPubSigningKey = highlevelcrypto.pointMult(
|
||||
potentialPrivSigningKey)
|
||||
while True:
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
||||
potentialPrivEncryptionKey = OpenSSL.rand(32)
|
||||
|
@ -110,15 +140,26 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
ripe.update(sha.digest())
|
||||
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
||||
break
|
||||
logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest()))
|
||||
logger.info(
|
||||
'Generated address with ripe digest: %s',
|
||||
hexlify(ripe.digest()))
|
||||
try:
|
||||
logger.info('Address generator calculated %s addresses at %s addresses per second before finding one with the correct ripe-prefix.' % (numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime)))
|
||||
logger.info(
|
||||
'Address generator calculated %s addresses at %s'
|
||||
' addresses per second before finding one with'
|
||||
' the correct ripe-prefix.',
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix,
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix
|
||||
/ (time.time() - startTime))
|
||||
except ZeroDivisionError:
|
||||
# The user must have a pretty fast computer. time.time() - startTime equaled zero.
|
||||
# The user must have a pretty fast computer.
|
||||
# time.time() - startTime equaled zero.
|
||||
pass
|
||||
address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
|
||||
address = encodeAddress(
|
||||
addressVersionNumber, streamNumber, ripe.digest())
|
||||
|
||||
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
|
||||
# An excellent way for us to store our keys
|
||||
# is in Wallet Import Format. Let us convert now.
|
||||
# https://en.bitcoin.it/wiki/Wallet_import_format
|
||||
privSigningKey = '\x80' + potentialPrivSigningKey
|
||||
checksum = hashlib.sha256(hashlib.sha256(
|
||||
|
@ -141,9 +182,9 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
|
||||
payloadLengthExtraBytes))
|
||||
BMConfigParser().set(
|
||||
address, 'privSigningKey', privSigningKeyWIF)
|
||||
address, 'privsigningkey', privSigningKeyWIF)
|
||||
BMConfigParser().set(
|
||||
address, 'privEncryptionKey', privEncryptionKeyWIF)
|
||||
address, 'privencryptionkey', privEncryptionKeyWIF)
|
||||
BMConfigParser().save()
|
||||
|
||||
# The API and the join and create Chan functionality
|
||||
|
@ -151,7 +192,12 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
queues.apiAddressGeneratorReturnQueue.put(address)
|
||||
|
||||
queues.UISignalQueue.put((
|
||||
'updateStatusBar', tr._translate("MainWindow", "Done generating address. Doing work necessary to broadcast it...")))
|
||||
'updateStatusBar',
|
||||
tr._translate(
|
||||
"MainWindow",
|
||||
"Done generating address. Doing work necessary"
|
||||
" to broadcast it...")
|
||||
))
|
||||
queues.UISignalQueue.put(('writeNewAddressToTable', (
|
||||
label, address, streamNumber)))
|
||||
shared.reloadMyAddressHashes()
|
||||
|
@ -162,31 +208,47 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
queues.workerQueue.put((
|
||||
'sendOutOrStoreMyV4Pubkey', address))
|
||||
|
||||
elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress' or command == 'createChan' or command == 'joinChan':
|
||||
elif command == 'createDeterministicAddresses' \
|
||||
or command == 'getDeterministicAddress' \
|
||||
or command == 'createChan' or command == 'joinChan':
|
||||
if len(deterministicPassphrase) == 0:
|
||||
sys.stderr.write(
|
||||
'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.')
|
||||
logger.warning(
|
||||
'You are creating deterministic'
|
||||
' address(es) using a blank passphrase.'
|
||||
' Bitmessage will do it but it is rather stupid.')
|
||||
if command == 'createDeterministicAddresses':
|
||||
queues.UISignalQueue.put((
|
||||
'updateStatusBar', tr._translate("MainWindow","Generating %1 new addresses.").arg(str(numberOfAddressesToMake))))
|
||||
'updateStatusBar',
|
||||
tr._translate(
|
||||
"MainWindow",
|
||||
"Generating %1 new addresses."
|
||||
).arg(str(numberOfAddressesToMake))
|
||||
))
|
||||
signingKeyNonce = 0
|
||||
encryptionKeyNonce = 1
|
||||
listOfNewAddressesToSendOutThroughTheAPI = [
|
||||
] # We fill out this list no matter what although we only need it if we end up passing the info to the API.
|
||||
# We fill out this list no matter what although we only
|
||||
# need it if we end up passing the info to the API.
|
||||
listOfNewAddressesToSendOutThroughTheAPI = []
|
||||
|
||||
for i in range(numberOfAddressesToMake):
|
||||
# This next section is a little bit strange. We're going to generate keys over and over until we
|
||||
# find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them
|
||||
# into a Bitmessage address, we won't store the \x00 or
|
||||
# This next section is a little bit strange. We're
|
||||
# going to generate keys over and over until we find
|
||||
# one that has a RIPEMD hash that starts with either
|
||||
# \x00 or \x00\x00. Then when we pack them into a
|
||||
# Bitmessage address, we won't store the \x00 or
|
||||
# \x00\x00 bytes thus making the address shorter.
|
||||
startTime = time.time()
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
||||
while True:
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
||||
potentialPrivSigningKey = hashlib.sha512(
|
||||
deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32]
|
||||
deterministicPassphrase +
|
||||
encodeVarint(signingKeyNonce)
|
||||
).digest()[:32]
|
||||
potentialPrivEncryptionKey = hashlib.sha512(
|
||||
deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32]
|
||||
deterministicPassphrase +
|
||||
encodeVarint(encryptionKeyNonce)
|
||||
).digest()[:32]
|
||||
potentialPubSigningKey = highlevelcrypto.pointMult(
|
||||
potentialPrivSigningKey)
|
||||
potentialPubEncryptionKey = highlevelcrypto.pointMult(
|
||||
|
@ -201,26 +263,39 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
||||
break
|
||||
|
||||
|
||||
logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest()))
|
||||
logger.info(
|
||||
'Generated address with ripe digest: %s',
|
||||
hexlify(ripe.digest()))
|
||||
try:
|
||||
logger.info('Address generator calculated %s addresses at %s addresses per second before finding one with the correct ripe-prefix.' % (numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime)))
|
||||
logger.info(
|
||||
'Address generator calculated %s addresses'
|
||||
' at %s addresses per second before finding'
|
||||
' one with the correct ripe-prefix.',
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix,
|
||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix /
|
||||
(time.time() - startTime)
|
||||
)
|
||||
except ZeroDivisionError:
|
||||
# The user must have a pretty fast computer. time.time() - startTime equaled zero.
|
||||
# The user must have a pretty fast computer.
|
||||
# time.time() - startTime equaled zero.
|
||||
pass
|
||||
address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
|
||||
address = encodeAddress(
|
||||
addressVersionNumber, streamNumber, ripe.digest())
|
||||
|
||||
saveAddressToDisk = True
|
||||
# If we are joining an existing chan, let us check to make sure it matches the provided Bitmessage address
|
||||
# If we are joining an existing chan, let us check
|
||||
# to make sure it matches the provided Bitmessage address
|
||||
if command == 'joinChan':
|
||||
if address != chanAddress:
|
||||
listOfNewAddressesToSendOutThroughTheAPI.append('chan name does not match address')
|
||||
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||
'chan name does not match address')
|
||||
saveAddressToDisk = False
|
||||
if command == 'getDeterministicAddress':
|
||||
saveAddressToDisk = False
|
||||
|
||||
if saveAddressToDisk and live:
|
||||
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
|
||||
# An excellent way for us to store our keys is
|
||||
# in Wallet Import Format. Let us convert now.
|
||||
# https://en.bitcoin.it/wiki/Wallet_import_format
|
||||
privSigningKey = '\x80' + potentialPrivSigningKey
|
||||
checksum = hashlib.sha256(hashlib.sha256(
|
||||
|
@ -235,63 +310,90 @@ class addressGenerator(threading.Thread, StoppableThread):
|
|||
privEncryptionKeyWIF = arithmetic.changebase(
|
||||
privEncryptionKey + checksum, 256, 58)
|
||||
|
||||
|
||||
try:
|
||||
BMConfigParser().add_section(address)
|
||||
addressAlreadyExists = False
|
||||
except:
|
||||
addressAlreadyExists = True
|
||||
|
||||
|
||||
if addressAlreadyExists:
|
||||
logger.info('%s already exists. Not adding it again.' % address)
|
||||
logger.info(
|
||||
'%s already exists. Not adding it again.',
|
||||
address
|
||||
)
|
||||
queues.UISignalQueue.put((
|
||||
'updateStatusBar', tr._translate("MainWindow","%1 is already in 'Your Identities'. Not adding it again.").arg(address)))
|
||||
'updateStatusBar',
|
||||
tr._translate(
|
||||
"MainWindow",
|
||||
"%1 is already in 'Your Identities'."
|
||||
" Not adding it again."
|
||||
).arg(address)
|
||||
))
|
||||
else:
|
||||
logger.debug('label: %s' % label)
|
||||
logger.debug('label: %s', label)
|
||||
BMConfigParser().set(address, 'label', label)
|
||||
BMConfigParser().set(address, 'enabled', 'true')
|
||||
BMConfigParser().set(address, 'decoy', 'false')
|
||||
if command == 'joinChan' or command == 'createChan':
|
||||
if command == 'joinChan' \
|
||||
or command == 'createChan':
|
||||
BMConfigParser().set(address, 'chan', 'true')
|
||||
BMConfigParser().set(address, 'noncetrialsperbyte', str(
|
||||
nonceTrialsPerByte))
|
||||
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
|
||||
payloadLengthExtraBytes))
|
||||
BMConfigParser().set(
|
||||
address, 'privSigningKey', privSigningKeyWIF)
|
||||
address, 'noncetrialsperbyte',
|
||||
str(nonceTrialsPerByte))
|
||||
BMConfigParser().set(
|
||||
address, 'privEncryptionKey', privEncryptionKeyWIF)
|
||||
address, 'payloadlengthextrabytes',
|
||||
str(payloadLengthExtraBytes))
|
||||
BMConfigParser().set(
|
||||
address, 'privSigningKey',
|
||||
privSigningKeyWIF)
|
||||
BMConfigParser().set(
|
||||
address, 'privEncryptionKey',
|
||||
privEncryptionKeyWIF)
|
||||
BMConfigParser().save()
|
||||
|
||||
queues.UISignalQueue.put(('writeNewAddressToTable', (
|
||||
label, address, str(streamNumber))))
|
||||
queues.UISignalQueue.put((
|
||||
'writeNewAddressToTable',
|
||||
(label, address, str(streamNumber))
|
||||
))
|
||||
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||
address)
|
||||
shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor(
|
||||
shared.myECCryptorObjects[ripe.digest()] = \
|
||||
highlevelcrypto.makeCryptor(
|
||||
hexlify(potentialPrivEncryptionKey))
|
||||
shared.myAddressesByHash[ripe.digest()] = address
|
||||
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
||||
addressVersionNumber) + encodeVarint(streamNumber) + ripe.digest()).digest()).digest()[32:]
|
||||
tag = hashlib.sha512(hashlib.sha512(
|
||||
encodeVarint(addressVersionNumber) +
|
||||
encodeVarint(streamNumber) + ripe.digest()
|
||||
).digest()).digest()[32:]
|
||||
shared.myAddressesByTag[tag] = address
|
||||
if addressVersionNumber == 3:
|
||||
# If this is a chan address,
|
||||
# the worker thread won't send out
|
||||
# the pubkey over the network.
|
||||
queues.workerQueue.put((
|
||||
'sendOutOrStoreMyV3Pubkey', ripe.digest())) # If this is a chan address,
|
||||
# the worker thread won't send out the pubkey over the network.
|
||||
'sendOutOrStoreMyV3Pubkey', ripe.digest()))
|
||||
elif addressVersionNumber == 4:
|
||||
queues.workerQueue.put((
|
||||
'sendOutOrStoreMyV4Pubkey', address))
|
||||
queues.UISignalQueue.put((
|
||||
'updateStatusBar', tr._translate("MainWindow", "Done generating address")))
|
||||
elif saveAddressToDisk and not live and not BMConfigParser().has_section(address):
|
||||
listOfNewAddressesToSendOutThroughTheAPI.append(address)
|
||||
'updateStatusBar',
|
||||
tr._translate(
|
||||
"MainWindow", "Done generating address")
|
||||
))
|
||||
elif saveAddressToDisk and not live \
|
||||
and not BMConfigParser().has_section(address):
|
||||
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||
address)
|
||||
|
||||
# Done generating addresses.
|
||||
if command == 'createDeterministicAddresses' or command == 'joinChan' or command == 'createChan':
|
||||
if command == 'createDeterministicAddresses' \
|
||||
or command == 'joinChan' or command == 'createChan':
|
||||
queues.apiAddressGeneratorReturnQueue.put(
|
||||
listOfNewAddressesToSendOutThroughTheAPI)
|
||||
elif command == 'getDeterministicAddress':
|
||||
queues.apiAddressGeneratorReturnQueue.put(address)
|
||||
else:
|
||||
raise Exception(
|
||||
"Error in the addressGenerator thread. Thread was given a command it could not understand: " + command)
|
||||
"Error in the addressGenerator thread. Thread was" +
|
||||
" given a command it could not understand: " + command)
|
||||
queues.addressGeneratorQueue.task_done()
|
||||
|
|
|
@ -1,42 +1,48 @@
|
|||
from __future__ import division
|
||||
|
||||
import threading
|
||||
import shared
|
||||
import time
|
||||
from time import strftime, localtime, gmtime
|
||||
import random
|
||||
from subprocess import call # used when the API must execute an outside program
|
||||
from addresses import *
|
||||
import highlevelcrypto
|
||||
import proofofwork
|
||||
import sys
|
||||
import threading
|
||||
import hashlib
|
||||
from struct import pack
|
||||
# used when the API must execute an outside program
|
||||
from subprocess import call
|
||||
from binascii import hexlify, unhexlify
|
||||
|
||||
import tr
|
||||
from bmconfigparser import BMConfigParser
|
||||
from debug import logger
|
||||
import defaults
|
||||
from helper_sql import *
|
||||
import helper_inbox
|
||||
from helper_generic import addDataPadding
|
||||
import helper_msgcoding
|
||||
from helper_threading import *
|
||||
from inventory import Inventory
|
||||
import l10n
|
||||
import protocol
|
||||
import queues
|
||||
import state
|
||||
from binascii import hexlify, unhexlify
|
||||
import shared
|
||||
import defaults
|
||||
import highlevelcrypto
|
||||
import proofofwork
|
||||
import helper_inbox
|
||||
import helper_random
|
||||
import helper_msgcoding
|
||||
from bmconfigparser import BMConfigParser
|
||||
from debug import logger
|
||||
from inventory import Inventory
|
||||
from addresses import (
|
||||
decodeAddress, encodeVarint, decodeVarint, calculateInventoryHash
|
||||
)
|
||||
# from helper_generic import addDataPadding
|
||||
from helper_threading import StoppableThread
|
||||
from helper_sql import sqlQuery, sqlExecute
|
||||
|
||||
|
||||
# This thread, of which there is only one, does the heavy lifting:
|
||||
# calculating POWs.
|
||||
|
||||
|
||||
def sizeof_fmt(num, suffix='h/s'):
|
||||
for unit in ['','k','M','G','T','P','E','Z']:
|
||||
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
|
||||
if abs(num) < 1000.0:
|
||||
return "%3.1f%s%s" % (num, unit, suffix)
|
||||
num /= 1024.0
|
||||
return "%.1f%s%s" % (num, 'Yi', suffix)
|
||||
|
||||
|
||||
class singleWorker(threading.Thread, StoppableThread):
|
||||
|
||||
def __init__(self):
|
||||
|
@ -58,21 +64,32 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
self.stop.wait(2)
|
||||
if state.shutdown > 0:
|
||||
return
|
||||
|
||||
|
||||
# Initialize the neededPubkeys dictionary.
|
||||
queryreturn = sqlQuery(
|
||||
'''SELECT DISTINCT toaddress FROM sent WHERE (status='awaitingpubkey' AND folder='sent')''')
|
||||
'''SELECT DISTINCT toaddress FROM sent'''
|
||||
''' WHERE (status='awaitingpubkey' AND folder='sent')''')
|
||||
for row in queryreturn:
|
||||
toAddress, = row
|
||||
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = decodeAddress(toAddress)
|
||||
if toAddressVersionNumber <= 3 :
|
||||
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = \
|
||||
decodeAddress(toAddress)
|
||||
if toAddressVersionNumber <= 3:
|
||||
state.neededPubkeys[toAddress] = 0
|
||||
elif toAddressVersionNumber >= 4:
|
||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
||||
toAddressVersionNumber) + encodeVarint(toStreamNumber) + toRipe).digest()).digest()
|
||||
privEncryptionKey = doubleHashOfAddressData[:32] # Note that this is the first half of the sha512 hash.
|
||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||
encodeVarint(toAddressVersionNumber) +
|
||||
encodeVarint(toStreamNumber) + toRipe
|
||||
).digest()).digest()
|
||||
# Note that this is the first half of the sha512 hash.
|
||||
privEncryptionKey = doubleHashOfAddressData[:32]
|
||||
tag = doubleHashOfAddressData[32:]
|
||||
state.neededPubkeys[tag] = (toAddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))) # We'll need this for when we receive a pubkey reply: it will be encrypted and we'll need to decrypt it.
|
||||
# We'll need this for when we receive a pubkey reply:
|
||||
# it will be encrypted and we'll need to decrypt it.
|
||||
state.neededPubkeys[tag] = (
|
||||
toAddress,
|
||||
highlevelcrypto.makeCryptor(
|
||||
hexlify(privEncryptionKey))
|
||||
)
|
||||
|
||||
# Initialize the shared.ackdataForWhichImWatching data structure
|
||||
queryreturn = sqlQuery(
|
||||
|
@ -84,16 +101,19 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
|
||||
# Fix legacy (headerless) watched ackdata to include header
|
||||
for oldack in shared.ackdataForWhichImWatching.keys():
|
||||
if (len(oldack)==32):
|
||||
if (len(oldack) == 32):
|
||||
# attach legacy header, always constant (msg/1/1)
|
||||
newack = '\x00\x00\x00\x02\x01\x01' + oldack
|
||||
shared.ackdataForWhichImWatching[newack] = 0
|
||||
sqlExecute('UPDATE sent SET ackdata=? WHERE ackdata=?',
|
||||
newack, oldack )
|
||||
sqlExecute(
|
||||
'UPDATE sent SET ackdata=? WHERE ackdata=?',
|
||||
newack, oldack
|
||||
)
|
||||
del shared.ackdataForWhichImWatching[oldack]
|
||||
|
||||
self.stop.wait(
|
||||
10) # give some time for the GUI to start before we start on existing POW tasks.
|
||||
# give some time for the GUI to start
|
||||
# before we start on existing POW tasks.
|
||||
self.stop.wait(10)
|
||||
|
||||
if state.shutdown == 0:
|
||||
# just in case there are any pending tasks for msg
|
||||
|
@ -141,17 +161,25 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
self.busy = 0
|
||||
return
|
||||
else:
|
||||
logger.error('Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command)
|
||||
logger.error(
|
||||
'Probable programming error: The command sent'
|
||||
' to the workerThread is weird. It is: %s\n',
|
||||
command
|
||||
)
|
||||
|
||||
queues.workerQueue.task_done()
|
||||
logger.info("Quitting...")
|
||||
|
||||
def doPOWForMyV2Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW
|
||||
# This function also broadcasts out the pubkey message
|
||||
# once it is done with the POW
|
||||
def doPOWForMyV2Pubkey(self, hash):
|
||||
# Look up my stream number based on my address hash
|
||||
"""configSections = shared.config.addresses()
|
||||
for addressInKeysFile in configSections:
|
||||
if addressInKeysFile <> 'bitmessagesettings':
|
||||
status,addressVersionNumber,streamNumber,hashFromThisParticularAddress = decodeAddress(addressInKeysFile)
|
||||
if addressInKeysFile != 'bitmessagesettings':
|
||||
status, addressVersionNumber, streamNumber, \
|
||||
hashFromThisParticularAddress = \
|
||||
decodeAddress(addressInKeysFile)
|
||||
if hash == hashFromThisParticularAddress:
|
||||
myAddress = addressInKeysFile
|
||||
break"""
|
||||
|
@ -159,13 +187,15 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||
myAddress)
|
||||
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))# 28 days from now plus or minus five minutes
|
||||
# 28 days from now plus or minus five minutes
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
|
||||
embeddedTime = int(time.time() + TTL)
|
||||
payload = pack('>Q', (embeddedTime))
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += encodeVarint(addressVersionNumber) # Address version number
|
||||
payload += encodeVarint(streamNumber)
|
||||
payload += protocol.getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
|
||||
# bitfield of features supported by me (see the wiki).
|
||||
payload += protocol.getBitfield(myAddress)
|
||||
|
||||
try:
|
||||
privSigningKeyBase58 = BMConfigParser().get(
|
||||
|
@ -173,7 +203,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||
myAddress, 'privencryptionkey')
|
||||
except Exception as err:
|
||||
logger.error('Error within doPOWForMyV2Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
|
||||
logger.error(
|
||||
'Error within doPOWForMyV2Pubkey. Could not read'
|
||||
' the keys from the keys.dat file for a requested'
|
||||
' address. %s\n' % err
|
||||
)
|
||||
return
|
||||
|
||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||
|
@ -189,19 +223,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
payload += pubEncryptionKey[1:]
|
||||
|
||||
# Do the POW for this pubkey message
|
||||
target = 2 ** 64 / (defaults.networkDefaultProofOfWorkNonceTrialsPerByte*(len(payload) + 8 + defaults.networkDefaultPayloadLengthExtraBytes + ((TTL*(len(payload)+8+defaults.networkDefaultPayloadLengthExtraBytes))/(2 ** 16))))
|
||||
target = 2 ** 64 / (
|
||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes + ((
|
||||
TTL * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes
|
||||
)) / (2 ** 16))
|
||||
))
|
||||
logger.info('(For pubkey message) Doing proof of work...')
|
||||
initialHash = hashlib.sha512(payload).digest()
|
||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||
logger.info('(For pubkey message) Found proof of work ' + str(trialValue), ' Nonce: ', str(nonce))
|
||||
logger.info(
|
||||
'(For pubkey message) Found proof of work %s Nonce: %s',
|
||||
trialValue, nonce
|
||||
)
|
||||
payload = pack('>Q', nonce) + payload
|
||||
|
||||
inventoryHash = calculateInventoryHash(payload)
|
||||
objectType = 1
|
||||
Inventory()[inventoryHash] = (
|
||||
objectType, streamNumber, payload, embeddedTime,'')
|
||||
objectType, streamNumber, payload, embeddedTime, '')
|
||||
|
||||
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
||||
logger.info('broadcasting inv with hash: %s', hexlify(inventoryHash))
|
||||
|
||||
queues.invQueue.put((streamNumber, inventoryHash))
|
||||
queues.UISignalQueue.put(('updateStatusBar', ''))
|
||||
|
@ -210,19 +255,19 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
||||
BMConfigParser().save()
|
||||
except:
|
||||
# The user deleted the address out of the keys.dat file before this
|
||||
# finished.
|
||||
# The user deleted the address out of the keys.dat file
|
||||
# before this finished.
|
||||
pass
|
||||
|
||||
# If this isn't a chan address, this function assembles the pubkey data,
|
||||
# does the necessary POW and sends it out. If it *is* a chan then it
|
||||
# assembles the pubkey and stores is in the pubkey table so that we can
|
||||
# send messages to "ourselves".
|
||||
def sendOutOrStoreMyV3Pubkey(self, hash):
|
||||
def sendOutOrStoreMyV3Pubkey(self, hash):
|
||||
try:
|
||||
myAddress = shared.myAddressesByHash[hash]
|
||||
except:
|
||||
#The address has been deleted.
|
||||
# The address has been deleted.
|
||||
return
|
||||
if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
||||
logger.info('This is a chan address. Not sending pubkey.')
|
||||
|
@ -230,22 +275,25 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||
myAddress)
|
||||
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
|
||||
# 28 days from now plus or minus five minutes
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
|
||||
embeddedTime = int(time.time() + TTL)
|
||||
signedTimeForProtocolV2 = embeddedTime - TTL
|
||||
# signedTimeForProtocolV2 = embeddedTime - TTL
|
||||
"""
|
||||
According to the protocol specification, the expiresTime along with the pubkey information is
|
||||
signed. But to be backwards compatible during the upgrade period, we shall sign not the
|
||||
expiresTime but rather the current time. There must be precisely a 28 day difference
|
||||
between the two. After the upgrade period we'll switch to signing the whole payload with the
|
||||
According to the protocol specification, the expiresTime
|
||||
along with the pubkey information is signed. But to be
|
||||
backwards compatible during the upgrade period, we shall sign
|
||||
not the expiresTime but rather the current time. There must be
|
||||
precisely a 28 day difference between the two. After the upgrade
|
||||
period we'll switch to signing the whole payload with the
|
||||
expiresTime time.
|
||||
"""
|
||||
payload = pack('>Q', (embeddedTime))
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += encodeVarint(addressVersionNumber) # Address version number
|
||||
payload += encodeVarint(streamNumber)
|
||||
payload += protocol.getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
|
||||
# bitfield of features supported by me (see the wiki).
|
||||
payload += protocol.getBitfield(myAddress)
|
||||
|
||||
try:
|
||||
privSigningKeyBase58 = BMConfigParser().get(
|
||||
|
@ -253,8 +301,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||
myAddress, 'privencryptionkey')
|
||||
except Exception as err:
|
||||
logger.error('Error within sendOutOrStoreMyV3Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
|
||||
|
||||
logger.error(
|
||||
'Error within sendOutOrStoreMyV3Pubkey. Could not read'
|
||||
' the keys from the keys.dat file for a requested'
|
||||
' address. %s\n' % err
|
||||
)
|
||||
return
|
||||
|
||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||
|
@ -273,23 +324,34 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
myAddress, 'noncetrialsperbyte'))
|
||||
payload += encodeVarint(BMConfigParser().getint(
|
||||
myAddress, 'payloadlengthextrabytes'))
|
||||
|
||||
|
||||
signature = highlevelcrypto.sign(payload, privSigningKeyHex)
|
||||
payload += encodeVarint(len(signature))
|
||||
payload += signature
|
||||
|
||||
# Do the POW for this pubkey message
|
||||
target = 2 ** 64 / (defaults.networkDefaultProofOfWorkNonceTrialsPerByte*(len(payload) + 8 + defaults.networkDefaultPayloadLengthExtraBytes + ((TTL*(len(payload)+8+defaults.networkDefaultPayloadLengthExtraBytes))/(2 ** 16))))
|
||||
target = 2 ** 64 / (
|
||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes + ((
|
||||
TTL * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes
|
||||
)) / (2 ** 16))
|
||||
))
|
||||
logger.info('(For pubkey message) Doing proof of work...')
|
||||
initialHash = hashlib.sha512(payload).digest()
|
||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||
logger.info('(For pubkey message) Found proof of work. Nonce: ' + str(nonce))
|
||||
logger.info(
|
||||
'(For pubkey message) Found proof of work. Nonce: %s',
|
||||
str(nonce)
|
||||
)
|
||||
|
||||
payload = pack('>Q', nonce) + payload
|
||||
inventoryHash = calculateInventoryHash(payload)
|
||||
objectType = 1
|
||||
Inventory()[inventoryHash] = (
|
||||
objectType, streamNumber, payload, embeddedTime,'')
|
||||
objectType, streamNumber, payload, embeddedTime, '')
|
||||
|
||||
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
||||
|
||||
|
@ -304,23 +366,23 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
# finished.
|
||||
pass
|
||||
|
||||
# If this isn't a chan address, this function assembles the pubkey data,
|
||||
# does the necessary POW and sends it out.
|
||||
# If this isn't a chan address, this function assembles
|
||||
# the pubkey data, does the necessary POW and sends it out.
|
||||
def sendOutOrStoreMyV4Pubkey(self, myAddress):
|
||||
if not BMConfigParser().has_section(myAddress):
|
||||
#The address has been deleted.
|
||||
# The address has been deleted.
|
||||
return
|
||||
if shared.BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
||||
logger.info('This is a chan address. Not sending pubkey.')
|
||||
return
|
||||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||
myAddress)
|
||||
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
|
||||
|
||||
# 28 days from now plus or minus five minutes
|
||||
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
|
||||
embeddedTime = int(time.time() + TTL)
|
||||
payload = pack('>Q', (embeddedTime))
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += '\x00\x00\x00\x01' # object type: pubkey
|
||||
payload += encodeVarint(addressVersionNumber) # Address version number
|
||||
payload += encodeVarint(streamNumber)
|
||||
dataToEncrypt = protocol.getBitfield(myAddress)
|
||||
|
@ -331,7 +393,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||
myAddress, 'privencryptionkey')
|
||||
except Exception as err:
|
||||
logger.error('Error within sendOutOrStoreMyV4Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
|
||||
logger.error(
|
||||
'Error within sendOutOrStoreMyV4Pubkey. Could not read'
|
||||
' the keys from the keys.dat file for a requested'
|
||||
' address. %s\n' % err
|
||||
)
|
||||
return
|
||||
|
||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||
|
@ -349,37 +415,55 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
myAddress, 'noncetrialsperbyte'))
|
||||
dataToEncrypt += encodeVarint(BMConfigParser().getint(
|
||||
myAddress, 'payloadlengthextrabytes'))
|
||||
|
||||
|
||||
# When we encrypt, we'll use a hash of the data
|
||||
# contained in an address as a decryption key. This way in order to
|
||||
# read the public keys in a pubkey message, a node must know the address
|
||||
# first. We'll also tag, unencrypted, the pubkey with part of the hash
|
||||
# so that nodes know which pubkey object to try to decrypt when they
|
||||
# want to send a message.
|
||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
||||
addressVersionNumber) + encodeVarint(streamNumber) + hash).digest()).digest()
|
||||
payload += doubleHashOfAddressData[32:] # the tag
|
||||
signature = highlevelcrypto.sign(payload + dataToEncrypt, privSigningKeyHex)
|
||||
# contained in an address as a decryption key. This way
|
||||
# in order to read the public keys in a pubkey message,
|
||||
# a node must know the address first. We'll also tag,
|
||||
# unencrypted, the pubkey with part of the hash so that nodes
|
||||
# know which pubkey object to try to decrypt
|
||||
# when they want to send a message.
|
||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||
encodeVarint(addressVersionNumber) +
|
||||
encodeVarint(streamNumber) + hash
|
||||
).digest()).digest()
|
||||
payload += doubleHashOfAddressData[32:] # the tag
|
||||
signature = highlevelcrypto.sign(
|
||||
payload + dataToEncrypt, privSigningKeyHex
|
||||
)
|
||||
dataToEncrypt += encodeVarint(len(signature))
|
||||
dataToEncrypt += signature
|
||||
|
||||
|
||||
privEncryptionKey = doubleHashOfAddressData[:32]
|
||||
pubEncryptionKey = highlevelcrypto.pointMult(privEncryptionKey)
|
||||
payload += highlevelcrypto.encrypt(
|
||||
dataToEncrypt, hexlify(pubEncryptionKey))
|
||||
|
||||
# Do the POW for this pubkey message
|
||||
target = 2 ** 64 / (defaults.networkDefaultProofOfWorkNonceTrialsPerByte*(len(payload) + 8 + defaults.networkDefaultPayloadLengthExtraBytes + ((TTL*(len(payload)+8+defaults.networkDefaultPayloadLengthExtraBytes))/(2 ** 16))))
|
||||
target = 2 ** 64 / (
|
||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes + ((
|
||||
TTL * (
|
||||
len(payload) + 8 +
|
||||
defaults.networkDefaultPayloadLengthExtraBytes
|
||||
)) / (2 ** 16))
|
||||
))
|
||||
logger.info('(For pubkey message) Doing proof of work...')
|
||||
initialHash = hashlib.sha512(payload).digest()
|
||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||
logger.info('(For pubkey message) Found proof of work ' + str(trialValue) + 'Nonce: ' + str(nonce))
|
||||
logger.info(
|
||||
'(For pubkey message) Found proof of work %s Nonce: %s',
|
||||
trialValue, nonce
|
||||
)
|
||||
|
||||
payload = pack('>Q', nonce) + payload
|
||||
inventoryHash = calculateInventoryHash(payload)
|
||||
objectType = 1
|
||||
Inventory()[inventoryHash] = (
|
||||
objectType, streamNumber, payload, embeddedTime, doubleHashOfAddressData[32:])
|
||||
objectType, streamNumber, payload, embeddedTime,
|
||||
doubleHashOfAddressData[32:]
|
||||
)
|
||||
|
||||
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
||||
|
||||
|
@ -390,21 +474,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
|||
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
||||
BMConfigParser().save()
|
||||
except Exception as err:
|
||||
logger.error('Error: Couldn\'t add the lastpubkeysendtime to the keys.dat file. Error message: %s' % err)
|
||||
logger.error(
|
||||
'Error: Couldn\'t add the lastpubkeysendtime'
|
||||
' to the keys.dat file. Error message: %s' % err
|
||||
)
|
||||
|
||||
def sendBroadcast(self):
|
||||
# Reset just in case
|
||||
sqlExecute(
|
||||
'''UPDATE sent SET status='broadcastqueued' WHERE status = 'doingbroadcastpow' ''')
|
||||
'''UPDATE sent SET status='broadcastqueued' '''
|
||||
'''WHERE status = 'doingbroadcastpow' ''')
|
||||
queryreturn = sqlQuery(
|
||||
'''SELECT fromaddress, subject, message, ackdata, ttl, encodingtype FROM sent WHERE status=? and folder='sent' ''', 'broadcastqueued')
|
||||
'''SELECT fromaddress, subject, message, '''
|
||||
''' ackdata, ttl, encodingtype FROM sent '''
|
||||
''' WHERE status=? and folder='sent' ''', 'broadcastqueued')
|
||||
|
||||
for row in queryreturn:
|
||||
fromaddress, subject, body, ackdata, TTL, encoding = row
|
||||
status, addressVersionNumber, streamNumber, ripe = decodeAddress(
|
||||
fromaddress)
|
||||
status, addressVersionNumber, streamNumber, ripe = \
|
||||
decodeAddress(fromaddress)
|
||||
if addressVersionNumber <= 1:
|
||||
logger.error('Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n')
|
||||
logger.error(
|
||||
'Error: In the singleWorker thread, the '
|
||||
' sendBroadcast function doesn\'t understand'
|
||||
' the address version.\n')
|
||||
|