Address operations: flake8
This commit is contained in:
parent
cbb228db8b
commit
006b98389b
230
src/addresses.py
230
src/addresses.py
|
@ -1,11 +1,12 @@
|
||||||
import hashlib
|
import hashlib
|
||||||
from struct import *
|
from struct import pack, unpack
|
||||||
from pyelliptic import arithmetic
|
from pyelliptic import arithmetic
|
||||||
from binascii import hexlify, unhexlify
|
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):
|
def convertIntToString(n):
|
||||||
a = __builtins__.hex(n)
|
a = __builtins__.hex(n)
|
||||||
if a[-1:] == 'L':
|
if a[-1:] == 'L':
|
||||||
|
@ -17,6 +18,7 @@ def convertIntToString(n):
|
||||||
|
|
||||||
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||||
|
|
||||||
|
|
||||||
def encodeBase58(num, alphabet=ALPHABET):
|
def encodeBase58(num, alphabet=ALPHABET):
|
||||||
"""Encode a number in Base X
|
"""Encode a number in Base X
|
||||||
|
|
||||||
|
@ -29,12 +31,13 @@ def encodeBase58(num, alphabet=ALPHABET):
|
||||||
base = len(alphabet)
|
base = len(alphabet)
|
||||||
while num:
|
while num:
|
||||||
rem = num % base
|
rem = num % base
|
||||||
#print 'num is:', num
|
# print 'num is:', num
|
||||||
num = num // base
|
num = num // base
|
||||||
arr.append(alphabet[rem])
|
arr.append(alphabet[rem])
|
||||||
arr.reverse()
|
arr.reverse()
|
||||||
return ''.join(arr)
|
return ''.join(arr)
|
||||||
|
|
||||||
|
|
||||||
def decodeBase58(string, alphabet=ALPHABET):
|
def decodeBase58(string, alphabet=ALPHABET):
|
||||||
"""Decode a Base X encoded string into the number
|
"""Decode a Base X encoded string into the number
|
||||||
|
|
||||||
|
@ -50,29 +53,32 @@ def decodeBase58(string, alphabet=ALPHABET):
|
||||||
num *= base
|
num *= base
|
||||||
num += alphabet.index(char)
|
num += alphabet.index(char)
|
||||||
except:
|
except:
|
||||||
#character not found (like a space character or a 0)
|
# character not found (like a space character or a 0)
|
||||||
return 0
|
return 0
|
||||||
return num
|
return num
|
||||||
|
|
||||||
|
|
||||||
def encodeVarint(integer):
|
def encodeVarint(integer):
|
||||||
if integer < 0:
|
if integer < 0:
|
||||||
logger.error('varint cannot be < 0')
|
logger.error('varint cannot be < 0')
|
||||||
raise SystemExit
|
raise SystemExit
|
||||||
if integer < 253:
|
if integer < 253:
|
||||||
return pack('>B',integer)
|
return pack('>B', integer)
|
||||||
if integer >= 253 and integer < 65536:
|
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:
|
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:
|
if integer >= 4294967296 and integer < 18446744073709551616:
|
||||||
return pack('>B',255) + pack('>Q',integer)
|
return pack('>B', 255) + pack('>Q', integer)
|
||||||
if integer >= 18446744073709551616:
|
if integer >= 18446744073709551616:
|
||||||
logger.error('varint cannot be >= 18446744073709551616')
|
logger.error('varint cannot be >= 18446744073709551616')
|
||||||
raise SystemExit
|
raise SystemExit
|
||||||
|
|
||||||
|
|
||||||
class varintDecodeError(Exception):
|
class varintDecodeError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def decodeVarint(data):
|
def decodeVarint(data):
|
||||||
"""
|
"""
|
||||||
Decodes an encoded varint to an integer and returns it.
|
Decodes an encoded varint to an integer and returns it.
|
||||||
|
@ -82,35 +88,50 @@ def decodeVarint(data):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
return (0,0)
|
return (0, 0)
|
||||||
firstByte, = unpack('>B',data[0:1])
|
firstByte, = unpack('>B', data[0:1])
|
||||||
if firstByte < 253:
|
if firstByte < 253:
|
||||||
# encodes 0 to 252
|
# 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:
|
if firstByte == 253:
|
||||||
# encodes 253 to 65535
|
# encodes 253 to 65535
|
||||||
if len(data) < 3:
|
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)))
|
raise varintDecodeError(
|
||||||
encodedValue, = unpack('>H',data[1:3])
|
'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:
|
if encodedValue < 253:
|
||||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
raise varintDecodeError(
|
||||||
return (encodedValue,3)
|
'This varint does not encode the value with the lowest'
|
||||||
|
' possible number of bytes.')
|
||||||
|
return (encodedValue, 3)
|
||||||
if firstByte == 254:
|
if firstByte == 254:
|
||||||
# encodes 65536 to 4294967295
|
# encodes 65536 to 4294967295
|
||||||
if len(data) < 5:
|
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)))
|
raise varintDecodeError(
|
||||||
encodedValue, = unpack('>I',data[1:5])
|
'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:
|
if encodedValue < 65536:
|
||||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
raise varintDecodeError(
|
||||||
return (encodedValue,5)
|
'This varint does not encode the value with the lowest'
|
||||||
|
' possible number of bytes.')
|
||||||
|
return (encodedValue, 5)
|
||||||
if firstByte == 255:
|
if firstByte == 255:
|
||||||
# encodes 4294967296 to 18446744073709551615
|
# encodes 4294967296 to 18446744073709551615
|
||||||
if len(data) < 9:
|
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)))
|
raise varintDecodeError(
|
||||||
encodedValue, = unpack('>Q',data[1:9])
|
'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:
|
if encodedValue < 4294967296:
|
||||||
raise varintDecodeError('This varint does not encode the value with the lowest possible number of bytes.')
|
raise varintDecodeError(
|
||||||
return (encodedValue,9)
|
'This varint does not encode the value with the lowest'
|
||||||
|
' possible number of bytes.')
|
||||||
|
return (encodedValue, 9)
|
||||||
|
|
||||||
|
|
||||||
def calculateInventoryHash(data):
|
def calculateInventoryHash(data):
|
||||||
|
@ -120,17 +141,23 @@ def calculateInventoryHash(data):
|
||||||
sha2.update(sha.digest())
|
sha2.update(sha.digest())
|
||||||
return sha2.digest()[0:32]
|
return sha2.digest()[0:32]
|
||||||
|
|
||||||
def encodeAddress(version,stream,ripe):
|
|
||||||
|
def encodeAddress(version, stream, ripe):
|
||||||
if version >= 2 and version < 4:
|
if version >= 2 and version < 4:
|
||||||
if len(ripe) != 20:
|
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':
|
if ripe[:2] == '\x00\x00':
|
||||||
ripe = ripe[2:]
|
ripe = ripe[2:]
|
||||||
elif ripe[:1] == '\x00':
|
elif ripe[:1] == '\x00':
|
||||||
ripe = ripe[1:]
|
ripe = ripe[1:]
|
||||||
elif version == 4:
|
elif version == 4:
|
||||||
if len(ripe) != 20:
|
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')
|
ripe = ripe.lstrip('\x00')
|
||||||
|
|
||||||
storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe
|
storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe
|
||||||
|
@ -143,11 +170,13 @@ def encodeAddress(version,stream,ripe):
|
||||||
sha.update(currentHash)
|
sha.update(currentHash)
|
||||||
checksum = sha.digest()[0:4]
|
checksum = sha.digest()[0:4]
|
||||||
|
|
||||||
asInt = int(hexlify(storedBinaryData) + hexlify(checksum),16)
|
asInt = int(hexlify(storedBinaryData) + hexlify(checksum), 16)
|
||||||
return 'BM-'+ encodeBase58(asInt)
|
return 'BM-' + encodeBase58(asInt)
|
||||||
|
|
||||||
|
|
||||||
def decodeAddress(address):
|
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()
|
address = str(address).strip()
|
||||||
|
|
||||||
|
@ -157,14 +186,15 @@ def decodeAddress(address):
|
||||||
integer = decodeBase58(address)
|
integer = decodeBase58(address)
|
||||||
if integer == 0:
|
if integer == 0:
|
||||||
status = 'invalidcharacters'
|
status = 'invalidcharacters'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
#after converting to hex, the string will be prepended with a 0x and appended with a L
|
# after converting to hex, the string will be prepended
|
||||||
|
# with a 0x and appended with a L
|
||||||
hexdata = hex(integer)[2:-1]
|
hexdata = hex(integer)[2:-1]
|
||||||
|
|
||||||
if len(hexdata) % 2 != 0:
|
if len(hexdata) % 2 != 0:
|
||||||
hexdata = '0' + hexdata
|
hexdata = '0' + hexdata
|
||||||
|
|
||||||
#print 'hexdata', hexdata
|
# print 'hexdata', hexdata
|
||||||
|
|
||||||
data = unhexlify(hexdata)
|
data = unhexlify(hexdata)
|
||||||
checksum = data[-4:]
|
checksum = data[-4:]
|
||||||
|
@ -172,15 +202,15 @@ def decodeAddress(address):
|
||||||
sha = hashlib.new('sha512')
|
sha = hashlib.new('sha512')
|
||||||
sha.update(data[:-4])
|
sha.update(data[:-4])
|
||||||
currentHash = sha.digest()
|
currentHash = sha.digest()
|
||||||
#print 'sha after first hashing: ', sha.hexdigest()
|
# print 'sha after first hashing: ', sha.hexdigest()
|
||||||
sha = hashlib.new('sha512')
|
sha = hashlib.new('sha512')
|
||||||
sha.update(currentHash)
|
sha.update(currentHash)
|
||||||
#print 'sha after second hashing: ', sha.hexdigest()
|
# print 'sha after second hashing: ', sha.hexdigest()
|
||||||
|
|
||||||
if checksum != sha.digest()[0:4]:
|
if checksum != sha.digest()[0:4]:
|
||||||
status = 'checksumfailed'
|
status = 'checksumfailed'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
#else:
|
# else:
|
||||||
# print 'checksum PASSED'
|
# print 'checksum PASSED'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -188,55 +218,64 @@ def decodeAddress(address):
|
||||||
except varintDecodeError as e:
|
except varintDecodeError as e:
|
||||||
logger.error(str(e))
|
logger.error(str(e))
|
||||||
status = 'varintmalformed'
|
status = 'varintmalformed'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
#print 'addressVersionNumber', addressVersionNumber
|
# print 'addressVersionNumber', addressVersionNumber
|
||||||
#print 'bytesUsedByVersionNumber', bytesUsedByVersionNumber
|
# print 'bytesUsedByVersionNumber', bytesUsedByVersionNumber
|
||||||
|
|
||||||
if addressVersionNumber > 4:
|
if addressVersionNumber > 4:
|
||||||
logger.error('cannot decode address version numbers this high')
|
logger.error('cannot decode address version numbers this high')
|
||||||
status = 'versiontoohigh'
|
status = 'versiontoohigh'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
elif addressVersionNumber == 0:
|
elif addressVersionNumber == 0:
|
||||||
logger.error('cannot decode address version numbers of zero.')
|
logger.error('cannot decode address version numbers of zero.')
|
||||||
status = 'versiontoohigh'
|
status = 'versiontoohigh'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
|
|
||||||
try:
|
try:
|
||||||
streamNumber, bytesUsedByStreamNumber = decodeVarint(data[bytesUsedByVersionNumber:])
|
streamNumber, bytesUsedByStreamNumber = \
|
||||||
|
decodeVarint(data[bytesUsedByVersionNumber:])
|
||||||
except varintDecodeError as e:
|
except varintDecodeError as e:
|
||||||
logger.error(str(e))
|
logger.error(str(e))
|
||||||
status = 'varintmalformed'
|
status = 'varintmalformed'
|
||||||
return status,0,0,""
|
return status, 0, 0, ''
|
||||||
#print streamNumber
|
# print streamNumber
|
||||||
status = 'success'
|
status = 'success'
|
||||||
if addressVersionNumber == 1:
|
if addressVersionNumber == 1:
|
||||||
return status,addressVersionNumber,streamNumber,data[-24:-4]
|
return status, addressVersionNumber, streamNumber, data[-24:-4]
|
||||||
elif addressVersionNumber == 2 or addressVersionNumber == 3:
|
elif addressVersionNumber == 2 or addressVersionNumber == 3:
|
||||||
embeddedRipeData = data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]
|
embeddedRipeData = \
|
||||||
|
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||||
if len(embeddedRipeData) == 19:
|
if len(embeddedRipeData) == 19:
|
||||||
return status,addressVersionNumber,streamNumber,'\x00'+embeddedRipeData
|
return status, addressVersionNumber, streamNumber, \
|
||||||
|
'\x00'+embeddedRipeData
|
||||||
elif len(embeddedRipeData) == 20:
|
elif len(embeddedRipeData) == 20:
|
||||||
return status,addressVersionNumber,streamNumber,embeddedRipeData
|
return status, addressVersionNumber, streamNumber, \
|
||||||
|
embeddedRipeData
|
||||||
elif len(embeddedRipeData) == 18:
|
elif len(embeddedRipeData) == 18:
|
||||||
return status,addressVersionNumber,streamNumber,'\x00\x00'+embeddedRipeData
|
return status, addressVersionNumber, streamNumber, \
|
||||||
|
'\x00\x00' + embeddedRipeData
|
||||||
elif len(embeddedRipeData) < 18:
|
elif len(embeddedRipeData) < 18:
|
||||||
return 'ripetooshort',0,0,""
|
return 'ripetooshort', 0, 0, ''
|
||||||
elif len(embeddedRipeData) > 20:
|
elif len(embeddedRipeData) > 20:
|
||||||
return 'ripetoolong',0,0,""
|
return 'ripetoolong', 0, 0, ''
|
||||||
else:
|
else:
|
||||||
return 'otherproblem',0,0,""
|
return 'otherproblem', 0, 0, ''
|
||||||
elif addressVersionNumber == 4:
|
elif addressVersionNumber == 4:
|
||||||
embeddedRipeData = data[bytesUsedByVersionNumber+bytesUsedByStreamNumber:-4]
|
embeddedRipeData = \
|
||||||
|
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||||
if embeddedRipeData[0:1] == '\x00':
|
if embeddedRipeData[0:1] == '\x00':
|
||||||
# In order to enforce address non-malleability, encoded RIPE data must have NULL bytes removed from the front
|
# In order to enforce address non-malleability, encoded
|
||||||
return 'encodingproblem',0,0,""
|
# RIPE data must have NULL bytes removed from the front
|
||||||
|
return 'encodingproblem', 0, 0, ''
|
||||||
elif len(embeddedRipeData) > 20:
|
elif len(embeddedRipeData) > 20:
|
||||||
return 'ripetoolong',0,0,""
|
return 'ripetoolong', 0, 0, ''
|
||||||
elif len(embeddedRipeData) < 4:
|
elif len(embeddedRipeData) < 4:
|
||||||
return 'ripetooshort',0,0,""
|
return 'ripetooshort', 0, 0, ''
|
||||||
else:
|
else:
|
||||||
x00string = '\x00' * (20 - len(embeddedRipeData))
|
x00string = '\x00' * (20 - len(embeddedRipeData))
|
||||||
return status,addressVersionNumber,streamNumber,x00string+embeddedRipeData
|
return status, addressVersionNumber, streamNumber, \
|
||||||
|
x00string + embeddedRipeData
|
||||||
|
|
||||||
|
|
||||||
def addBMIfNotPresent(address):
|
def addBMIfNotPresent(address):
|
||||||
address = str(address).strip()
|
address = str(address).strip()
|
||||||
|
@ -245,38 +284,65 @@ def addBMIfNotPresent(address):
|
||||||
else:
|
else:
|
||||||
return address
|
return address
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
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:'
|
print(
|
||||||
privateSigningKey = '93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665'
|
'\nLet us make an address from scratch. Suppose we generate two'
|
||||||
privateEncryptionKey = '4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a'
|
' random 32 byte values and call the first one the signing key'
|
||||||
print 'privateSigningKey =', privateSigningKey
|
' and the second one the encryption key:'
|
||||||
print 'privateEncryptionKey =', privateEncryptionKey
|
)
|
||||||
print 'Now let us convert them to public keys by doing an elliptic curve point multiplication.'
|
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)
|
publicSigningKey = arithmetic.privtopub(privateSigningKey)
|
||||||
publicEncryptionKey = arithmetic.privtopub(privateEncryptionKey)
|
publicEncryptionKey = arithmetic.privtopub(privateEncryptionKey)
|
||||||
print 'publicSigningKey =', publicSigningKey
|
print(
|
||||||
print 'publicEncryptionKey =', publicEncryptionKey
|
'\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)
|
publicSigningKeyBinary = \
|
||||||
publicEncryptionKeyBinary = arithmetic.changebase(publicEncryptionKey,16,256,minlen=64)
|
arithmetic.changebase(publicSigningKey, 16, 256, minlen=64)
|
||||||
|
publicEncryptionKeyBinary = \
|
||||||
|
arithmetic.changebase(publicEncryptionKey, 16, 256, minlen=64)
|
||||||
|
|
||||||
ripe = hashlib.new('ripemd160')
|
ripe = hashlib.new('ripemd160')
|
||||||
sha = hashlib.new('sha512')
|
sha = hashlib.new('sha512')
|
||||||
sha.update(publicSigningKeyBinary+publicEncryptionKeyBinary)
|
sha.update(publicSigningKeyBinary + publicEncryptionKeyBinary)
|
||||||
|
|
||||||
ripe.update(sha.digest())
|
ripe.update(sha.digest())
|
||||||
addressVersionNumber = 2
|
addressVersionNumber = 2
|
||||||
streamNumber = 1
|
streamNumber = 1
|
||||||
print 'Ripe digest that we will encode in the address:', hexlify(ripe.digest())
|
print(
|
||||||
returnedAddress = encodeAddress(addressVersionNumber,streamNumber,ripe.digest())
|
'\nRipe digest that we will encode in the address: %s' %
|
||||||
print 'Encoded address:', returnedAddress
|
hexlify(ripe.digest())
|
||||||
status,addressVersionNumber,streamNumber,data = decodeAddress(returnedAddress)
|
)
|
||||||
print '\nAfter decoding address:'
|
returnedAddress = \
|
||||||
print 'Status:', status
|
encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
|
||||||
print 'addressVersionNumber', addressVersionNumber
|
print('Encoded address: %s' % returnedAddress)
|
||||||
print 'streamNumber', streamNumber
|
status, addressVersionNumber, streamNumber, data = \
|
||||||
print 'length of data(the ripe hash):', len(data)
|
decodeAddress(returnedAddress)
|
||||||
print 'ripe data:', hexlify(data)
|
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 time
|
||||||
import sys
|
import threading
|
||||||
from pyelliptic.openssl import OpenSSL
|
|
||||||
import ctypes
|
|
||||||
import hashlib
|
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 binascii import hexlify
|
||||||
|
from pyelliptic import arithmetic
|
||||||
|
from pyelliptic.openssl import OpenSSL
|
||||||
|
|
||||||
|
import tr
|
||||||
import queues
|
import queues
|
||||||
import state
|
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):
|
class addressGenerator(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
|
@ -38,66 +39,95 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
payloadLengthExtraBytes = 0
|
payloadLengthExtraBytes = 0
|
||||||
live = True
|
live = True
|
||||||
if queueValue[0] == 'createChan':
|
if queueValue[0] == 'createChan':
|
||||||
command, addressVersionNumber, streamNumber, label, deterministicPassphrase, live = queueValue
|
command, addressVersionNumber, streamNumber, label, \
|
||||||
|
deterministicPassphrase, live = queueValue
|
||||||
eighteenByteRipe = False
|
eighteenByteRipe = False
|
||||||
numberOfAddressesToMake = 1
|
numberOfAddressesToMake = 1
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||||
elif queueValue[0] == 'joinChan':
|
elif queueValue[0] == 'joinChan':
|
||||||
command, chanAddress, label, deterministicPassphrase, live = queueValue
|
command, chanAddress, label, deterministicPassphrase, \
|
||||||
|
live = queueValue
|
||||||
eighteenByteRipe = False
|
eighteenByteRipe = False
|
||||||
addressVersionNumber = decodeAddress(chanAddress)[1]
|
addressVersionNumber = decodeAddress(chanAddress)[1]
|
||||||
streamNumber = decodeAddress(chanAddress)[2]
|
streamNumber = decodeAddress(chanAddress)[2]
|
||||||
numberOfAddressesToMake = 1
|
numberOfAddressesToMake = 1
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||||
elif len(queueValue) == 7:
|
elif len(queueValue) == 7:
|
||||||
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
|
command, addressVersionNumber, streamNumber, label, \
|
||||||
|
numberOfAddressesToMake, deterministicPassphrase, \
|
||||||
|
eighteenByteRipe = queueValue
|
||||||
try:
|
try:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
|
numberOfNullBytesDemandedOnFrontOfRipeHash = \
|
||||||
'bitmessagesettings', 'numberofnullbytesonaddress')
|
BMConfigParser().getint(
|
||||||
|
'bitmessagesettings',
|
||||||
|
'numberofnullbytesonaddress'
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
if eighteenByteRipe:
|
if eighteenByteRipe:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
||||||
else:
|
else:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # the default
|
# the default
|
||||||
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||||
elif len(queueValue) == 9:
|
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:
|
try:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
|
numberOfNullBytesDemandedOnFrontOfRipeHash = \
|
||||||
'bitmessagesettings', 'numberofnullbytesonaddress')
|
BMConfigParser().getint(
|
||||||
|
'bitmessagesettings',
|
||||||
|
'numberofnullbytesonaddress'
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
if eighteenByteRipe:
|
if eighteenByteRipe:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
|
||||||
else:
|
else:
|
||||||
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # the default
|
# the default
|
||||||
|
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
|
||||||
elif queueValue[0] == 'stopThread':
|
elif queueValue[0] == 'stopThread':
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
sys.stderr.write(
|
logger.error(
|
||||||
'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % repr(queueValue))
|
'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:
|
if addressVersionNumber < 3 or addressVersionNumber > 4:
|
||||||
sys.stderr.write(
|
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)
|
'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:
|
if nonceTrialsPerByte == 0:
|
||||||
nonceTrialsPerByte = BMConfigParser().getint(
|
nonceTrialsPerByte = BMConfigParser().getint(
|
||||||
'bitmessagesettings', 'defaultnoncetrialsperbyte')
|
'bitmessagesettings', 'defaultnoncetrialsperbyte')
|
||||||
if nonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
|
if nonceTrialsPerByte < \
|
||||||
nonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
|
||||||
|
nonceTrialsPerByte = \
|
||||||
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
if payloadLengthExtraBytes == 0:
|
if payloadLengthExtraBytes == 0:
|
||||||
payloadLengthExtraBytes = BMConfigParser().getint(
|
payloadLengthExtraBytes = BMConfigParser().getint(
|
||||||
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
|
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
|
||||||
if payloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes:
|
if payloadLengthExtraBytes < \
|
||||||
payloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
|
defaults.networkDefaultPayloadLengthExtraBytes:
|
||||||
|
payloadLengthExtraBytes = \
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
if command == 'createRandomAddress':
|
if command == 'createRandomAddress':
|
||||||
queues.UISignalQueue.put((
|
queues.UISignalQueue.put((
|
||||||
'updateStatusBar', tr._translate("MainWindow", "Generating one new address")))
|
'updateStatusBar',
|
||||||
# This next section is a little bit strange. We're going to generate keys over and over until we
|
tr._translate(
|
||||||
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
|
"MainWindow", "Generating one new address")
|
||||||
# we won't store the \x00 or \x00\x00 bytes thus making the
|
))
|
||||||
# address shorter.
|
# 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()
|
startTime = time.time()
|
||||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
||||||
potentialPrivSigningKey = OpenSSL.rand(32)
|
potentialPrivSigningKey = OpenSSL.rand(32)
|
||||||
potentialPubSigningKey = highlevelcrypto.pointMult(potentialPrivSigningKey)
|
potentialPubSigningKey = highlevelcrypto.pointMult(
|
||||||
|
potentialPrivSigningKey)
|
||||||
while True:
|
while True:
|
||||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
||||||
potentialPrivEncryptionKey = OpenSSL.rand(32)
|
potentialPrivEncryptionKey = OpenSSL.rand(32)
|
||||||
|
@ -110,15 +140,26 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
ripe.update(sha.digest())
|
ripe.update(sha.digest())
|
||||||
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
||||||
break
|
break
|
||||||
logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest()))
|
logger.info(
|
||||||
|
'Generated address with ripe digest: %s',
|
||||||
|
hexlify(ripe.digest()))
|
||||||
try:
|
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:
|
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
|
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
|
# https://en.bitcoin.it/wiki/Wallet_import_format
|
||||||
privSigningKey = '\x80' + potentialPrivSigningKey
|
privSigningKey = '\x80' + potentialPrivSigningKey
|
||||||
checksum = hashlib.sha256(hashlib.sha256(
|
checksum = hashlib.sha256(hashlib.sha256(
|
||||||
|
@ -141,9 +182,9 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
|
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
|
||||||
payloadLengthExtraBytes))
|
payloadLengthExtraBytes))
|
||||||
BMConfigParser().set(
|
BMConfigParser().set(
|
||||||
address, 'privSigningKey', privSigningKeyWIF)
|
address, 'privsigningkey', privSigningKeyWIF)
|
||||||
BMConfigParser().set(
|
BMConfigParser().set(
|
||||||
address, 'privEncryptionKey', privEncryptionKeyWIF)
|
address, 'privencryptionkey', privEncryptionKeyWIF)
|
||||||
BMConfigParser().save()
|
BMConfigParser().save()
|
||||||
|
|
||||||
# The API and the join and create Chan functionality
|
# The API and the join and create Chan functionality
|
||||||
|
@ -151,7 +192,12 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
queues.apiAddressGeneratorReturnQueue.put(address)
|
queues.apiAddressGeneratorReturnQueue.put(address)
|
||||||
|
|
||||||
queues.UISignalQueue.put((
|
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', (
|
queues.UISignalQueue.put(('writeNewAddressToTable', (
|
||||||
label, address, streamNumber)))
|
label, address, streamNumber)))
|
||||||
shared.reloadMyAddressHashes()
|
shared.reloadMyAddressHashes()
|
||||||
|
@ -162,31 +208,47 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
queues.workerQueue.put((
|
queues.workerQueue.put((
|
||||||
'sendOutOrStoreMyV4Pubkey', address))
|
'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:
|
if len(deterministicPassphrase) == 0:
|
||||||
sys.stderr.write(
|
logger.warning(
|
||||||
'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.')
|
'You are creating deterministic'
|
||||||
|
' address(es) using a blank passphrase.'
|
||||||
|
' Bitmessage will do it but it is rather stupid.')
|
||||||
if command == 'createDeterministicAddresses':
|
if command == 'createDeterministicAddresses':
|
||||||
queues.UISignalQueue.put((
|
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
|
signingKeyNonce = 0
|
||||||
encryptionKeyNonce = 1
|
encryptionKeyNonce = 1
|
||||||
listOfNewAddressesToSendOutThroughTheAPI = [
|
# We fill out this list no matter what although we only
|
||||||
] # We fill out this list no matter what although we only need it if we end up passing the info to the API.
|
# need it if we end up passing the info to the API.
|
||||||
|
listOfNewAddressesToSendOutThroughTheAPI = []
|
||||||
|
|
||||||
for i in range(numberOfAddressesToMake):
|
for i in range(numberOfAddressesToMake):
|
||||||
# This next section is a little bit strange. We're going to generate keys over and over until we
|
# This next section is a little bit strange. We're
|
||||||
# find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them
|
# going to generate keys over and over until we find
|
||||||
# into a Bitmessage address, we won't store the \x00 or
|
# 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.
|
# \x00\x00 bytes thus making the address shorter.
|
||||||
startTime = time.time()
|
startTime = time.time()
|
||||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
|
||||||
while True:
|
while True:
|
||||||
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
|
||||||
potentialPrivSigningKey = hashlib.sha512(
|
potentialPrivSigningKey = hashlib.sha512(
|
||||||
deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32]
|
deterministicPassphrase +
|
||||||
|
encodeVarint(signingKeyNonce)
|
||||||
|
).digest()[:32]
|
||||||
potentialPrivEncryptionKey = hashlib.sha512(
|
potentialPrivEncryptionKey = hashlib.sha512(
|
||||||
deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32]
|
deterministicPassphrase +
|
||||||
|
encodeVarint(encryptionKeyNonce)
|
||||||
|
).digest()[:32]
|
||||||
potentialPubSigningKey = highlevelcrypto.pointMult(
|
potentialPubSigningKey = highlevelcrypto.pointMult(
|
||||||
potentialPrivSigningKey)
|
potentialPrivSigningKey)
|
||||||
potentialPubEncryptionKey = highlevelcrypto.pointMult(
|
potentialPubEncryptionKey = highlevelcrypto.pointMult(
|
||||||
|
@ -201,26 +263,39 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
logger.info(
|
||||||
logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest()))
|
'Generated address with ripe digest: %s',
|
||||||
|
hexlify(ripe.digest()))
|
||||||
try:
|
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:
|
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
|
pass
|
||||||
address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
|
address = encodeAddress(
|
||||||
|
addressVersionNumber, streamNumber, ripe.digest())
|
||||||
|
|
||||||
saveAddressToDisk = True
|
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 command == 'joinChan':
|
||||||
if address != chanAddress:
|
if address != chanAddress:
|
||||||
listOfNewAddressesToSendOutThroughTheAPI.append('chan name does not match address')
|
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||||
|
'chan name does not match address')
|
||||||
saveAddressToDisk = False
|
saveAddressToDisk = False
|
||||||
if command == 'getDeterministicAddress':
|
if command == 'getDeterministicAddress':
|
||||||
saveAddressToDisk = False
|
saveAddressToDisk = False
|
||||||
|
|
||||||
if saveAddressToDisk and live:
|
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
|
# https://en.bitcoin.it/wiki/Wallet_import_format
|
||||||
privSigningKey = '\x80' + potentialPrivSigningKey
|
privSigningKey = '\x80' + potentialPrivSigningKey
|
||||||
checksum = hashlib.sha256(hashlib.sha256(
|
checksum = hashlib.sha256(hashlib.sha256(
|
||||||
|
@ -235,7 +310,6 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyWIF = arithmetic.changebase(
|
privEncryptionKeyWIF = arithmetic.changebase(
|
||||||
privEncryptionKey + checksum, 256, 58)
|
privEncryptionKey + checksum, 256, 58)
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
BMConfigParser().add_section(address)
|
BMConfigParser().add_section(address)
|
||||||
addressAlreadyExists = False
|
addressAlreadyExists = False
|
||||||
|
@ -243,55 +317,83 @@ class addressGenerator(threading.Thread, StoppableThread):
|
||||||
addressAlreadyExists = True
|
addressAlreadyExists = True
|
||||||
|
|
||||||
if addressAlreadyExists:
|
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((
|
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:
|
else:
|
||||||
logger.debug('label: %s' % label)
|
logger.debug('label: %s', label)
|
||||||
BMConfigParser().set(address, 'label', label)
|
BMConfigParser().set(address, 'label', label)
|
||||||
BMConfigParser().set(address, 'enabled', 'true')
|
BMConfigParser().set(address, 'enabled', 'true')
|
||||||
BMConfigParser().set(address, 'decoy', 'false')
|
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, 'chan', 'true')
|
||||||
BMConfigParser().set(address, 'noncetrialsperbyte', str(
|
|
||||||
nonceTrialsPerByte))
|
|
||||||
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
|
|
||||||
payloadLengthExtraBytes))
|
|
||||||
BMConfigParser().set(
|
BMConfigParser().set(
|
||||||
address, 'privSigningKey', privSigningKeyWIF)
|
address, 'noncetrialsperbyte',
|
||||||
|
str(nonceTrialsPerByte))
|
||||||
BMConfigParser().set(
|
BMConfigParser().set(
|
||||||
address, 'privEncryptionKey', privEncryptionKeyWIF)
|
address, 'payloadlengthextrabytes',
|
||||||
|
str(payloadLengthExtraBytes))
|
||||||
|
BMConfigParser().set(
|
||||||
|
address, 'privSigningKey',
|
||||||
|
privSigningKeyWIF)
|
||||||
|
BMConfigParser().set(
|
||||||
|
address, 'privEncryptionKey',
|
||||||
|
privEncryptionKeyWIF)
|
||||||
BMConfigParser().save()
|
BMConfigParser().save()
|
||||||
|
|
||||||
queues.UISignalQueue.put(('writeNewAddressToTable', (
|
queues.UISignalQueue.put((
|
||||||
label, address, str(streamNumber))))
|
'writeNewAddressToTable',
|
||||||
|
(label, address, str(streamNumber))
|
||||||
|
))
|
||||||
listOfNewAddressesToSendOutThroughTheAPI.append(
|
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||||
address)
|
address)
|
||||||
shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor(
|
shared.myECCryptorObjects[ripe.digest()] = \
|
||||||
|
highlevelcrypto.makeCryptor(
|
||||||
hexlify(potentialPrivEncryptionKey))
|
hexlify(potentialPrivEncryptionKey))
|
||||||
shared.myAddressesByHash[ripe.digest()] = address
|
shared.myAddressesByHash[ripe.digest()] = address
|
||||||
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
tag = hashlib.sha512(hashlib.sha512(
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + ripe.digest()).digest()).digest()[32:]
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + ripe.digest()
|
||||||
|
).digest()).digest()[32:]
|
||||||
shared.myAddressesByTag[tag] = address
|
shared.myAddressesByTag[tag] = address
|
||||||
if addressVersionNumber == 3:
|
if addressVersionNumber == 3:
|
||||||
|
# If this is a chan address,
|
||||||
|
# the worker thread won't send out
|
||||||
|
# the pubkey over the network.
|
||||||
queues.workerQueue.put((
|
queues.workerQueue.put((
|
||||||
'sendOutOrStoreMyV3Pubkey', ripe.digest())) # If this is a chan address,
|
'sendOutOrStoreMyV3Pubkey', ripe.digest()))
|
||||||
# the worker thread won't send out the pubkey over the network.
|
|
||||||
elif addressVersionNumber == 4:
|
elif addressVersionNumber == 4:
|
||||||
queues.workerQueue.put((
|
queues.workerQueue.put((
|
||||||
'sendOutOrStoreMyV4Pubkey', address))
|
'sendOutOrStoreMyV4Pubkey', address))
|
||||||
queues.UISignalQueue.put((
|
queues.UISignalQueue.put((
|
||||||
'updateStatusBar', tr._translate("MainWindow", "Done generating address")))
|
'updateStatusBar',
|
||||||
elif saveAddressToDisk and not live and not BMConfigParser().has_section(address):
|
tr._translate(
|
||||||
listOfNewAddressesToSendOutThroughTheAPI.append(address)
|
"MainWindow", "Done generating address")
|
||||||
|
))
|
||||||
|
elif saveAddressToDisk and not live \
|
||||||
|
and not BMConfigParser().has_section(address):
|
||||||
|
listOfNewAddressesToSendOutThroughTheAPI.append(
|
||||||
|
address)
|
||||||
|
|
||||||
# Done generating addresses.
|
# Done generating addresses.
|
||||||
if command == 'createDeterministicAddresses' or command == 'joinChan' or command == 'createChan':
|
if command == 'createDeterministicAddresses' \
|
||||||
|
or command == 'joinChan' or command == 'createChan':
|
||||||
queues.apiAddressGeneratorReturnQueue.put(
|
queues.apiAddressGeneratorReturnQueue.put(
|
||||||
listOfNewAddressesToSendOutThroughTheAPI)
|
listOfNewAddressesToSendOutThroughTheAPI)
|
||||||
elif command == 'getDeterministicAddress':
|
elif command == 'getDeterministicAddress':
|
||||||
queues.apiAddressGeneratorReturnQueue.put(address)
|
queues.apiAddressGeneratorReturnQueue.put(address)
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
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()
|
queues.addressGeneratorQueue.task_done()
|
||||||
|
|
|
@ -1,42 +1,48 @@
|
||||||
from __future__ import division
|
from __future__ import division
|
||||||
|
|
||||||
import threading
|
|
||||||
import shared
|
|
||||||
import time
|
import time
|
||||||
from time import strftime, localtime, gmtime
|
import threading
|
||||||
import random
|
import hashlib
|
||||||
from subprocess import call # used when the API must execute an outside program
|
from struct import pack
|
||||||
from addresses import *
|
# used when the API must execute an outside program
|
||||||
import highlevelcrypto
|
from subprocess import call
|
||||||
import proofofwork
|
from binascii import hexlify, unhexlify
|
||||||
import sys
|
|
||||||
import tr
|
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 l10n
|
||||||
import protocol
|
import protocol
|
||||||
import queues
|
import queues
|
||||||
import state
|
import state
|
||||||
from binascii import hexlify, unhexlify
|
import shared
|
||||||
|
import defaults
|
||||||
|
import highlevelcrypto
|
||||||
|
import proofofwork
|
||||||
|
import helper_inbox
|
||||||
import helper_random
|
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:
|
# This thread, of which there is only one, does the heavy lifting:
|
||||||
# calculating POWs.
|
# calculating POWs.
|
||||||
|
|
||||||
|
|
||||||
def sizeof_fmt(num, suffix='h/s'):
|
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:
|
if abs(num) < 1000.0:
|
||||||
return "%3.1f%s%s" % (num, unit, suffix)
|
return "%3.1f%s%s" % (num, unit, suffix)
|
||||||
num /= 1024.0
|
num /= 1024.0
|
||||||
return "%.1f%s%s" % (num, 'Yi', suffix)
|
return "%.1f%s%s" % (num, 'Yi', suffix)
|
||||||
|
|
||||||
|
|
||||||
class singleWorker(threading.Thread, StoppableThread):
|
class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
@ -61,18 +67,29 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
# Initialize the neededPubkeys dictionary.
|
# Initialize the neededPubkeys dictionary.
|
||||||
queryreturn = sqlQuery(
|
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:
|
for row in queryreturn:
|
||||||
toAddress, = row
|
toAddress, = row
|
||||||
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = decodeAddress(toAddress)
|
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = \
|
||||||
if toAddressVersionNumber <= 3 :
|
decodeAddress(toAddress)
|
||||||
|
if toAddressVersionNumber <= 3:
|
||||||
state.neededPubkeys[toAddress] = 0
|
state.neededPubkeys[toAddress] = 0
|
||||||
elif toAddressVersionNumber >= 4:
|
elif toAddressVersionNumber >= 4:
|
||||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||||
toAddressVersionNumber) + encodeVarint(toStreamNumber) + toRipe).digest()).digest()
|
encodeVarint(toAddressVersionNumber) +
|
||||||
privEncryptionKey = doubleHashOfAddressData[:32] # Note that this is the first half of the sha512 hash.
|
encodeVarint(toStreamNumber) + toRipe
|
||||||
|
).digest()).digest()
|
||||||
|
# Note that this is the first half of the sha512 hash.
|
||||||
|
privEncryptionKey = doubleHashOfAddressData[:32]
|
||||||
tag = 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
|
# Initialize the shared.ackdataForWhichImWatching data structure
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
|
@ -84,16 +101,19 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
# Fix legacy (headerless) watched ackdata to include header
|
# Fix legacy (headerless) watched ackdata to include header
|
||||||
for oldack in shared.ackdataForWhichImWatching.keys():
|
for oldack in shared.ackdataForWhichImWatching.keys():
|
||||||
if (len(oldack)==32):
|
if (len(oldack) == 32):
|
||||||
# attach legacy header, always constant (msg/1/1)
|
# attach legacy header, always constant (msg/1/1)
|
||||||
newack = '\x00\x00\x00\x02\x01\x01' + oldack
|
newack = '\x00\x00\x00\x02\x01\x01' + oldack
|
||||||
shared.ackdataForWhichImWatching[newack] = 0
|
shared.ackdataForWhichImWatching[newack] = 0
|
||||||
sqlExecute('UPDATE sent SET ackdata=? WHERE ackdata=?',
|
sqlExecute(
|
||||||
newack, oldack )
|
'UPDATE sent SET ackdata=? WHERE ackdata=?',
|
||||||
|
newack, oldack
|
||||||
|
)
|
||||||
del shared.ackdataForWhichImWatching[oldack]
|
del shared.ackdataForWhichImWatching[oldack]
|
||||||
|
|
||||||
self.stop.wait(
|
# give some time for the GUI to start
|
||||||
10) # give some time for the GUI to start before we start on existing POW tasks.
|
# before we start on existing POW tasks.
|
||||||
|
self.stop.wait(10)
|
||||||
|
|
||||||
if state.shutdown == 0:
|
if state.shutdown == 0:
|
||||||
# just in case there are any pending tasks for msg
|
# just in case there are any pending tasks for msg
|
||||||
|
@ -141,17 +161,25 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
self.busy = 0
|
self.busy = 0
|
||||||
return
|
return
|
||||||
else:
|
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()
|
queues.workerQueue.task_done()
|
||||||
logger.info("Quitting...")
|
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
|
# Look up my stream number based on my address hash
|
||||||
"""configSections = shared.config.addresses()
|
"""configSections = shared.config.addresses()
|
||||||
for addressInKeysFile in configSections:
|
for addressInKeysFile in configSections:
|
||||||
if addressInKeysFile <> 'bitmessagesettings':
|
if addressInKeysFile != 'bitmessagesettings':
|
||||||
status,addressVersionNumber,streamNumber,hashFromThisParticularAddress = decodeAddress(addressInKeysFile)
|
status, addressVersionNumber, streamNumber, \
|
||||||
|
hashFromThisParticularAddress = \
|
||||||
|
decodeAddress(addressInKeysFile)
|
||||||
if hash == hashFromThisParticularAddress:
|
if hash == hashFromThisParticularAddress:
|
||||||
myAddress = addressInKeysFile
|
myAddress = addressInKeysFile
|
||||||
break"""
|
break"""
|
||||||
|
@ -159,13 +187,15 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||||
myAddress)
|
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)
|
embeddedTime = int(time.time() + TTL)
|
||||||
payload = pack('>Q', (embeddedTime))
|
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(addressVersionNumber) # Address version number
|
||||||
payload += encodeVarint(streamNumber)
|
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:
|
try:
|
||||||
privSigningKeyBase58 = BMConfigParser().get(
|
privSigningKeyBase58 = BMConfigParser().get(
|
||||||
|
@ -173,7 +203,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
myAddress, 'privencryptionkey')
|
myAddress, 'privencryptionkey')
|
||||||
except Exception as err:
|
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
|
return
|
||||||
|
|
||||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
|
@ -189,19 +223,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
payload += pubEncryptionKey[1:]
|
payload += pubEncryptionKey[1:]
|
||||||
|
|
||||||
# Do the POW for this pubkey message
|
# 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...')
|
logger.info('(For pubkey message) Doing proof of work...')
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
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
|
payload = pack('>Q', nonce) + payload
|
||||||
|
|
||||||
inventoryHash = calculateInventoryHash(payload)
|
inventoryHash = calculateInventoryHash(payload)
|
||||||
objectType = 1
|
objectType = 1
|
||||||
Inventory()[inventoryHash] = (
|
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.invQueue.put((streamNumber, inventoryHash))
|
||||||
queues.UISignalQueue.put(('updateStatusBar', ''))
|
queues.UISignalQueue.put(('updateStatusBar', ''))
|
||||||
|
@ -210,8 +255,8 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
||||||
BMConfigParser().save()
|
BMConfigParser().save()
|
||||||
except:
|
except:
|
||||||
# The user deleted the address out of the keys.dat file before this
|
# The user deleted the address out of the keys.dat file
|
||||||
# finished.
|
# before this finished.
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# If this isn't a chan address, this function assembles the pubkey data,
|
# If this isn't a chan address, this function assembles the pubkey data,
|
||||||
|
@ -222,7 +267,7 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
try:
|
try:
|
||||||
myAddress = shared.myAddressesByHash[hash]
|
myAddress = shared.myAddressesByHash[hash]
|
||||||
except:
|
except:
|
||||||
#The address has been deleted.
|
# The address has been deleted.
|
||||||
return
|
return
|
||||||
if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
||||||
logger.info('This is a chan address. Not sending pubkey.')
|
logger.info('This is a chan address. Not sending pubkey.')
|
||||||
|
@ -230,22 +275,25 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||||
myAddress)
|
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)
|
embeddedTime = int(time.time() + TTL)
|
||||||
signedTimeForProtocolV2 = embeddedTime - TTL
|
# signedTimeForProtocolV2 = embeddedTime - TTL
|
||||||
"""
|
"""
|
||||||
According to the protocol specification, the expiresTime along with the pubkey information is
|
According to the protocol specification, the expiresTime
|
||||||
signed. But to be backwards compatible during the upgrade period, we shall sign not the
|
along with the pubkey information is signed. But to be
|
||||||
expiresTime but rather the current time. There must be precisely a 28 day difference
|
backwards compatible during the upgrade period, we shall sign
|
||||||
between the two. After the upgrade period we'll switch to signing the whole payload with the
|
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.
|
expiresTime time.
|
||||||
"""
|
"""
|
||||||
payload = pack('>Q', (embeddedTime))
|
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(addressVersionNumber) # Address version number
|
||||||
payload += encodeVarint(streamNumber)
|
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:
|
try:
|
||||||
privSigningKeyBase58 = BMConfigParser().get(
|
privSigningKeyBase58 = BMConfigParser().get(
|
||||||
|
@ -253,8 +301,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
myAddress, 'privencryptionkey')
|
myAddress, 'privencryptionkey')
|
||||||
except Exception as err:
|
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
|
return
|
||||||
|
|
||||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
|
@ -279,17 +330,28 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
payload += signature
|
payload += signature
|
||||||
|
|
||||||
# Do the POW for this pubkey message
|
# 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...')
|
logger.info('(For pubkey message) Doing proof of work...')
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
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
|
payload = pack('>Q', nonce) + payload
|
||||||
inventoryHash = calculateInventoryHash(payload)
|
inventoryHash = calculateInventoryHash(payload)
|
||||||
objectType = 1
|
objectType = 1
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, payload, embeddedTime,'')
|
objectType, streamNumber, payload, embeddedTime, '')
|
||||||
|
|
||||||
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
||||||
|
|
||||||
|
@ -304,11 +366,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# finished.
|
# finished.
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# If this isn't a chan address, this function assembles the pubkey data,
|
# If this isn't a chan address, this function assembles
|
||||||
# does the necessary POW and sends it out.
|
# the pubkey data, does the necessary POW and sends it out.
|
||||||
def sendOutOrStoreMyV4Pubkey(self, myAddress):
|
def sendOutOrStoreMyV4Pubkey(self, myAddress):
|
||||||
if not BMConfigParser().has_section(myAddress):
|
if not BMConfigParser().has_section(myAddress):
|
||||||
#The address has been deleted.
|
# The address has been deleted.
|
||||||
return
|
return
|
||||||
if shared.BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
if shared.BMConfigParser().safeGetBoolean(myAddress, 'chan'):
|
||||||
logger.info('This is a chan address. Not sending pubkey.')
|
logger.info('This is a chan address. Not sending pubkey.')
|
||||||
|
@ -316,11 +378,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
status, addressVersionNumber, streamNumber, hash = decodeAddress(
|
||||||
myAddress)
|
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)
|
embeddedTime = int(time.time() + TTL)
|
||||||
payload = pack('>Q', (embeddedTime))
|
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(addressVersionNumber) # Address version number
|
||||||
payload += encodeVarint(streamNumber)
|
payload += encodeVarint(streamNumber)
|
||||||
dataToEncrypt = protocol.getBitfield(myAddress)
|
dataToEncrypt = protocol.getBitfield(myAddress)
|
||||||
|
@ -331,7 +393,11 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
myAddress, 'privencryptionkey')
|
myAddress, 'privencryptionkey')
|
||||||
except Exception as err:
|
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
|
return
|
||||||
|
|
||||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
|
@ -351,15 +417,20 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
myAddress, 'payloadlengthextrabytes'))
|
myAddress, 'payloadlengthextrabytes'))
|
||||||
|
|
||||||
# When we encrypt, we'll use a hash of the data
|
# When we encrypt, we'll use a hash of the data
|
||||||
# contained in an address as a decryption key. This way in order to
|
# contained in an address as a decryption key. This way
|
||||||
# read the public keys in a pubkey message, a node must know the address
|
# in order to read the public keys in a pubkey message,
|
||||||
# first. We'll also tag, unencrypted, the pubkey with part of the hash
|
# a node must know the address first. We'll also tag,
|
||||||
# so that nodes know which pubkey object to try to decrypt when they
|
# unencrypted, the pubkey with part of the hash so that nodes
|
||||||
# want to send a message.
|
# know which pubkey object to try to decrypt
|
||||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
# when they want to send a message.
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + hash).digest()).digest()
|
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||||
payload += doubleHashOfAddressData[32:] # the tag
|
encodeVarint(addressVersionNumber) +
|
||||||
signature = highlevelcrypto.sign(payload + dataToEncrypt, privSigningKeyHex)
|
encodeVarint(streamNumber) + hash
|
||||||
|
).digest()).digest()
|
||||||
|
payload += doubleHashOfAddressData[32:] # the tag
|
||||||
|
signature = highlevelcrypto.sign(
|
||||||
|
payload + dataToEncrypt, privSigningKeyHex
|
||||||
|
)
|
||||||
dataToEncrypt += encodeVarint(len(signature))
|
dataToEncrypt += encodeVarint(len(signature))
|
||||||
dataToEncrypt += signature
|
dataToEncrypt += signature
|
||||||
|
|
||||||
|
@ -369,17 +440,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
dataToEncrypt, hexlify(pubEncryptionKey))
|
dataToEncrypt, hexlify(pubEncryptionKey))
|
||||||
|
|
||||||
# Do the POW for this pubkey message
|
# 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...')
|
logger.info('(For pubkey message) Doing proof of work...')
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
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
|
payload = pack('>Q', nonce) + payload
|
||||||
inventoryHash = calculateInventoryHash(payload)
|
inventoryHash = calculateInventoryHash(payload)
|
||||||
objectType = 1
|
objectType = 1
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, payload, embeddedTime, doubleHashOfAddressData[32:])
|
objectType, streamNumber, payload, embeddedTime,
|
||||||
|
doubleHashOfAddressData[32:]
|
||||||
|
)
|
||||||
|
|
||||||
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
logger.info('broadcasting inv with hash: ' + hexlify(inventoryHash))
|
||||||
|
|
||||||
|
@ -390,21 +474,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
myAddress, 'lastpubkeysendtime', str(int(time.time())))
|
||||||
BMConfigParser().save()
|
BMConfigParser().save()
|
||||||
except Exception as err:
|
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):
|
def sendBroadcast(self):
|
||||||
# Reset just in case
|
# Reset just in case
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='broadcastqueued' WHERE status = 'doingbroadcastpow' ''')
|
'''UPDATE sent SET status='broadcastqueued' '''
|
||||||
|
'''WHERE status = 'doingbroadcastpow' ''')
|
||||||
queryreturn = sqlQuery(
|
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:
|
for row in queryreturn:
|
||||||
fromaddress, subject, body, ackdata, TTL, encoding = row
|
fromaddress, subject, body, ackdata, TTL, encoding = row
|
||||||
status, addressVersionNumber, streamNumber, ripe = decodeAddress(
|
status, addressVersionNumber, streamNumber, ripe = \
|
||||||
fromaddress)
|
decodeAddress(fromaddress)
|
||||||
if addressVersionNumber <= 1:
|
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')
|
||||||
return
|
return
|
||||||
# We need to convert our private keys to public keys in order
|
# We need to convert our private keys to public keys in order
|
||||||
# to include them.
|
# to include them.
|
||||||
|
@ -414,12 +507,19 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
fromaddress, 'privencryptionkey')
|
fromaddress, 'privencryptionkey')
|
||||||
except:
|
except:
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
queues.UISignalQueue.put((
|
||||||
ackdata, tr._translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file."))))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Error! Could not find sender address"
|
||||||
|
" (your address) in the keys.dat file."))
|
||||||
|
))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='doingbroadcastpow' WHERE ackdata=? AND status='broadcastqueued' ''',
|
'''UPDATE sent SET status='doingbroadcastpow' '''
|
||||||
|
''' WHERE ackdata=? AND status='broadcastqueued' ''',
|
||||||
ackdata)
|
ackdata)
|
||||||
|
|
||||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
|
@ -427,20 +527,23 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
privEncryptionKeyBase58))
|
privEncryptionKeyBase58))
|
||||||
|
|
||||||
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode(
|
# At this time these pubkeys are 65 bytes long
|
||||||
'hex') # At this time these pubkeys are 65 bytes long because they include the encoding byte which we won't be sending in the broadcast message.
|
# because they include the encoding byte which we won't
|
||||||
|
# be sending in the broadcast message.
|
||||||
|
pubSigningKey = \
|
||||||
|
highlevelcrypto.privToPub(privSigningKeyHex).decode('hex')
|
||||||
pubEncryptionKey = unhexlify(highlevelcrypto.privToPub(
|
pubEncryptionKey = unhexlify(highlevelcrypto.privToPub(
|
||||||
privEncryptionKeyHex))
|
privEncryptionKeyHex))
|
||||||
|
|
||||||
if TTL > 28 * 24 * 60 * 60:
|
if TTL > 28 * 24 * 60 * 60:
|
||||||
TTL = 28 * 24 * 60 * 60
|
TTL = 28 * 24 * 60 * 60
|
||||||
if TTL < 60*60:
|
if TTL < 60 * 60:
|
||||||
TTL = 60*60
|
TTL = 60 * 60
|
||||||
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
|
||||||
# add some randomness to the TTL
|
# add some randomness to the TTL
|
||||||
|
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
||||||
embeddedTime = int(time.time() + TTL)
|
embeddedTime = int(time.time() + TTL)
|
||||||
payload = pack('>Q', embeddedTime)
|
payload = pack('>Q', embeddedTime)
|
||||||
payload += '\x00\x00\x00\x03' # object type: broadcast
|
payload += '\x00\x00\x00\x03' # object type: broadcast
|
||||||
|
|
||||||
if addressVersionNumber <= 3:
|
if addressVersionNumber <= 3:
|
||||||
payload += encodeVarint(4) # broadcast version
|
payload += encodeVarint(4) # broadcast version
|
||||||
|
@ -449,8 +552,10 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
payload += encodeVarint(streamNumber)
|
payload += encodeVarint(streamNumber)
|
||||||
if addressVersionNumber >= 4:
|
if addressVersionNumber >= 4:
|
||||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()).digest()
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + ripe
|
||||||
|
).digest()).digest()
|
||||||
tag = doubleHashOfAddressData[32:]
|
tag = doubleHashOfAddressData[32:]
|
||||||
payload += tag
|
payload += tag
|
||||||
else:
|
else:
|
||||||
|
@ -458,14 +563,19 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
dataToEncrypt = encodeVarint(addressVersionNumber)
|
dataToEncrypt = encodeVarint(addressVersionNumber)
|
||||||
dataToEncrypt += encodeVarint(streamNumber)
|
dataToEncrypt += encodeVarint(streamNumber)
|
||||||
dataToEncrypt += protocol.getBitfield(fromaddress) # behavior bitfield
|
# behavior bitfield
|
||||||
|
dataToEncrypt += protocol.getBitfield(fromaddress)
|
||||||
dataToEncrypt += pubSigningKey[1:]
|
dataToEncrypt += pubSigningKey[1:]
|
||||||
dataToEncrypt += pubEncryptionKey[1:]
|
dataToEncrypt += pubEncryptionKey[1:]
|
||||||
if addressVersionNumber >= 3:
|
if addressVersionNumber >= 3:
|
||||||
dataToEncrypt += encodeVarint(BMConfigParser().getint(fromaddress,'noncetrialsperbyte'))
|
dataToEncrypt += encodeVarint(BMConfigParser().getint(
|
||||||
dataToEncrypt += encodeVarint(BMConfigParser().getint(fromaddress,'payloadlengthextrabytes'))
|
fromaddress, 'noncetrialsperbyte'))
|
||||||
dataToEncrypt += encodeVarint(encoding) # message encoding type
|
dataToEncrypt += encodeVarint(BMConfigParser().getint(
|
||||||
encodedMessage = helper_msgcoding.MsgEncode({"subject": subject, "body": body}, encoding)
|
fromaddress, 'payloadlengthextrabytes'))
|
||||||
|
# message encoding type
|
||||||
|
dataToEncrypt += encodeVarint(encoding)
|
||||||
|
encodedMessage = helper_msgcoding.MsgEncode(
|
||||||
|
{"subject": subject, "body": body}, encoding)
|
||||||
dataToEncrypt += encodeVarint(encodedMessage.length)
|
dataToEncrypt += encodeVarint(encodedMessage.length)
|
||||||
dataToEncrypt += encodedMessage.data
|
dataToEncrypt += encodedMessage.data
|
||||||
dataToSign = payload + dataToEncrypt
|
dataToSign = payload + dataToEncrypt
|
||||||
|
@ -475,14 +585,18 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
dataToEncrypt += encodeVarint(len(signature))
|
dataToEncrypt += encodeVarint(len(signature))
|
||||||
dataToEncrypt += signature
|
dataToEncrypt += signature
|
||||||
|
|
||||||
# Encrypt the broadcast with the information contained in the broadcaster's address.
|
# Encrypt the broadcast with the information
|
||||||
# Anyone who knows the address can generate the private encryption key to decrypt
|
# contained in the broadcaster's address.
|
||||||
# the broadcast. This provides virtually no privacy; its purpose is to keep
|
# Anyone who knows the address can generate
|
||||||
# questionable and illegal content from flowing through the Internet connections
|
# the private encryption key to decrypt the broadcast.
|
||||||
# and being stored on the disk of 3rd parties.
|
# This provides virtually no privacy; its purpose is to keep
|
||||||
|
# questionable and illegal content from flowing through the
|
||||||
|
# Internet connections and being stored on the disk of 3rd parties.
|
||||||
if addressVersionNumber <= 3:
|
if addressVersionNumber <= 3:
|
||||||
privEncryptionKey = hashlib.sha512(encodeVarint(
|
privEncryptionKey = hashlib.sha512(
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32]
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + ripe
|
||||||
|
).digest()[:32]
|
||||||
else:
|
else:
|
||||||
privEncryptionKey = doubleHashOfAddressData[:32]
|
privEncryptionKey = doubleHashOfAddressData[:32]
|
||||||
|
|
||||||
|
@ -490,166 +604,283 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
payload += highlevelcrypto.encrypt(
|
payload += highlevelcrypto.encrypt(
|
||||||
dataToEncrypt, hexlify(pubEncryptionKey))
|
dataToEncrypt, hexlify(pubEncryptionKey))
|
||||||
|
|
||||||
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 broadcast message) Doing proof of work...')
|
logger.info('(For broadcast message) Doing proof of work...')
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
queues.UISignalQueue.put((
|
||||||
ackdata, tr._translate("MainWindow", "Doing work necessary to send broadcast..."))))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Doing work necessary to send broadcast..."))
|
||||||
|
))
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
logger.info('(For broadcast message) Found proof of work ' + str(trialValue) + ' Nonce: ' + str(nonce))
|
logger.info(
|
||||||
|
'(For broadcast message) Found proof of work %s Nonce: %s',
|
||||||
|
trialValue, nonce
|
||||||
|
)
|
||||||
|
|
||||||
payload = pack('>Q', nonce) + payload
|
payload = pack('>Q', nonce) + payload
|
||||||
|
|
||||||
# Sanity check. The payload size should never be larger than 256 KiB. There should
|
# Sanity check. The payload size should never be larger
|
||||||
# be checks elsewhere in the code to not let the user try to send a message this large
|
# than 256 KiB. There should be checks elsewhere in the code
|
||||||
|
# to not let the user try to send a message this large
|
||||||
# until we implement message continuation.
|
# until we implement message continuation.
|
||||||
if len(payload) > 2 ** 18: # 256 KiB
|
if len(payload) > 2 ** 18: # 256 KiB
|
||||||
logger.critical('This broadcast object is too large to send. This should never happen. Object size: %s' % len(payload))
|
logger.critical(
|
||||||
|
'This broadcast object is too large to send.'
|
||||||
|
' This should never happen. Object size: %s',
|
||||||
|
len(payload)
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
inventoryHash = calculateInventoryHash(payload)
|
inventoryHash = calculateInventoryHash(payload)
|
||||||
objectType = 3
|
objectType = 3
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, payload, embeddedTime, tag)
|
objectType, streamNumber, payload, embeddedTime, tag)
|
||||||
logger.info('sending inv (within sendBroadcast function) for object: ' + hexlify(inventoryHash))
|
logger.info(
|
||||||
|
'sending inv (within sendBroadcast function)'
|
||||||
|
' for object: %s',
|
||||||
|
hexlify(inventoryHash)
|
||||||
|
)
|
||||||
queues.invQueue.put((streamNumber, inventoryHash))
|
queues.invQueue.put((streamNumber, inventoryHash))
|
||||||
|
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Broadcast sent on %1").arg(l10n.formatTimestamp()))))
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Broadcast sent on %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
|
|
||||||
# Update the status of the message in the 'sent' table to have
|
# Update the status of the message in the 'sent' table to have
|
||||||
# a 'broadcastsent' status
|
# a 'broadcastsent' status
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'UPDATE sent SET msgid=?, status=?, lastactiontime=? WHERE ackdata=?',
|
'UPDATE sent SET msgid=?, status=?, lastactiontime=?'
|
||||||
inventoryHash,
|
' WHERE ackdata=?',
|
||||||
'broadcastsent',
|
inventoryHash, 'broadcastsent', int(time.time()), ackdata
|
||||||
int(time.time()),
|
)
|
||||||
ackdata)
|
|
||||||
|
|
||||||
|
|
||||||
def sendMsg(self):
|
def sendMsg(self):
|
||||||
# Reset just in case
|
# Reset just in case
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='msgqueued' WHERE status IN ('doingpubkeypow', 'doingmsgpow')''')
|
'''UPDATE sent SET status='msgqueued' '''
|
||||||
|
''' WHERE status IN ('doingpubkeypow', 'doingmsgpow')''')
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'''SELECT toaddress, fromaddress, subject, message, ackdata, status, ttl, retrynumber, encodingtype FROM sent WHERE (status='msgqueued' or status='forcepow') and folder='sent' ''')
|
'''SELECT toaddress, fromaddress, subject, message, '''
|
||||||
for row in queryreturn: # while we have a msg that needs some work
|
''' ackdata, status, ttl, retrynumber, encodingtype FROM '''
|
||||||
toaddress, fromaddress, subject, message, ackdata, status, TTL, retryNumber, encoding = row
|
''' sent WHERE (status='msgqueued' or status='forcepow') '''
|
||||||
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = decodeAddress(
|
''' and folder='sent' ''')
|
||||||
toaddress)
|
# while we have a msg that needs some work
|
||||||
fromStatus, fromAddressVersionNumber, fromStreamNumber, fromRipe = decodeAddress(
|
for row in queryreturn:
|
||||||
fromaddress)
|
toaddress, fromaddress, subject, message, \
|
||||||
|
ackdata, status, TTL, retryNumber, encoding = row
|
||||||
|
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = \
|
||||||
|
decodeAddress(toaddress)
|
||||||
|
fromStatus, fromAddressVersionNumber, fromStreamNumber, \
|
||||||
|
fromRipe = decodeAddress(fromaddress)
|
||||||
|
|
||||||
# We may or may not already have the pubkey for this toAddress. Let's check.
|
# We may or may not already have the pubkey
|
||||||
|
# for this toAddress. Let's check.
|
||||||
if status == 'forcepow':
|
if status == 'forcepow':
|
||||||
# if the status of this msg is 'forcepow' then clearly we have the pubkey already
|
# if the status of this msg is 'forcepow'
|
||||||
# because the user could not have overridden the message about the POW being
|
# then clearly we have the pubkey already
|
||||||
# too difficult without knowing the required difficulty.
|
# because the user could not have overridden the message
|
||||||
|
# about the POW being too difficult without knowing
|
||||||
|
# the required difficulty.
|
||||||
pass
|
pass
|
||||||
elif status == 'doingmsgpow':
|
elif status == 'doingmsgpow':
|
||||||
# We wouldn't have set the status to doingmsgpow if we didn't already have the pubkey
|
# We wouldn't have set the status to doingmsgpow
|
||||||
# so let's assume that we have it.
|
# if we didn't already have the pubkey so let's assume
|
||||||
|
# that we have it.
|
||||||
pass
|
pass
|
||||||
# If we are sending a message to ourselves or a chan then we won't need an entry in the pubkeys table; we can calculate the needed pubkey using the private keys in our keys.dat file.
|
# If we are sending a message to ourselves or a chan
|
||||||
|
# then we won't need an entry in the pubkeys table;
|
||||||
|
# we can calculate the needed pubkey using the private keys
|
||||||
|
# in our keys.dat file.
|
||||||
elif BMConfigParser().has_section(toaddress):
|
elif BMConfigParser().has_section(toaddress):
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''',
|
'''UPDATE sent SET status='doingmsgpow' '''
|
||||||
toaddress)
|
''' WHERE toaddress=? AND status='msgqueued' ''',
|
||||||
status='doingmsgpow'
|
toaddress
|
||||||
|
)
|
||||||
|
status = 'doingmsgpow'
|
||||||
elif status == 'msgqueued':
|
elif status == 'msgqueued':
|
||||||
# Let's see if we already have the pubkey in our pubkeys table
|
# Let's see if we already have the pubkey in our pubkeys table
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'''SELECT address FROM pubkeys WHERE address=?''', toaddress)
|
'''SELECT address FROM pubkeys WHERE address=?''',
|
||||||
if queryreturn != []: # If we have the needed pubkey in the pubkey table already,
|
toaddress
|
||||||
|
)
|
||||||
|
# If we have the needed pubkey in the pubkey table already,
|
||||||
|
if queryreturn != []:
|
||||||
# set the status of this msg to doingmsgpow
|
# set the status of this msg to doingmsgpow
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''',
|
'''UPDATE sent SET status='doingmsgpow' '''
|
||||||
toaddress)
|
''' WHERE toaddress=? AND status='msgqueued' ''',
|
||||||
|
toaddress
|
||||||
|
)
|
||||||
status = 'doingmsgpow'
|
status = 'doingmsgpow'
|
||||||
# mark the pubkey as 'usedpersonally' so that we don't delete it later. If the pubkey version
|
# mark the pubkey as 'usedpersonally' so that
|
||||||
# is >= 4 then usedpersonally will already be set to yes because we'll only ever have
|
# we don't delete it later. If the pubkey version
|
||||||
|
# is >= 4 then usedpersonally will already be set
|
||||||
|
# to yes because we'll only ever have
|
||||||
# usedpersonally v4 pubkeys in the pubkeys table.
|
# usedpersonally v4 pubkeys in the pubkeys table.
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE pubkeys SET usedpersonally='yes' WHERE address=?''',
|
'''UPDATE pubkeys SET usedpersonally='yes' '''
|
||||||
toaddress)
|
''' WHERE address=?''',
|
||||||
else: # We don't have the needed pubkey in the pubkeys table already.
|
toaddress
|
||||||
|
)
|
||||||
|
# We don't have the needed pubkey in the pubkeys table already.
|
||||||
|
else:
|
||||||
if toAddressVersionNumber <= 3:
|
if toAddressVersionNumber <= 3:
|
||||||
toTag = ''
|
toTag = ''
|
||||||
else:
|
else:
|
||||||
toTag = hashlib.sha512(hashlib.sha512(encodeVarint(toAddressVersionNumber)+encodeVarint(toStreamNumber)+toRipe).digest()).digest()[32:]
|
toTag = hashlib.sha512(hashlib.sha512(
|
||||||
if toaddress in state.neededPubkeys or toTag in state.neededPubkeys:
|
encodeVarint(toAddressVersionNumber) +
|
||||||
|
encodeVarint(toStreamNumber) + toRipe
|
||||||
|
).digest()).digest()[32:]
|
||||||
|
if toaddress in state.neededPubkeys or \
|
||||||
|
toTag in state.neededPubkeys:
|
||||||
# We already sent a request for the pubkey
|
# We already sent a request for the pubkey
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='awaitingpubkey', sleeptill=? WHERE toaddress=? AND status='msgqueued' ''',
|
'''UPDATE sent SET status='awaitingpubkey', '''
|
||||||
int(time.time()) + 2.5*24*60*60,
|
''' sleeptill=? WHERE toaddress=? '''
|
||||||
toaddress)
|
''' AND status='msgqueued' ''',
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByToAddress', (
|
int(time.time()) + 2.5 * 24 * 60 * 60,
|
||||||
toaddress, tr._translate("MainWindow",'Encryption key was requested earlier.'))))
|
toaddress
|
||||||
continue #on with the next msg on which we can do some work
|
)
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByToAddress', (
|
||||||
|
toaddress,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Encryption key was requested earlier."))
|
||||||
|
))
|
||||||
|
# on with the next msg on which we can do some work
|
||||||
|
continue
|
||||||
else:
|
else:
|
||||||
# We have not yet sent a request for the pubkey
|
# We have not yet sent a request for the pubkey
|
||||||
needToRequestPubkey = True
|
needToRequestPubkey = True
|
||||||
if toAddressVersionNumber >= 4: # If we are trying to send to address version >= 4 then
|
# If we are trying to send to address
|
||||||
# the needed pubkey might be encrypted in the inventory.
|
# version >= 4 then the needed pubkey might be
|
||||||
# If we have it we'll need to decrypt it and put it in
|
# encrypted in the inventory.
|
||||||
# the pubkeys table.
|
# If we have it we'll need to decrypt it
|
||||||
|
# and put it in the pubkeys table.
|
||||||
|
|
||||||
# The decryptAndCheckPubkeyPayload function expects that the shared.neededPubkeys
|
# The decryptAndCheckPubkeyPayload function
|
||||||
# dictionary already contains the toAddress and cryptor object associated with
|
# expects that the shared.neededPubkeys dictionary
|
||||||
# the tag for this toAddress.
|
# already contains the toAddress and cryptor
|
||||||
doubleHashOfToAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
# object associated with the tag for this toAddress.
|
||||||
toAddressVersionNumber) + encodeVarint(toStreamNumber) + toRipe).digest()).digest()
|
if toAddressVersionNumber >= 4:
|
||||||
privEncryptionKey = doubleHashOfToAddressData[:32] # The first half of the sha512 hash.
|
doubleHashOfToAddressData = hashlib.sha512(
|
||||||
tag = doubleHashOfToAddressData[32:] # The second half of the sha512 hash.
|
hashlib.sha512(encodeVarint(
|
||||||
state.neededPubkeys[tag] = (toaddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)))
|
toAddressVersionNumber) +
|
||||||
|
encodeVarint(toStreamNumber) +
|
||||||
|
toRipe
|
||||||
|
).digest()
|
||||||
|
).digest()
|
||||||
|
# The first half of the sha512 hash.
|
||||||
|
privEncryptionKey = doubleHashOfToAddressData[:32]
|
||||||
|
# The second half of the sha512 hash.
|
||||||
|
tag = doubleHashOfToAddressData[32:]
|
||||||
|
state.neededPubkeys[tag] = (
|
||||||
|
toaddress,
|
||||||
|
highlevelcrypto.makeCryptor(
|
||||||
|
hexlify(privEncryptionKey))
|
||||||
|
)
|
||||||
|
|
||||||
for value in Inventory().by_type_and_tag(1, toTag):
|
for value in Inventory().by_type_and_tag(1, toTag):
|
||||||
if shared.decryptAndCheckPubkeyPayload(value.payload, toaddress) == 'successful': #if valid, this function also puts it in the pubkeys table.
|
# if valid, this function also puts it
|
||||||
|
# in the pubkeys table.
|
||||||
|
if shared.decryptAndCheckPubkeyPayload(
|
||||||
|
value.payload, toaddress
|
||||||
|
) == 'successful':
|
||||||
needToRequestPubkey = False
|
needToRequestPubkey = False
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='doingmsgpow', retrynumber=0 WHERE toaddress=? AND (status='msgqueued' or status='awaitingpubkey' or status='doingpubkeypow')''',
|
'''UPDATE sent SET '''
|
||||||
|
''' status='doingmsgpow', '''
|
||||||
|
''' retrynumber=0 WHERE '''
|
||||||
|
''' toaddress=? AND '''
|
||||||
|
''' (status='msgqueued' or '''
|
||||||
|
''' status='awaitingpubkey' or '''
|
||||||
|
''' status='doingpubkeypow')''',
|
||||||
toaddress)
|
toaddress)
|
||||||
del state.neededPubkeys[tag]
|
del state.neededPubkeys[tag]
|
||||||
break
|
break
|
||||||
#else: # There was something wrong with this pubkey object even
|
# else:
|
||||||
# though it had the correct tag- almost certainly because
|
# There was something wrong with this
|
||||||
# of malicious behavior or a badly programmed client. If
|
# pubkey object even though it had
|
||||||
# there are any other pubkeys in our inventory with the correct
|
# the correct tag- almost certainly
|
||||||
# tag then we'll try to decrypt those.
|
# because of malicious behavior or
|
||||||
|
# a badly programmed client. If there are
|
||||||
|
# any other pubkeys in our inventory
|
||||||
|
# with the correct tag then we'll try
|
||||||
|
# to decrypt those.
|
||||||
if needToRequestPubkey:
|
if needToRequestPubkey:
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='doingpubkeypow' WHERE toaddress=? AND status='msgqueued' ''',
|
'''UPDATE sent SET '''
|
||||||
toaddress)
|
''' status='doingpubkeypow' WHERE '''
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByToAddress', (
|
''' toaddress=? AND status='msgqueued' ''',
|
||||||
toaddress, tr._translate("MainWindow",'Sending a request for the recipient\'s encryption key.'))))
|
toaddress
|
||||||
|
)
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByToAddress', (
|
||||||
|
toaddress,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Sending a request for the"
|
||||||
|
" recipient\'s encryption key."))
|
||||||
|
))
|
||||||
self.requestPubKey(toaddress)
|
self.requestPubKey(toaddress)
|
||||||
continue #on with the next msg on which we can do some work
|
# on with the next msg on which we can do some work
|
||||||
|
continue
|
||||||
|
|
||||||
# At this point we know that we have the necessary pubkey in the pubkeys table.
|
# At this point we know that we have the necessary pubkey
|
||||||
|
# in the pubkeys table.
|
||||||
|
|
||||||
TTL *= 2**retryNumber
|
TTL *= 2**retryNumber
|
||||||
if TTL > 28 * 24 * 60 * 60:
|
if TTL > 28 * 24 * 60 * 60:
|
||||||
TTL = 28 * 24 * 60 * 60
|
TTL = 28 * 24 * 60 * 60
|
||||||
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
|
||||||
# add some randomness to the TTL
|
# add some randomness to the TTL
|
||||||
|
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
||||||
embeddedTime = int(time.time() + TTL)
|
embeddedTime = int(time.time() + TTL)
|
||||||
|
|
||||||
if not BMConfigParser().has_section(toaddress): # if we aren't sending this to ourselves or a chan
|
# if we aren't sending this to ourselves or a chan
|
||||||
|
if not BMConfigParser().has_section(toaddress):
|
||||||
shared.ackdataForWhichImWatching[ackdata] = 0
|
shared.ackdataForWhichImWatching[ackdata] = 0
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
queues.UISignalQueue.put((
|
||||||
ackdata, tr._translate("MainWindow", "Looking up the receiver\'s public key"))))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Looking up the receiver\'s public key"))
|
||||||
|
))
|
||||||
logger.info('Sending a message.')
|
logger.info('Sending a message.')
|
||||||
logger.debug('First 150 characters of message: ' + repr(message[:150]))
|
logger.debug(
|
||||||
|
'First 150 characters of message: %s',
|
||||||
|
repr(message[:150])
|
||||||
|
)
|
||||||
|
|
||||||
# Let us fetch the recipient's public key out of our database. If
|
# Let us fetch the recipient's public key out of
|
||||||
# the required proof of work difficulty is too hard then we'll
|
# our database. If the required proof of work difficulty
|
||||||
# abort.
|
# is too hard then we'll abort.
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'SELECT transmitdata FROM pubkeys WHERE address=?',
|
'SELECT transmitdata FROM pubkeys WHERE address=?',
|
||||||
toaddress)
|
toaddress)
|
||||||
for row in queryreturn:
|
for row in queryreturn:
|
||||||
pubkeyPayload, = row
|
pubkeyPayload, = row
|
||||||
|
|
||||||
# The pubkey message is stored with the following items all appended:
|
# The pubkey message is stored with the following items
|
||||||
|
# all appended:
|
||||||
# -address version
|
# -address version
|
||||||
# -stream number
|
# -stream number
|
||||||
# -behavior bitfield
|
# -behavior bitfield
|
||||||
|
@ -658,22 +889,52 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# -nonce trials per byte (if address version is >= 3)
|
# -nonce trials per byte (if address version is >= 3)
|
||||||
# -length extra bytes (if address version is >= 3)
|
# -length extra bytes (if address version is >= 3)
|
||||||
|
|
||||||
readPosition = 1 # to bypass the address version whose length is definitely 1
|
# to bypass the address version whose length is definitely 1
|
||||||
|
readPosition = 1
|
||||||
streamNumber, streamNumberLength = decodeVarint(
|
streamNumber, streamNumberLength = decodeVarint(
|
||||||
pubkeyPayload[readPosition:readPosition + 10])
|
pubkeyPayload[readPosition:readPosition + 10])
|
||||||
readPosition += streamNumberLength
|
readPosition += streamNumberLength
|
||||||
behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4]
|
behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4]
|
||||||
# Mobile users may ask us to include their address's RIPE hash on a message
|
# Mobile users may ask us to include their address's
|
||||||
# unencrypted. Before we actually do it the sending human must check a box
|
# RIPE hash on a message unencrypted. Before we actually
|
||||||
|
# do it the sending human must check a box
|
||||||
# in the settings menu to allow it.
|
# in the settings menu to allow it.
|
||||||
if shared.isBitSetWithinBitfield(behaviorBitfield,30): # if receiver is a mobile device who expects that their address RIPE is included unencrypted on the front of the message..
|
|
||||||
if not shared.BMConfigParser().safeGetBoolean('bitmessagesettings','willinglysendtomobile'): # if we are Not willing to include the receiver's RIPE hash on the message..
|
# if receiver is a mobile device who expects that their
|
||||||
logger.info('The receiver is a mobile user but the sender (you) has not selected that you are willing to send to mobiles. Aborting send.')
|
# address RIPE is included unencrypted on the front of
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr._translate("MainWindow",'Problem: Destination is a mobile device who requests that the destination be included in the message but this is disallowed in your settings. %1').arg(l10n.formatTimestamp()))))
|
# the message..
|
||||||
# if the human changes their setting and then sends another message or restarts their client, this one will send at that time.
|
if shared.isBitSetWithinBitfield(behaviorBitfield, 30):
|
||||||
|
# if we are Not willing to include the receiver's
|
||||||
|
# RIPE hash on the message..
|
||||||
|
if not shared.BMConfigParser().safeGetBoolean(
|
||||||
|
'bitmessagesettings', 'willinglysendtomobile'
|
||||||
|
):
|
||||||
|
logger.info(
|
||||||
|
'The receiver is a mobile user but the'
|
||||||
|
' sender (you) has not selected that you'
|
||||||
|
' are willing to send to mobiles. Aborting'
|
||||||
|
' send.'
|
||||||
|
)
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Problem: Destination is a mobile"
|
||||||
|
" device who requests that the"
|
||||||
|
" destination be included in the"
|
||||||
|
" message but this is disallowed in"
|
||||||
|
" your settings. %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
|
# if the human changes their setting and then
|
||||||
|
# sends another message or restarts their client,
|
||||||
|
# this one will send at that time.
|
||||||
continue
|
continue
|
||||||
readPosition += 4 # to bypass the bitfield of behaviors
|
readPosition += 4 # to bypass the bitfield of behaviors
|
||||||
# pubSigningKeyBase256 = pubkeyPayload[readPosition:readPosition+64] # We don't use this key for anything here.
|
# We don't use this key for anything here.
|
||||||
|
# pubSigningKeyBase256 =
|
||||||
|
# pubkeyPayload[readPosition:readPosition+64]
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
pubEncryptionKeyBase256 = pubkeyPayload[
|
pubEncryptionKeyBase256 = pubkeyPayload[
|
||||||
readPosition:readPosition + 64]
|
readPosition:readPosition + 64]
|
||||||
|
@ -681,59 +942,153 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
|
|
||||||
# Let us fetch the amount of work required by the recipient.
|
# Let us fetch the amount of work required by the recipient.
|
||||||
if toAddressVersionNumber == 2:
|
if toAddressVersionNumber == 2:
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
requiredAverageProofOfWorkNonceTrialsPerByte = \
|
||||||
requiredPayloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
requiredPayloadLengthExtraBytes = \
|
||||||
ackdata, tr._translate("MainWindow", "Doing work necessary to send message.\nThere is no required difficulty for version 2 addresses like this."))))
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Doing work necessary to send message.\n"
|
||||||
|
"There is no required difficulty for"
|
||||||
|
" version 2 addresses like this."))
|
||||||
|
))
|
||||||
elif toAddressVersionNumber >= 3:
|
elif toAddressVersionNumber >= 3:
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
|
requiredAverageProofOfWorkNonceTrialsPerByte, \
|
||||||
pubkeyPayload[readPosition:readPosition + 10])
|
varintLength = decodeVarint(
|
||||||
|
pubkeyPayload[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
|
requiredPayloadLengthExtraBytes, varintLength = \
|
||||||
pubkeyPayload[readPosition:readPosition + 10])
|
decodeVarint(
|
||||||
|
pubkeyPayload[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
if requiredAverageProofOfWorkNonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte: # We still have to meet a minimum POW difficulty regardless of what they say is allowed in order to get our message to propagate through the network.
|
# We still have to meet a minimum POW difficulty
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
# regardless of what they say is allowed in order
|
||||||
if requiredPayloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes:
|
# to get our message to propagate through the network.
|
||||||
requiredPayloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
|
if requiredAverageProofOfWorkNonceTrialsPerByte < \
|
||||||
logger.debug('Using averageProofOfWorkNonceTrialsPerByte: %s and payloadLengthExtraBytes: %s.' % (requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes))
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float(
|
requiredAverageProofOfWorkNonceTrialsPerByte = \
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes)))))
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
|
if requiredPayloadLengthExtraBytes < \
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes:
|
||||||
|
requiredPayloadLengthExtraBytes = \
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
logger.debug(
|
||||||
|
'Using averageProofOfWorkNonceTrialsPerByte: %s'
|
||||||
|
' and payloadLengthExtraBytes: %s.' % (
|
||||||
|
requiredAverageProofOfWorkNonceTrialsPerByte,
|
||||||
|
requiredPayloadLengthExtraBytes
|
||||||
|
))
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Doing work necessary to send message.\n"
|
||||||
|
"Receiver\'s required difficulty: %1"
|
||||||
|
" and %2"
|
||||||
|
).arg(str(float(
|
||||||
|
requiredAverageProofOfWorkNonceTrialsPerByte) /
|
||||||
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
|
)).arg(str(float(
|
||||||
|
requiredPayloadLengthExtraBytes) /
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
)))))
|
||||||
if status != 'forcepow':
|
if status != 'forcepow':
|
||||||
if (requiredAverageProofOfWorkNonceTrialsPerByte > BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') and BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') != 0) or (requiredPayloadLengthExtraBytes > BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') and BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') != 0):
|
if (requiredAverageProofOfWorkNonceTrialsPerByte
|
||||||
# The demanded difficulty is more than we are willing
|
> BMConfigParser().getint(
|
||||||
# to do.
|
'bitmessagesettings',
|
||||||
|
'maxacceptablenoncetrialsperbyte'
|
||||||
|
) and
|
||||||
|
BMConfigParser().getint(
|
||||||
|
'bitmessagesettings',
|
||||||
|
'maxacceptablenoncetrialsperbyte'
|
||||||
|
) != 0) or (
|
||||||
|
requiredPayloadLengthExtraBytes
|
||||||
|
> BMConfigParser().getint(
|
||||||
|
'bitmessagesettings',
|
||||||
|
'maxacceptablepayloadlengthextrabytes'
|
||||||
|
) and
|
||||||
|
BMConfigParser().getint(
|
||||||
|
'bitmessagesettings',
|
||||||
|
'maxacceptablepayloadlengthextrabytes'
|
||||||
|
) != 0):
|
||||||
|
# The demanded difficulty is more than
|
||||||
|
# we are willing to do.
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''',
|
'''UPDATE sent SET status='toodifficult' '''
|
||||||
|
''' WHERE ackdata=? ''',
|
||||||
ackdata)
|
ackdata)
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do. %3").arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(
|
queues.UISignalQueue.put((
|
||||||
requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes)).arg(l10n.formatTimestamp()))))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Problem: The work demanded by"
|
||||||
|
" the recipient (%1 and %2) is"
|
||||||
|
" more difficult than you are"
|
||||||
|
" willing to do. %3"
|
||||||
|
).arg(str(float(
|
||||||
|
requiredAverageProofOfWorkNonceTrialsPerByte)
|
||||||
|
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
|
)).arg(str(float(
|
||||||
|
requiredPayloadLengthExtraBytes)
|
||||||
|
/ defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
)).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
continue
|
continue
|
||||||
else: # if we are sending a message to ourselves or a chan..
|
else: # if we are sending a message to ourselves or a chan..
|
||||||
logger.info('Sending a message.')
|
logger.info('Sending a message.')
|
||||||
logger.debug('First 150 characters of message: ' + repr(message[:150]))
|
logger.debug(
|
||||||
|
'First 150 characters of message: %r', message[:150])
|
||||||
behaviorBitfield = protocol.getBitfield(fromaddress)
|
behaviorBitfield = protocol.getBitfield(fromaddress)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
toaddress, 'privencryptionkey')
|
toaddress, 'privencryptionkey')
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr._translate("MainWindow",'Problem: You are trying to send a message to yourself or a chan but your encryption key could not be found in the keys.dat file. Could not encrypt message. %1').arg(l10n.formatTimestamp()))))
|
queues.UISignalQueue.put((
|
||||||
logger.error('Error within sendMsg. Could not read the keys from the keys.dat file for our own address. %s\n' % err)
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Problem: You are trying to send a"
|
||||||
|
" message to yourself or a chan but your"
|
||||||
|
" encryption key could not be found in"
|
||||||
|
" the keys.dat file. Could not encrypt"
|
||||||
|
" message. %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
)) # log or show the address maybe?
|
||||||
|
logger.error(
|
||||||
|
'Error within sendMsg. Could not read the keys'
|
||||||
|
' from the keys.dat file for our own address. %s\n'
|
||||||
|
% err)
|
||||||
continue
|
continue
|
||||||
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privEncryptionKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
privEncryptionKeyBase58))
|
privEncryptionKeyBase58))
|
||||||
pubEncryptionKeyBase256 = unhexlify(highlevelcrypto.privToPub(
|
pubEncryptionKeyBase256 = unhexlify(highlevelcrypto.privToPub(
|
||||||
privEncryptionKeyHex))[1:]
|
privEncryptionKeyHex))[1:]
|
||||||
requiredAverageProofOfWorkNonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
requiredAverageProofOfWorkNonceTrialsPerByte = \
|
||||||
requiredPayloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
requiredPayloadLengthExtraBytes = \
|
||||||
ackdata, tr._translate("MainWindow", "Doing work necessary to send message."))))
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Doing work necessary to send message."))
|
||||||
|
))
|
||||||
|
|
||||||
# Now we can start to assemble our message.
|
# Now we can start to assemble our message.
|
||||||
payload = encodeVarint(fromAddressVersionNumber)
|
payload = encodeVarint(fromAddressVersionNumber)
|
||||||
payload += encodeVarint(fromStreamNumber)
|
payload += encodeVarint(fromStreamNumber)
|
||||||
payload += protocol.getBitfield(fromaddress) # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features )
|
# Bitfield of features and behaviors
|
||||||
|
# that can be expected from me. (See
|
||||||
|
# https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features)
|
||||||
|
payload += protocol.getBitfield(fromaddress)
|
||||||
|
|
||||||
# We need to convert our private keys to public keys in order
|
# We need to convert our private keys to public keys in order
|
||||||
# to include them.
|
# to include them.
|
||||||
|
@ -743,8 +1098,14 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
privEncryptionKeyBase58 = BMConfigParser().get(
|
privEncryptionKeyBase58 = BMConfigParser().get(
|
||||||
fromaddress, 'privencryptionkey')
|
fromaddress, 'privencryptionkey')
|
||||||
except:
|
except:
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
|
queues.UISignalQueue.put((
|
||||||
ackdata, tr._translate("MainWindow", "Error! Could not find sender address (your address) in the keys.dat file."))))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Error! Could not find sender address"
|
||||||
|
" (your address) in the keys.dat file."))
|
||||||
|
))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
privSigningKeyHex = hexlify(shared.decodeWalletImportFormat(
|
||||||
|
@ -757,8 +1118,10 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
pubEncryptionKey = unhexlify(highlevelcrypto.privToPub(
|
pubEncryptionKey = unhexlify(highlevelcrypto.privToPub(
|
||||||
privEncryptionKeyHex))
|
privEncryptionKeyHex))
|
||||||
|
|
||||||
payload += pubSigningKey[
|
# The \x04 on the beginning of the public keys are not sent.
|
||||||
1:] # The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key.
|
# This way there is only one acceptable way to encode
|
||||||
|
# and send a public key.
|
||||||
|
payload += pubSigningKey[1:]
|
||||||
payload += pubEncryptionKey[1:]
|
payload += pubEncryptionKey[1:]
|
||||||
|
|
||||||
if fromAddressVersionNumber >= 3:
|
if fromAddressVersionNumber >= 3:
|
||||||
|
@ -766,7 +1129,8 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# subscriptions list, or whitelist then we will allow them to
|
# subscriptions list, or whitelist then we will allow them to
|
||||||
# do the network-minimum proof of work. Let us check to see if
|
# do the network-minimum proof of work. Let us check to see if
|
||||||
# the receiver is in any of those lists.
|
# the receiver is in any of those lists.
|
||||||
if shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(toaddress):
|
if shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(
|
||||||
|
toaddress):
|
||||||
payload += encodeVarint(
|
payload += encodeVarint(
|
||||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
|
||||||
payload += encodeVarint(
|
payload += encodeVarint(
|
||||||
|
@ -777,91 +1141,171 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
payload += encodeVarint(BMConfigParser().getint(
|
payload += encodeVarint(BMConfigParser().getint(
|
||||||
fromaddress, 'payloadlengthextrabytes'))
|
fromaddress, 'payloadlengthextrabytes'))
|
||||||
|
|
||||||
payload += toRipe # This hash will be checked by the receiver of the message to verify that toRipe belongs to them. This prevents a Surreptitious Forwarding Attack.
|
# This hash will be checked by the receiver of the message
|
||||||
payload += encodeVarint(encoding) # message encoding type
|
# to verify that toRipe belongs to them. This prevents
|
||||||
encodedMessage = helper_msgcoding.MsgEncode({"subject": subject, "body": message}, encoding)
|
# a Surreptitious Forwarding Attack.
|
||||||
|
payload += toRipe
|
||||||
|
payload += encodeVarint(encoding) # message encoding type
|
||||||
|
encodedMessage = helper_msgcoding.MsgEncode(
|
||||||
|
{"subject": subject, "body": message}, encoding
|
||||||
|
)
|
||||||
payload += encodeVarint(encodedMessage.length)
|
payload += encodeVarint(encodedMessage.length)
|
||||||
payload += encodedMessage.data
|
payload += encodedMessage.data
|
||||||
if BMConfigParser().has_section(toaddress):
|
if BMConfigParser().has_section(toaddress):
|
||||||
logger.info('Not bothering to include ackdata because we are sending to ourselves or a chan.')
|
logger.info(
|
||||||
|
'Not bothering to include ackdata because we are'
|
||||||
|
' sending to ourselves or a chan.'
|
||||||
|
)
|
||||||
fullAckPayload = ''
|
fullAckPayload = ''
|
||||||
elif not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
|
elif not protocol.checkBitfield(
|
||||||
logger.info('Not bothering to include ackdata because the receiver said that they won\'t relay it anyway.')
|
behaviorBitfield, protocol.BITFIELD_DOESACK):
|
||||||
|
logger.info(
|
||||||
|
'Not bothering to include ackdata because'
|
||||||
|
' the receiver said that they won\'t relay it anyway.'
|
||||||
|
)
|
||||||
fullAckPayload = ''
|
fullAckPayload = ''
|
||||||
else:
|
else:
|
||||||
|
# The fullAckPayload is a normal msg protocol message
|
||||||
|
# with the proof of work already completed that the
|
||||||
|
# receiver of this message can easily send out.
|
||||||
fullAckPayload = self.generateFullAckMessage(
|
fullAckPayload = self.generateFullAckMessage(
|
||||||
ackdata, toStreamNumber, TTL) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out.
|
ackdata, toStreamNumber, TTL)
|
||||||
payload += encodeVarint(len(fullAckPayload))
|
payload += encodeVarint(len(fullAckPayload))
|
||||||
payload += fullAckPayload
|
payload += fullAckPayload
|
||||||
dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02' + encodeVarint(1) + encodeVarint(toStreamNumber) + payload
|
dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02' + \
|
||||||
|
encodeVarint(1) + encodeVarint(toStreamNumber) + payload
|
||||||
signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex)
|
signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex)
|
||||||
payload += encodeVarint(len(signature))
|
payload += encodeVarint(len(signature))
|
||||||
payload += signature
|
payload += signature
|
||||||
|
|
||||||
# We have assembled the data that will be encrypted.
|
# We have assembled the data that will be encrypted.
|
||||||
try:
|
try:
|
||||||
encrypted = highlevelcrypto.encrypt(payload,"04"+hexlify(pubEncryptionKeyBase256))
|
encrypted = highlevelcrypto.encrypt(
|
||||||
|
payload, "04" + hexlify(pubEncryptionKeyBase256)
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
sqlExecute('''UPDATE sent SET status='badkey' WHERE ackdata=?''', ackdata)
|
sqlExecute(
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr._translate("MainWindow",'Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1').arg(l10n.formatTimestamp()))))
|
'''UPDATE sent SET status='badkey' WHERE ackdata=?''',
|
||||||
|
ackdata
|
||||||
|
)
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Problem: The recipient\'s encryption key is"
|
||||||
|
" no good. Could not encrypt message. %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
encryptedPayload = pack('>Q', embeddedTime)
|
encryptedPayload = pack('>Q', embeddedTime)
|
||||||
encryptedPayload += '\x00\x00\x00\x02' # object type: msg
|
encryptedPayload += '\x00\x00\x00\x02' # object type: msg
|
||||||
encryptedPayload += encodeVarint(1) # msg version
|
encryptedPayload += encodeVarint(1) # msg version
|
||||||
encryptedPayload += encodeVarint(toStreamNumber) + encrypted
|
encryptedPayload += encodeVarint(toStreamNumber) + encrypted
|
||||||
target = 2 ** 64 / (requiredAverageProofOfWorkNonceTrialsPerByte*(len(encryptedPayload) + 8 + requiredPayloadLengthExtraBytes + ((TTL*(len(encryptedPayload)+8+requiredPayloadLengthExtraBytes))/(2 ** 16))))
|
target = 2 ** 64 / (
|
||||||
logger.info('(For msg message) Doing proof of work. Total required difficulty: %f. Required small message difficulty: %f.', float(requiredAverageProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte, float(requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes)
|
requiredAverageProofOfWorkNonceTrialsPerByte * (
|
||||||
|
len(encryptedPayload) + 8 +
|
||||||
|
requiredPayloadLengthExtraBytes + ((
|
||||||
|
TTL * (
|
||||||
|
len(encryptedPayload) + 8 +
|
||||||
|
requiredPayloadLengthExtraBytes
|
||||||
|
)) / (2 ** 16))
|
||||||
|
))
|
||||||
|
logger.info(
|
||||||
|
'(For msg message) Doing proof of work. Total required'
|
||||||
|
' difficulty: %f. Required small message difficulty: %f.',
|
||||||
|
float(requiredAverageProofOfWorkNonceTrialsPerByte) /
|
||||||
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
|
||||||
|
float(requiredPayloadLengthExtraBytes) /
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
)
|
||||||
|
|
||||||
powStartTime = time.time()
|
powStartTime = time.time()
|
||||||
initialHash = hashlib.sha512(encryptedPayload).digest()
|
initialHash = hashlib.sha512(encryptedPayload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
logger.info('(For msg message) Found proof of work ' + str(trialValue) + ' Nonce: ' + str(nonce))
|
logger.info(
|
||||||
|
'(For msg message) Found proof of work %s Nonce: %s',
|
||||||
|
trialValue, nonce
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
logger.info('PoW took %.1f seconds, speed %s.', time.time() - powStartTime, sizeof_fmt(nonce / (time.time() - powStartTime)))
|
logger.info(
|
||||||
|
'PoW took %.1f seconds, speed %s.',
|
||||||
|
time.time() - powStartTime,
|
||||||
|
sizeof_fmt(nonce / (time.time() - powStartTime))
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
encryptedPayload = pack('>Q', nonce) + encryptedPayload
|
encryptedPayload = pack('>Q', nonce) + encryptedPayload
|
||||||
|
|
||||||
# Sanity check. The encryptedPayload size should never be larger than 256 KiB. There should
|
# Sanity check. The encryptedPayload size should never be
|
||||||
# be checks elsewhere in the code to not let the user try to send a message this large
|
# larger than 256 KiB. There should be checks elsewhere
|
||||||
# until we implement message continuation.
|
# in the code to not let the user try to send a message
|
||||||
if len(encryptedPayload) > 2 ** 18: # 256 KiB
|
# this large until we implement message continuation.
|
||||||
logger.critical('This msg object is too large to send. This should never happen. Object size: %s' % len(encryptedPayload))
|
if len(encryptedPayload) > 2 ** 18: # 256 KiB
|
||||||
|
logger.critical(
|
||||||
|
'This msg object is too large to send. This should'
|
||||||
|
' never happen. Object size: %i',
|
||||||
|
len(encryptedPayload)
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
inventoryHash = calculateInventoryHash(encryptedPayload)
|
inventoryHash = calculateInventoryHash(encryptedPayload)
|
||||||
objectType = 2
|
objectType = 2
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, toStreamNumber, encryptedPayload, embeddedTime, '')
|
objectType, toStreamNumber, encryptedPayload, embeddedTime, '')
|
||||||
if BMConfigParser().has_section(toaddress) or not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
|
if BMConfigParser().has_section(toaddress) or \
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Message sent. Sent at %1").arg(l10n.formatTimestamp()))))
|
not protocol.checkBitfield(
|
||||||
|
behaviorBitfield, protocol.BITFIELD_DOESACK):
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Message sent. Sent at %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
else:
|
else:
|
||||||
# not sending to a chan or one of my addresses
|
# not sending to a chan or one of my addresses
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Message sent. Waiting for acknowledgement. Sent on %1").arg(l10n.formatTimestamp()))))
|
queues.UISignalQueue.put((
|
||||||
logger.info('Broadcasting inv for my msg(within sendmsg function):' + hexlify(inventoryHash))
|
'updateSentItemStatusByAckdata', (
|
||||||
|
ackdata,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Message sent. Waiting for acknowledgement."
|
||||||
|
" Sent on %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
|
logger.info(
|
||||||
|
'Broadcasting inv for my msg(within sendmsg function): %s',
|
||||||
|
hexlify(inventoryHash)
|
||||||
|
)
|
||||||
queues.invQueue.put((toStreamNumber, inventoryHash))
|
queues.invQueue.put((toStreamNumber, inventoryHash))
|
||||||
|
|
||||||
# Update the sent message in the sent table with the necessary information.
|
# Update the sent message in the sent table with the
|
||||||
if BMConfigParser().has_section(toaddress) or not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
|
# necessary information.
|
||||||
|
if BMConfigParser().has_section(toaddress) or \
|
||||||
|
not protocol.checkBitfield(
|
||||||
|
behaviorBitfield, protocol.BITFIELD_DOESACK):
|
||||||
newStatus = 'msgsentnoackexpected'
|
newStatus = 'msgsentnoackexpected'
|
||||||
else:
|
else:
|
||||||
newStatus = 'msgsent'
|
newStatus = 'msgsent'
|
||||||
# wait 10% past expiration
|
# wait 10% past expiration
|
||||||
sleepTill = int(time.time() + TTL * 1.1)
|
sleepTill = int(time.time() + TTL * 1.1)
|
||||||
sqlExecute('''UPDATE sent SET msgid=?, status=?, retrynumber=?, sleeptill=?, lastactiontime=? WHERE ackdata=?''',
|
sqlExecute(
|
||||||
inventoryHash,
|
'''UPDATE sent SET msgid=?, status=?, retrynumber=?, '''
|
||||||
newStatus,
|
''' sleeptill=?, lastactiontime=? WHERE ackdata=?''',
|
||||||
retryNumber+1,
|
inventoryHash, newStatus, retryNumber + 1,
|
||||||
sleepTill,
|
sleepTill, int(time.time()), ackdata
|
||||||
int(time.time()),
|
)
|
||||||
ackdata)
|
|
||||||
|
|
||||||
# If we are sending to ourselves or a chan, let's put the message in
|
# If we are sending to ourselves or a chan, let's put
|
||||||
# our own inbox.
|
# the message in our own inbox.
|
||||||
if BMConfigParser().has_section(toaddress):
|
if BMConfigParser().has_section(toaddress):
|
||||||
sigHash = hashlib.sha512(hashlib.sha512(signature).digest()).digest()[32:] # Used to detect and ignore duplicate messages in our inbox
|
# Used to detect and ignore duplicate messages in our inbox
|
||||||
|
sigHash = hashlib.sha512(hashlib.sha512(
|
||||||
|
signature).digest()).digest()[32:]
|
||||||
t = (inventoryHash, toaddress, fromaddress, subject, int(
|
t = (inventoryHash, toaddress, fromaddress, subject, int(
|
||||||
time.time()), message, 'inbox', encoding, 0, sigHash)
|
time.time()), message, 'inbox', encoding, 0, sigHash)
|
||||||
helper_inbox.insert(t)
|
helper_inbox.insert(t)
|
||||||
|
@ -872,7 +1316,8 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# If we are behaving as an API then we might need to run an
|
# If we are behaving as an API then we might need to run an
|
||||||
# outside command to let some program know that a new message
|
# outside command to let some program know that a new message
|
||||||
# has arrived.
|
# has arrived.
|
||||||
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
|
if BMConfigParser().safeGetBoolean(
|
||||||
|
'bitmessagesettings', 'apienabled'):
|
||||||
try:
|
try:
|
||||||
apiNotifyPath = BMConfigParser().get(
|
apiNotifyPath = BMConfigParser().get(
|
||||||
'bitmessagesettings', 'apinotifypath')
|
'bitmessagesettings', 'apinotifypath')
|
||||||
|
@ -885,56 +1330,102 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress(
|
toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress(
|
||||||
toAddress)
|
toAddress)
|
||||||
if toStatus != 'success':
|
if toStatus != 'success':
|
||||||
logger.error('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr(
|
logger.error(
|
||||||
toAddress) + '. Please report this error to Atheros.')
|
'Very abnormal error occurred in requestPubKey.'
|
||||||
|
' toAddress is: %r. Please report this error to Atheros.',
|
||||||
|
toAddress
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
queryReturn = sqlQuery(
|
queryReturn = sqlQuery(
|
||||||
'''SELECT retrynumber FROM sent WHERE toaddress=? AND (status='doingpubkeypow' OR status='awaitingpubkey') LIMIT 1''',
|
'''SELECT retrynumber FROM sent WHERE toaddress=? '''
|
||||||
toAddress)
|
''' AND (status='doingpubkeypow' OR status='awaitingpubkey') '''
|
||||||
|
''' LIMIT 1''',
|
||||||
|
toAddress
|
||||||
|
)
|
||||||
if len(queryReturn) == 0:
|
if len(queryReturn) == 0:
|
||||||
logger.critical("BUG: Why are we requesting the pubkey for %s if there are no messages in the sent folder to that address?" % toAddress)
|
logger.critical(
|
||||||
|
'BUG: Why are we requesting the pubkey for %s'
|
||||||
|
' if there are no messages in the sent folder'
|
||||||
|
' to that address?', toAddress
|
||||||
|
)
|
||||||
return
|
return
|
||||||
retryNumber = queryReturn[0][0]
|
retryNumber = queryReturn[0][0]
|
||||||
|
|
||||||
if addressVersionNumber <= 3:
|
if addressVersionNumber <= 3:
|
||||||
state.neededPubkeys[toAddress] = 0
|
state.neededPubkeys[toAddress] = 0
|
||||||
elif addressVersionNumber >= 4:
|
elif addressVersionNumber >= 4:
|
||||||
# If the user just clicked 'send' then the tag (and other information) will already
|
# If the user just clicked 'send' then the tag
|
||||||
# be in the neededPubkeys dictionary. But if we are recovering from a restart
|
# (and other information) will already be in the
|
||||||
# of the client then we have to put it in now.
|
# neededPubkeys dictionary. But if we are recovering
|
||||||
privEncryptionKey = hashlib.sha512(hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+ripe).digest()).digest()[:32] # Note that this is the first half of the sha512 hash.
|
# from a restart of the client then we have to put it in now.
|
||||||
tag = hashlib.sha512(hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+ripe).digest()).digest()[32:] # Note that this is the second half of the sha512 hash.
|
|
||||||
if tag not in state.neededPubkeys:
|
|
||||||
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.
|
|
||||||
|
|
||||||
TTL = 2.5*24*60*60 # 2.5 days. This was chosen fairly arbitrarily.
|
# Note that this is the first half of the sha512 hash.
|
||||||
TTL *= 2**retryNumber
|
privEncryptionKey = hashlib.sha512(hashlib.sha512(
|
||||||
if TTL > 28*24*60*60:
|
encodeVarint(addressVersionNumber) +
|
||||||
TTL = 28*24*60*60
|
encodeVarint(streamNumber) + ripe
|
||||||
TTL = TTL + helper_random.randomrandrange(-300, 300)# add some randomness to the TTL
|
).digest()).digest()[:32]
|
||||||
|
# Note that this is the second half of the sha512 hash.
|
||||||
|
tag = hashlib.sha512(hashlib.sha512(
|
||||||
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + ripe
|
||||||
|
).digest()).digest()[32:]
|
||||||
|
if tag not in state.neededPubkeys:
|
||||||
|
# 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))
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2.5 days. This was chosen fairly arbitrarily.
|
||||||
|
TTL = 2.5 * 24 * 60 * 60
|
||||||
|
TTL *= 2 ** retryNumber
|
||||||
|
if TTL > 28 * 24 * 60 * 60:
|
||||||
|
TTL = 28 * 24 * 60 * 60
|
||||||
|
# add some randomness to the TTL
|
||||||
|
TTL = TTL + helper_random.randomrandrange(-300, 300)
|
||||||
embeddedTime = int(time.time() + TTL)
|
embeddedTime = int(time.time() + TTL)
|
||||||
payload = pack('>Q', embeddedTime)
|
payload = pack('>Q', embeddedTime)
|
||||||
payload += '\x00\x00\x00\x00' # object type: getpubkey
|
payload += '\x00\x00\x00\x00' # object type: getpubkey
|
||||||
payload += encodeVarint(addressVersionNumber)
|
payload += encodeVarint(addressVersionNumber)
|
||||||
payload += encodeVarint(streamNumber)
|
payload += encodeVarint(streamNumber)
|
||||||
if addressVersionNumber <= 3:
|
if addressVersionNumber <= 3:
|
||||||
payload += ripe
|
payload += ripe
|
||||||
logger.info('making request for pubkey with ripe: %s', hexlify(ripe))
|
logger.info(
|
||||||
|
'making request for pubkey with ripe: %s', hexlify(ripe))
|
||||||
else:
|
else:
|
||||||
payload += tag
|
payload += tag
|
||||||
logger.info('making request for v4 pubkey with tag: %s', hexlify(tag))
|
logger.info(
|
||||||
|
'making request for v4 pubkey with tag: %s', hexlify(tag))
|
||||||
|
|
||||||
# print 'trial value', trialValue
|
# print 'trial value', trialValue
|
||||||
statusbar = 'Doing the computations necessary to request the recipient\'s public key.'
|
statusbar = 'Doing the computations necessary to request' +\
|
||||||
|
' the recipient\'s public key.'
|
||||||
queues.UISignalQueue.put(('updateStatusBar', statusbar))
|
queues.UISignalQueue.put(('updateStatusBar', statusbar))
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByToAddress', (
|
queues.UISignalQueue.put((
|
||||||
toAddress, tr._translate("MainWindow",'Doing work necessary to request encryption key.'))))
|
'updateSentItemStatusByToAddress', (
|
||||||
|
toAddress,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Doing work necessary to request encryption key."))
|
||||||
|
))
|
||||||
|
|
||||||
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))
|
||||||
|
))
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
logger.info('Found proof of work ' + str(trialValue) + ' Nonce: ' + str(nonce))
|
logger.info(
|
||||||
|
'Found proof of work %s Nonce: %s',
|
||||||
|
trialValue, nonce
|
||||||
|
)
|
||||||
|
|
||||||
payload = pack('>Q', nonce) + payload
|
payload = pack('>Q', nonce) + payload
|
||||||
inventoryHash = calculateInventoryHash(payload)
|
inventoryHash = calculateInventoryHash(payload)
|
||||||
|
@ -947,18 +1438,30 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# wait 10% past expiration
|
# wait 10% past expiration
|
||||||
sleeptill = int(time.time() + TTL * 1.1)
|
sleeptill = int(time.time() + TTL * 1.1)
|
||||||
sqlExecute(
|
sqlExecute(
|
||||||
'''UPDATE sent SET lastactiontime=?, status='awaitingpubkey', retrynumber=?, sleeptill=? WHERE toaddress=? AND (status='doingpubkeypow' OR status='awaitingpubkey') ''',
|
'''UPDATE sent SET lastactiontime=?, '''
|
||||||
int(time.time()),
|
''' status='awaitingpubkey', retrynumber=?, sleeptill=? '''
|
||||||
retryNumber+1,
|
''' WHERE toaddress=? AND (status='doingpubkeypow' OR '''
|
||||||
sleeptill,
|
''' status='awaitingpubkey') ''',
|
||||||
toAddress)
|
int(time.time()), retryNumber + 1, sleeptill, toAddress)
|
||||||
|
|
||||||
queues.UISignalQueue.put((
|
queues.UISignalQueue.put((
|
||||||
'updateStatusBar', tr._translate("MainWindow",'Broadcasting the public key request. This program will auto-retry if they are offline.')))
|
'updateStatusBar',
|
||||||
queues.UISignalQueue.put(('updateSentItemStatusByToAddress', (toAddress, tr._translate("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(l10n.formatTimestamp()))))
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Broadcasting the public key request. This program will"
|
||||||
|
" auto-retry if they are offline.")
|
||||||
|
))
|
||||||
|
queues.UISignalQueue.put((
|
||||||
|
'updateSentItemStatusByToAddress', (
|
||||||
|
toAddress,
|
||||||
|
tr._translate(
|
||||||
|
"MainWindow",
|
||||||
|
"Sending public key request. Waiting for reply."
|
||||||
|
" Requested at %1"
|
||||||
|
).arg(l10n.formatTimestamp()))
|
||||||
|
))
|
||||||
|
|
||||||
def generateFullAckMessage(self, ackdata, toStreamNumber, TTL):
|
def generateFullAckMessage(self, ackdata, toStreamNumber, TTL):
|
||||||
|
|
||||||
# It might be perfectly fine to just use the same TTL for
|
# It might be perfectly fine to just use the same TTL for
|
||||||
# the ackdata that we use for the message. But I would rather
|
# the ackdata that we use for the message. But I would rather
|
||||||
# it be more difficult for attackers to associate ackData with
|
# it be more difficult for attackers to associate ackData with
|
||||||
|
@ -968,28 +1471,44 @@ class singleWorker(threading.Thread, StoppableThread):
|
||||||
# acknowledgement to be in one of three 'buckets': 1 hour, 7
|
# acknowledgement to be in one of three 'buckets': 1 hour, 7
|
||||||
# days, or 28 days, whichever is relatively close to what the
|
# days, or 28 days, whichever is relatively close to what the
|
||||||
# user specified.
|
# user specified.
|
||||||
if TTL < 24*60*60: # 1 day
|
if TTL < 24 * 60 * 60: # 1 day
|
||||||
TTL = 24*60*60 # 1 day
|
TTL = 24 * 60 * 60 # 1 day
|
||||||
elif TTL < 7*24*60*60: # 1 week
|
elif TTL < 7 * 24 * 60 * 60: # 1 week
|
||||||
TTL = 7*24*60*60 # 1 week
|
TTL = 7 * 24 * 60 * 60 # 1 week
|
||||||
else:
|
else:
|
||||||
TTL = 28*24*60*60 # 4 weeks
|
TTL = 28 * 24 * 60 * 60 # 4 weeks
|
||||||
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
|
||||||
# Add some randomness to the TTL
|
# Add some randomness to the TTL
|
||||||
|
TTL = int(TTL + helper_random.randomrandrange(-300, 300))
|
||||||
embeddedTime = int(time.time() + TTL)
|
embeddedTime = int(time.time() + TTL)
|
||||||
|
|
||||||
# type/version/stream already included
|
# type/version/stream already included
|
||||||
payload = pack('>Q', (embeddedTime)) + ackdata
|
payload = pack('>Q', (embeddedTime)) + ackdata
|
||||||
|
|
||||||
target = 2 ** 64 / (defaults.networkDefaultProofOfWorkNonceTrialsPerByte*(len(payload) + 8 + defaults.networkDefaultPayloadLengthExtraBytes + ((TTL*(len(payload)+8+defaults.networkDefaultPayloadLengthExtraBytes))/(2 ** 16))))
|
target = 2 ** 64 / (
|
||||||
logger.info('(For ack message) Doing proof of work. TTL set to ' + str(TTL))
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * (
|
||||||
|
len(payload) + 8 +
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes + ((
|
||||||
|
TTL * (
|
||||||
|
len(payload) + 8 +
|
||||||
|
defaults.networkDefaultPayloadLengthExtraBytes
|
||||||
|
)) / (2 ** 16))
|
||||||
|
))
|
||||||
|
logger.info(
|
||||||
|
'(For ack message) Doing proof of work. TTL set to %s', TTL)
|
||||||
|
|
||||||
powStartTime = time.time()
|
powStartTime = time.time()
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
logger.info('(For ack message) Found proof of work ' + str(trialValue) + ' Nonce: ' + str(nonce))
|
logger.info(
|
||||||
|
'(For ack message) Found proof of work %s Nonce: %s',
|
||||||
|
trialValue, nonce
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
logger.info('PoW took %.1f seconds, speed %s.', time.time() - powStartTime, sizeof_fmt(nonce / (time.time() - powStartTime)))
|
logger.info(
|
||||||
|
'PoW took %.1f seconds, speed %s.',
|
||||||
|
time.time() - powStartTime,
|
||||||
|
sizeof_fmt(nonce / (time.time() - powStartTime))
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
513
src/shared.py
513
src/shared.py
|
@ -1,105 +1,148 @@
|
||||||
from __future__ import division
|
from __future__ import division
|
||||||
|
|
||||||
verbose = 1
|
|
||||||
maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # This is obsolete with the change to protocol v3 but the singleCleaner thread still hasn't been updated so we need this a little longer.
|
|
||||||
lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time.
|
|
||||||
maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours
|
|
||||||
useVeryEasyProofOfWorkForTesting = False # If you set this to True while on the normal network, you won't be able to send or sometimes receive messages.
|
|
||||||
|
|
||||||
|
|
||||||
# Libraries.
|
# Libraries.
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import stat
|
import stat
|
||||||
import threading
|
|
||||||
import time
|
import time
|
||||||
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
|
import hashlib
|
||||||
|
import subprocess
|
||||||
|
from struct import unpack
|
||||||
from binascii import hexlify
|
from binascii import hexlify
|
||||||
|
from pyelliptic import arithmetic
|
||||||
|
|
||||||
# Project imports.
|
# Project imports.
|
||||||
from addresses import *
|
|
||||||
from bmconfigparser import BMConfigParser
|
|
||||||
import highlevelcrypto
|
|
||||||
#import helper_startup
|
|
||||||
from helper_sql import *
|
|
||||||
from inventory import Inventory
|
|
||||||
from queues import objectProcessorQueue
|
|
||||||
import protocol
|
import protocol
|
||||||
import state
|
import state
|
||||||
|
import highlevelcrypto
|
||||||
|
from bmconfigparser import BMConfigParser
|
||||||
|
from debug import logger
|
||||||
|
from addresses import (
|
||||||
|
decodeAddress, encodeVarint, decodeVarint, varintDecodeError,
|
||||||
|
calculateInventoryHash
|
||||||
|
)
|
||||||
|
from helper_sql import sqlQuery, sqlExecute
|
||||||
|
from inventory import Inventory
|
||||||
|
from queues import objectProcessorQueue
|
||||||
|
|
||||||
|
|
||||||
|
verbose = 1
|
||||||
|
# This is obsolete with the change to protocol v3
|
||||||
|
# but the singleCleaner thread still hasn't been updated
|
||||||
|
# so we need this a little longer.
|
||||||
|
maximumAgeOfAnObjectThatIAmWillingToAccept = 216000
|
||||||
|
# Equals 4 weeks. You could make this longer if you want
|
||||||
|
# but making it shorter would not be advisable because
|
||||||
|
# there is a very small possibility that it could keep you
|
||||||
|
# from obtaining a needed pubkey for a period of time.
|
||||||
|
lengthOfTimeToHoldOnToAllPubkeys = 2419200
|
||||||
|
maximumAgeOfNodesThatIAdvertiseToOthers = 10800 # Equals three hours
|
||||||
|
# If you set this to True while on the normal network,
|
||||||
|
# you won't be able to send or sometimes receive messages.
|
||||||
|
useVeryEasyProofOfWorkForTesting = False
|
||||||
|
|
||||||
|
|
||||||
myECCryptorObjects = {}
|
myECCryptorObjects = {}
|
||||||
MyECSubscriptionCryptorObjects = {}
|
MyECSubscriptionCryptorObjects = {}
|
||||||
myAddressesByHash = {} #The key in this dictionary is the RIPE hash which is encoded in an address and value is the address itself.
|
# The key in this dictionary is the RIPE hash which is encoded
|
||||||
myAddressesByTag = {} # The key in this dictionary is the tag generated from the address.
|
# in an address and value is the address itself.
|
||||||
|
myAddressesByHash = {}
|
||||||
|
# The key in this dictionary is the tag generated from the address.
|
||||||
|
myAddressesByTag = {}
|
||||||
broadcastSendersForWhichImWatching = {}
|
broadcastSendersForWhichImWatching = {}
|
||||||
printLock = threading.Lock()
|
printLock = threading.Lock()
|
||||||
statusIconColor = 'red'
|
statusIconColor = 'red'
|
||||||
connectedHostsList = {} #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice.
|
# List of hosts to which we are connected. Used to guarantee
|
||||||
thisapp = None # singleton lock instance
|
# that the outgoingSynSender threads won't connect to the same
|
||||||
|
# remote node twice.
|
||||||
|
connectedHostsList = {}
|
||||||
|
thisapp = None # singleton lock instance
|
||||||
alreadyAttemptedConnectionsList = {
|
alreadyAttemptedConnectionsList = {
|
||||||
} # This is a list of nodes to which we have already attempted a connection
|
} # This is a list of nodes to which we have already attempted a connection
|
||||||
alreadyAttemptedConnectionsListLock = threading.Lock()
|
alreadyAttemptedConnectionsListLock = threading.Lock()
|
||||||
alreadyAttemptedConnectionsListResetTime = int(
|
# used to clear out the alreadyAttemptedConnectionsList periodically
|
||||||
time.time()) # used to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect.
|
# so that we will retry connecting to hosts to which we have already
|
||||||
successfullyDecryptMessageTimings = [
|
# tried to connect.
|
||||||
] # A list of the amounts of time it took to successfully decrypt msg messages
|
alreadyAttemptedConnectionsListResetTime = int(time.time())
|
||||||
|
# A list of the amounts of time it took to successfully decrypt msg messages
|
||||||
|
successfullyDecryptMessageTimings = []
|
||||||
ackdataForWhichImWatching = {}
|
ackdataForWhichImWatching = {}
|
||||||
clientHasReceivedIncomingConnections = False #used by API command clientStatus
|
# used by API command clientStatus
|
||||||
|
clientHasReceivedIncomingConnections = False
|
||||||
numberOfMessagesProcessed = 0
|
numberOfMessagesProcessed = 0
|
||||||
numberOfBroadcastsProcessed = 0
|
numberOfBroadcastsProcessed = 0
|
||||||
numberOfPubkeysProcessed = 0
|
numberOfPubkeysProcessed = 0
|
||||||
|
|
||||||
needToWriteKnownNodesToDisk = False # If True, the singleCleaner will write it to disk eventually.
|
# If True, the singleCleaner will write it to disk eventually.
|
||||||
|
needToWriteKnownNodesToDisk = False
|
||||||
|
|
||||||
maximumLengthOfTimeToBotherResendingMessages = 0
|
maximumLengthOfTimeToBotherResendingMessages = 0
|
||||||
timeOffsetWrongCount = 0
|
timeOffsetWrongCount = 0
|
||||||
|
|
||||||
|
|
||||||
def isAddressInMyAddressBook(address):
|
def isAddressInMyAddressBook(address):
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'''select address from addressbook where address=?''',
|
'''select address from addressbook where address=?''',
|
||||||
address)
|
address)
|
||||||
return queryreturn != []
|
return queryreturn != []
|
||||||
|
|
||||||
#At this point we should really just have a isAddressInMy(book, address)...
|
|
||||||
|
# At this point we should really just have a isAddressInMy(book, address)...
|
||||||
def isAddressInMySubscriptionsList(address):
|
def isAddressInMySubscriptionsList(address):
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'''select * from subscriptions where address=?''',
|
'''select * from subscriptions where address=?''',
|
||||||
str(address))
|
str(address))
|
||||||
return queryreturn != []
|
return queryreturn != []
|
||||||
|
|
||||||
|
|
||||||
def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
|
def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
|
||||||
if isAddressInMyAddressBook(address):
|
if isAddressInMyAddressBook(address):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
queryreturn = sqlQuery('''SELECT address FROM whitelist where address=? and enabled = '1' ''', address)
|
queryreturn = sqlQuery(
|
||||||
if queryreturn <> []:
|
'''SELECT address FROM whitelist where address=?'''
|
||||||
|
''' and enabled = '1' ''',
|
||||||
|
address)
|
||||||
|
if queryreturn != []:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
queryreturn = sqlQuery(
|
queryreturn = sqlQuery(
|
||||||
'''select address from subscriptions where address=? and enabled = '1' ''',
|
'''select address from subscriptions where address=?'''
|
||||||
|
''' and enabled = '1' ''',
|
||||||
address)
|
address)
|
||||||
if queryreturn <> []:
|
if queryreturn != []:
|
||||||
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:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
|
if fullString[-4:] != \
|
||||||
logger.critical('Major problem! When trying to decode one of your private keys, the checksum '
|
hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
|
||||||
'failed. Here are the first 6 characters of the PRIVATE key: %s' % str(WIFstring)[:6])
|
logger.critical(
|
||||||
|
'Major problem! When trying to decode one of your'
|
||||||
|
' private keys, the checksum failed. Here are the first'
|
||||||
|
' 6 characters of the PRIVATE key: %s',
|
||||||
|
str(WIFstring)[:6]
|
||||||
|
)
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
return ""
|
# return ""
|
||||||
else:
|
else:
|
||||||
#checksum passed
|
# checksum passed
|
||||||
if privkey[0] == '\x80':
|
if privkey[0] == '\x80':
|
||||||
return privkey[1:]
|
return privkey[1:]
|
||||||
else:
|
else:
|
||||||
logger.critical('Major problem! When trying to decode one of your private keys, the '
|
logger.critical(
|
||||||
'checksum passed but the key doesn\'t begin with hex 80. Here is the '
|
'Major problem! When trying to decode one of your'
|
||||||
'PRIVATE key: %s' % str(WIFstring))
|
' private keys, the checksum passed but the key doesn\'t'
|
||||||
|
' begin with hex 80. Here is the PRIVATE key: %s',
|
||||||
|
WIFstring
|
||||||
|
)
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
return ""
|
# return ""
|
||||||
|
|
||||||
|
|
||||||
def reloadMyAddressHashes():
|
def reloadMyAddressHashes():
|
||||||
|
@ -107,7 +150,7 @@ def reloadMyAddressHashes():
|
||||||
myECCryptorObjects.clear()
|
myECCryptorObjects.clear()
|
||||||
myAddressesByHash.clear()
|
myAddressesByHash.clear()
|
||||||
myAddressesByTag.clear()
|
myAddressesByTag.clear()
|
||||||
#myPrivateKeys.clear()
|
# myPrivateKeys.clear()
|
||||||
|
|
||||||
keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat')
|
keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat')
|
||||||
hasEnabledKeys = False
|
hasEnabledKeys = False
|
||||||
|
@ -115,26 +158,36 @@ def reloadMyAddressHashes():
|
||||||
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
|
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
|
||||||
if isEnabled:
|
if isEnabled:
|
||||||
hasEnabledKeys = True
|
hasEnabledKeys = True
|
||||||
status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile)
|
status, addressVersionNumber, streamNumber, hash = \
|
||||||
if addressVersionNumber == 2 or addressVersionNumber == 3 or addressVersionNumber == 4:
|
decodeAddress(addressInKeysFile)
|
||||||
# Returns a simple 32 bytes of information encoded in 64 Hex characters,
|
if addressVersionNumber in (2, 3, 4):
|
||||||
# or null if there was an error.
|
# Returns a simple 32 bytes of information encoded
|
||||||
|
# in 64 Hex characters, or null if there was an error.
|
||||||
privEncryptionKey = hexlify(decodeWalletImportFormat(
|
privEncryptionKey = hexlify(decodeWalletImportFormat(
|
||||||
BMConfigParser().get(addressInKeysFile, 'privencryptionkey')))
|
BMConfigParser().get(addressInKeysFile, 'privencryptionkey'))
|
||||||
|
)
|
||||||
|
|
||||||
if len(privEncryptionKey) == 64:#It is 32 bytes encoded as 64 hex characters
|
# It is 32 bytes encoded as 64 hex characters
|
||||||
myECCryptorObjects[hash] = highlevelcrypto.makeCryptor(privEncryptionKey)
|
if len(privEncryptionKey) == 64:
|
||||||
|
myECCryptorObjects[hash] = \
|
||||||
|
highlevelcrypto.makeCryptor(privEncryptionKey)
|
||||||
myAddressesByHash[hash] = addressInKeysFile
|
myAddressesByHash[hash] = addressInKeysFile
|
||||||
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
|
tag = hashlib.sha512(hashlib.sha512(
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + hash).digest()).digest()[32:]
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + hash).digest()
|
||||||
|
).digest()[32:]
|
||||||
myAddressesByTag[tag] = addressInKeysFile
|
myAddressesByTag[tag] = addressInKeysFile
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.error('Error in reloadMyAddressHashes: Can\'t handle address versions other than 2, 3, or 4.\n')
|
logger.error(
|
||||||
|
'Error in reloadMyAddressHashes: Can\'t handle'
|
||||||
|
' address versions other than 2, 3, or 4.\n'
|
||||||
|
)
|
||||||
|
|
||||||
if not keyfileSecure:
|
if not keyfileSecure:
|
||||||
fixSensitiveFilePermissions(state.appdata + 'keys.dat', hasEnabledKeys)
|
fixSensitiveFilePermissions(state.appdata + 'keys.dat', hasEnabledKeys)
|
||||||
|
|
||||||
|
|
||||||
def reloadBroadcastSendersForWhichImWatching():
|
def reloadBroadcastSendersForWhichImWatching():
|
||||||
broadcastSendersForWhichImWatching.clear()
|
broadcastSendersForWhichImWatching.clear()
|
||||||
MyECSubscriptionCryptorObjects.clear()
|
MyECSubscriptionCryptorObjects.clear()
|
||||||
|
@ -142,31 +195,43 @@ def reloadBroadcastSendersForWhichImWatching():
|
||||||
logger.debug('reloading subscriptions...')
|
logger.debug('reloading subscriptions...')
|
||||||
for row in queryreturn:
|
for row in queryreturn:
|
||||||
address, = row
|
address, = row
|
||||||
status,addressVersionNumber,streamNumber,hash = decodeAddress(address)
|
status, addressVersionNumber, streamNumber, hash = \
|
||||||
|
decodeAddress(address)
|
||||||
if addressVersionNumber == 2:
|
if addressVersionNumber == 2:
|
||||||
broadcastSendersForWhichImWatching[hash] = 0
|
broadcastSendersForWhichImWatching[hash] = 0
|
||||||
#Now, for all addresses, even version 2 addresses, we should create Cryptor objects in a dictionary which we will use to attempt to decrypt encrypted broadcast messages.
|
# Now, for all addresses, even version 2 addresses,
|
||||||
|
# we should create Cryptor objects in a dictionary which we will
|
||||||
|
# use to attempt to decrypt encrypted broadcast messages.
|
||||||
|
|
||||||
if addressVersionNumber <= 3:
|
if addressVersionNumber <= 3:
|
||||||
privEncryptionKey = hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+hash).digest()[:32]
|
privEncryptionKey = hashlib.sha512(
|
||||||
MyECSubscriptionCryptorObjects[hash] = highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + hash
|
||||||
|
).digest()[:32]
|
||||||
|
MyECSubscriptionCryptorObjects[hash] = \
|
||||||
|
highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
|
||||||
else:
|
else:
|
||||||
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
|
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(
|
||||||
addressVersionNumber) + encodeVarint(streamNumber) + hash).digest()).digest()
|
encodeVarint(addressVersionNumber) +
|
||||||
|
encodeVarint(streamNumber) + hash
|
||||||
|
).digest()).digest()
|
||||||
tag = doubleHashOfAddressData[32:]
|
tag = doubleHashOfAddressData[32:]
|
||||||
privEncryptionKey = doubleHashOfAddressData[:32]
|
privEncryptionKey = doubleHashOfAddressData[:32]
|
||||||
MyECSubscriptionCryptorObjects[tag] = highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
|
MyECSubscriptionCryptorObjects[tag] = \
|
||||||
|
highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
|
||||||
|
|
||||||
|
|
||||||
def fixPotentiallyInvalidUTF8Data(text):
|
def fixPotentiallyInvalidUTF8Data(text):
|
||||||
try:
|
try:
|
||||||
unicode(text,'utf-8')
|
unicode(text, 'utf-8')
|
||||||
return text
|
return text
|
||||||
except:
|
except:
|
||||||
output = 'Part of the message is corrupt. The message cannot be displayed the normal way.\n\n' + repr(text)
|
return 'Part of the message is corrupt. The message cannot be' \
|
||||||
return output
|
' displayed the normal way.\n\n' + repr(text)
|
||||||
|
|
||||||
# Checks sensitive file permissions for inappropriate umask during keys.dat creation.
|
|
||||||
# (Or unwise subsequent chmod.)
|
# Checks sensitive file permissions for inappropriate umask
|
||||||
|
# during keys.dat creation. (Or unwise subsequent chmod.)
|
||||||
#
|
#
|
||||||
# Returns true iff file appears to have appropriate permissions.
|
# Returns true iff file appears to have appropriate permissions.
|
||||||
def checkSensitiveFilePermissions(filename):
|
def checkSensitiveFilePermissions(filename):
|
||||||
|
@ -181,14 +246,17 @@ def checkSensitiveFilePermissions(filename):
|
||||||
return present_permissions & disallowed_permissions == 0
|
return present_permissions & disallowed_permissions == 0
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
# Skip known problems for non-Win32 filesystems without POSIX permissions.
|
# Skip known problems for non-Win32 filesystems
|
||||||
import subprocess
|
# without POSIX permissions.
|
||||||
fstype = subprocess.check_output('stat -f -c "%%T" %s' % (filename),
|
fstype = subprocess.check_output(
|
||||||
shell=True,
|
'stat -f -c "%%T" %s' % (filename),
|
||||||
stderr=subprocess.STDOUT)
|
shell=True,
|
||||||
|
stderr=subprocess.STDOUT
|
||||||
|
)
|
||||||
if 'fuseblk' in fstype:
|
if 'fuseblk' in fstype:
|
||||||
logger.info('Skipping file permissions check for %s. Filesystem fuseblk detected.',
|
logger.info(
|
||||||
filename)
|
'Skipping file permissions check for %s.'
|
||||||
|
' Filesystem fuseblk detected.', filename)
|
||||||
return True
|
return True
|
||||||
except:
|
except:
|
||||||
# Swallow exception here, but we might run into trouble later!
|
# Swallow exception here, but we might run into trouble later!
|
||||||
|
@ -197,27 +265,32 @@ def checkSensitiveFilePermissions(filename):
|
||||||
disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO
|
disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO
|
||||||
return present_permissions & disallowed_permissions == 0
|
return present_permissions & disallowed_permissions == 0
|
||||||
|
|
||||||
|
|
||||||
# Fixes permissions on a sensitive file.
|
# Fixes permissions on a sensitive file.
|
||||||
def fixSensitiveFilePermissions(filename, hasEnabledKeys):
|
def fixSensitiveFilePermissions(filename, hasEnabledKeys):
|
||||||
if hasEnabledKeys:
|
if hasEnabledKeys:
|
||||||
logger.warning('Keyfile had insecure permissions, and there were enabled keys. '
|
logger.warning(
|
||||||
'The truly paranoid should stop using them immediately.')
|
'Keyfile had insecure permissions, and there were enabled'
|
||||||
|
' keys. The truly paranoid should stop using them immediately.')
|
||||||
else:
|
else:
|
||||||
logger.warning('Keyfile had insecure permissions, but there were no enabled keys.')
|
logger.warning(
|
||||||
|
'Keyfile had insecure permissions, but there were no enabled keys.'
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
present_permissions = os.stat(filename)[0]
|
present_permissions = os.stat(filename)[0]
|
||||||
disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO
|
disallowed_permissions = stat.S_IRWXG | stat.S_IRWXO
|
||||||
allowed_permissions = ((1<<32)-1) ^ disallowed_permissions
|
allowed_permissions = ((1 << 32) - 1) ^ disallowed_permissions
|
||||||
new_permissions = (
|
new_permissions = (
|
||||||
allowed_permissions & present_permissions)
|
allowed_permissions & present_permissions)
|
||||||
os.chmod(filename, new_permissions)
|
os.chmod(filename, new_permissions)
|
||||||
|
|
||||||
logger.info('Keyfile permissions automatically fixed.')
|
logger.info('Keyfile permissions automatically fixed.')
|
||||||
|
|
||||||
except Exception, e:
|
except Exception:
|
||||||
logger.exception('Keyfile permissions could not be fixed.')
|
logger.exception('Keyfile permissions could not be fixed.')
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def isBitSetWithinBitfield(fourByteString, n):
|
def isBitSetWithinBitfield(fourByteString, n):
|
||||||
# Uses MSB 0 bit numbering across 4 bytes of data
|
# Uses MSB 0 bit numbering across 4 bytes of data
|
||||||
n = 31 - n
|
n = 31 - n
|
||||||
|
@ -227,39 +300,57 @@ def isBitSetWithinBitfield(fourByteString, n):
|
||||||
|
|
||||||
def decryptAndCheckPubkeyPayload(data, address):
|
def decryptAndCheckPubkeyPayload(data, address):
|
||||||
"""
|
"""
|
||||||
Version 4 pubkeys are encrypted. This function is run when we already have the
|
Version 4 pubkeys are encrypted. This function is run when we
|
||||||
address to which we want to try to send a message. The 'data' may come either
|
already have the address to which we want to try to send a message.
|
||||||
off of the wire or we might have had it already in our inventory when we tried
|
The 'data' may come either off of the wire or we might have had it
|
||||||
to send a msg to this particular address.
|
already in our inventory when we tried to send a msg to this
|
||||||
|
particular address.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
status, addressVersion, streamNumber, ripe = decodeAddress(address)
|
status, addressVersion, streamNumber, ripe = decodeAddress(address)
|
||||||
|
|
||||||
readPosition = 20 # bypass the nonce, time, and object type
|
readPosition = 20 # bypass the nonce, time, and object type
|
||||||
embeddedAddressVersion, varintLength = decodeVarint(data[readPosition:readPosition + 10])
|
embeddedAddressVersion, varintLength = \
|
||||||
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
embeddedStreamNumber, varintLength = decodeVarint(data[readPosition:readPosition + 10])
|
embeddedStreamNumber, varintLength = \
|
||||||
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
storedData = data[20:readPosition] # We'll store the address version and stream number (and some more) in the pubkeys table.
|
# We'll store the address version and stream number
|
||||||
|
# (and some more) in the pubkeys table.
|
||||||
|
storedData = data[20:readPosition]
|
||||||
|
|
||||||
if addressVersion != embeddedAddressVersion:
|
if addressVersion != embeddedAddressVersion:
|
||||||
logger.info('Pubkey decryption was UNsuccessful due to address version mismatch.')
|
logger.info(
|
||||||
|
'Pubkey decryption was UNsuccessful'
|
||||||
|
' due to address version mismatch.')
|
||||||
return 'failed'
|
return 'failed'
|
||||||
if streamNumber != embeddedStreamNumber:
|
if streamNumber != embeddedStreamNumber:
|
||||||
logger.info('Pubkey decryption was UNsuccessful due to stream number mismatch.')
|
logger.info(
|
||||||
|
'Pubkey decryption was UNsuccessful'
|
||||||
|
' due to stream number mismatch.')
|
||||||
return 'failed'
|
return 'failed'
|
||||||
|
|
||||||
tag = data[readPosition:readPosition + 32]
|
tag = data[readPosition:readPosition + 32]
|
||||||
readPosition += 32
|
readPosition += 32
|
||||||
signedData = data[8:readPosition] # the time through the tag. More data is appended onto signedData below after the decryption.
|
# the time through the tag. More data is appended onto
|
||||||
|
# signedData below after the decryption.
|
||||||
|
signedData = data[8:readPosition]
|
||||||
encryptedData = data[readPosition:]
|
encryptedData = data[readPosition:]
|
||||||
|
|
||||||
# Let us try to decrypt the pubkey
|
# Let us try to decrypt the pubkey
|
||||||
toAddress, cryptorObject = state.neededPubkeys[tag]
|
toAddress, cryptorObject = state.neededPubkeys[tag]
|
||||||
if toAddress != address:
|
if toAddress != address:
|
||||||
logger.critical('decryptAndCheckPubkeyPayload failed due to toAddress mismatch. This is very peculiar. toAddress: %s, address %s' % (toAddress, address))
|
logger.critical(
|
||||||
# the only way I can think that this could happen is if someone encodes their address data two different ways.
|
'decryptAndCheckPubkeyPayload failed due to toAddress'
|
||||||
# That sort of address-malleability should have been caught by the UI or API and an error given to the user.
|
' mismatch. This is very peculiar.'
|
||||||
|
' toAddress: %s, address %s',
|
||||||
|
toAddress, address
|
||||||
|
)
|
||||||
|
# the only way I can think that this could happen
|
||||||
|
# is if someone encodes their address data two different ways.
|
||||||
|
# That sort of address-malleability should have been caught
|
||||||
|
# by the UI or API and an error given to the user.
|
||||||
return 'failed'
|
return 'failed'
|
||||||
try:
|
try:
|
||||||
decryptedData = cryptorObject.decrypt(encryptedData)
|
decryptedData = cryptorObject.decrypt(encryptedData)
|
||||||
|
@ -270,29 +361,35 @@ def decryptAndCheckPubkeyPayload(data, address):
|
||||||
return 'failed'
|
return 'failed'
|
||||||
|
|
||||||
readPosition = 0
|
readPosition = 0
|
||||||
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
|
# bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
|
||||||
readPosition += 4
|
readPosition += 4
|
||||||
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
publicSigningKey = \
|
||||||
|
'\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
|
publicEncryptionKey = \
|
||||||
|
'\x04' + decryptedData[readPosition:readPosition + 64]
|
||||||
readPosition += 64
|
readPosition += 64
|
||||||
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
|
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = \
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decodeVarint(decryptedData[readPosition:readPosition + 10])
|
||||||
readPosition += specifiedNonceTrialsPerByteLength
|
readPosition += specifiedNonceTrialsPerByteLength
|
||||||
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
|
specifiedPayloadLengthExtraBytes, \
|
||||||
decryptedData[readPosition:readPosition + 10])
|
specifiedPayloadLengthExtraBytesLength = \
|
||||||
|
decodeVarint(decryptedData[readPosition:readPosition + 10])
|
||||||
readPosition += specifiedPayloadLengthExtraBytesLength
|
readPosition += specifiedPayloadLengthExtraBytesLength
|
||||||
storedData += decryptedData[:readPosition]
|
storedData += decryptedData[:readPosition]
|
||||||
signedData += decryptedData[:readPosition]
|
signedData += decryptedData[:readPosition]
|
||||||
signatureLength, signatureLengthLength = decodeVarint(
|
signatureLength, signatureLengthLength = \
|
||||||
decryptedData[readPosition:readPosition + 10])
|
decodeVarint(decryptedData[readPosition:readPosition + 10])
|
||||||
readPosition += signatureLengthLength
|
readPosition += signatureLengthLength
|
||||||
signature = decryptedData[readPosition:readPosition + signatureLength]
|
signature = decryptedData[readPosition:readPosition + signatureLength]
|
||||||
|
|
||||||
if highlevelcrypto.verify(signedData, signature, hexlify(publicSigningKey)):
|
if highlevelcrypto.verify(
|
||||||
logger.info('ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
|
signedData, signature, hexlify(publicSigningKey)):
|
||||||
|
logger.info(
|
||||||
|
'ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
|
||||||
else:
|
else:
|
||||||
logger.info('ECDSA verify failed (within decryptAndCheckPubkeyPayload)')
|
logger.info(
|
||||||
|
'ECDSA verify failed (within decryptAndCheckPubkeyPayload)')
|
||||||
return 'failed'
|
return 'failed'
|
||||||
|
|
||||||
sha = hashlib.new('sha512')
|
sha = hashlib.new('sha512')
|
||||||
|
@ -302,44 +399,52 @@ def decryptAndCheckPubkeyPayload(data, address):
|
||||||
embeddedRipe = ripeHasher.digest()
|
embeddedRipe = ripeHasher.digest()
|
||||||
|
|
||||||
if embeddedRipe != ripe:
|
if embeddedRipe != ripe:
|
||||||
# Although this pubkey object had the tag were were looking for and was
|
# Although this pubkey object had the tag were were looking for
|
||||||
# encrypted with the correct encryption key, it doesn't contain the
|
# and was encrypted with the correct encryption key,
|
||||||
# correct pubkeys. Someone is either being malicious or using buggy software.
|
# it doesn't contain the correct pubkeys. Someone is
|
||||||
logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch.')
|
# either being malicious or using buggy software.
|
||||||
|
logger.info(
|
||||||
|
'Pubkey decryption was UNsuccessful due to RIPE mismatch.')
|
||||||
return 'failed'
|
return 'failed'
|
||||||
|
|
||||||
# Everything checked out. Insert it into the pubkeys table.
|
# Everything checked out. Insert it into the pubkeys table.
|
||||||
|
|
||||||
logger.info('within decryptAndCheckPubkeyPayload, addressVersion: %s, streamNumber: %s \n\
|
logger.info(
|
||||||
ripe %s\n\
|
'within decryptAndCheckPubkeyPayload, '
|
||||||
publicSigningKey in hex: %s\n\
|
'addressVersion: %s, streamNumber: %s\nripe %s\n'
|
||||||
publicEncryptionKey in hex: %s' % (addressVersion,
|
'publicSigningKey in hex: %s\npublicEncryptionKey in hex: %s',
|
||||||
streamNumber,
|
addressVersion, streamNumber, hexlify(ripe),
|
||||||
hexlify(ripe),
|
hexlify(publicSigningKey), hexlify(publicEncryptionKey)
|
||||||
hexlify(publicSigningKey),
|
)
|
||||||
hexlify(publicEncryptionKey)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
t = (address, addressVersion, storedData, int(time.time()), 'yes')
|
t = (address, addressVersion, storedData, int(time.time()), 'yes')
|
||||||
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
|
||||||
return 'successful'
|
return 'successful'
|
||||||
except varintDecodeError as e:
|
except varintDecodeError:
|
||||||
logger.info('Pubkey decryption was UNsuccessful due to a malformed varint.')
|
logger.info(
|
||||||
|
'Pubkey decryption was UNsuccessful due to a malformed varint.')
|
||||||
return 'failed'
|
return 'failed'
|
||||||
except Exception as e:
|
except Exception:
|
||||||
logger.critical('Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s' % traceback.format_exc())
|
logger.critical(
|
||||||
|
'Pubkey decryption was UNsuccessful because of'
|
||||||
|
' an unhandled exception! This is definitely a bug! \n%s' %
|
||||||
|
traceback.format_exc()
|
||||||
|
)
|
||||||
return 'failed'
|
return 'failed'
|
||||||
|
|
||||||
|
|
||||||
def checkAndShareObjectWithPeers(data):
|
def checkAndShareObjectWithPeers(data):
|
||||||
"""
|
"""
|
||||||
This function is called after either receiving an object off of the wire
|
This function is called after either receiving an object
|
||||||
or after receiving one as ackdata.
|
off of the wire or after receiving one as ackdata.
|
||||||
Returns the length of time that we should reserve to process this message
|
Returns the length of time that we should reserve to process
|
||||||
if we are receiving it off of the wire.
|
this message if we are receiving it off of the wire.
|
||||||
"""
|
"""
|
||||||
if len(data) > 2 ** 18:
|
if len(data) > 2 ** 18:
|
||||||
logger.info('The payload length of this object is too large (%s bytes). Ignoring it.' % len(data))
|
logger.info(
|
||||||
|
'The payload length of this object is too large (%i bytes).'
|
||||||
|
' Ignoring it.', len(data)
|
||||||
|
)
|
||||||
return 0
|
return 0
|
||||||
# Let us check to make sure that the proof of work is sufficient.
|
# Let us check to make sure that the proof of work is sufficient.
|
||||||
if not protocol.isProofOfWorkSufficient(data):
|
if not protocol.isProofOfWorkSufficient(data):
|
||||||
|
@ -347,11 +452,19 @@ def checkAndShareObjectWithPeers(data):
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
endOfLifeTime, = unpack('>Q', data[8:16])
|
endOfLifeTime, = unpack('>Q', data[8:16])
|
||||||
if endOfLifeTime - int(time.time()) > 28 * 24 * 60 * 60 + 10800: # The TTL may not be larger than 28 days + 3 hours of wiggle room
|
# The TTL may not be larger than 28 days + 3 hours of wiggle room
|
||||||
logger.info('This object\'s End of Life time is too far in the future. Ignoring it. Time is %s' % endOfLifeTime)
|
if endOfLifeTime - int(time.time()) > 28 * 24 * 60 * 60 + 10800:
|
||||||
|
logger.info(
|
||||||
|
'This object\'s End of Life time is too far in the future.'
|
||||||
|
' Ignoring it. Time is %s', endOfLifeTime
|
||||||
|
)
|
||||||
return 0
|
return 0
|
||||||
if endOfLifeTime - int(time.time()) < - 3600: # The EOL time was more than an hour ago. That's too much.
|
# The EOL time was more than an hour ago. That's too much.
|
||||||
logger.info('This object\'s End of Life time was more than an hour ago. Ignoring the object. Time is %s' % endOfLifeTime)
|
if endOfLifeTime - int(time.time()) < - 3600:
|
||||||
|
logger.info(
|
||||||
|
'This object\'s End of Life time was more than an hour ago.'
|
||||||
|
' Ignoring the object. Time is %s' % endOfLifeTime
|
||||||
|
)
|
||||||
return 0
|
return 0
|
||||||
intObjectType, = unpack('>I', data[16:20])
|
intObjectType, = unpack('>I', data[16:20])
|
||||||
try:
|
try:
|
||||||
|
@ -371,45 +484,59 @@ def checkAndShareObjectWithPeers(data):
|
||||||
_checkAndShareUndefinedObjectWithPeers(data)
|
_checkAndShareUndefinedObjectWithPeers(data)
|
||||||
return 0.6
|
return 0.6
|
||||||
except varintDecodeError as e:
|
except varintDecodeError as e:
|
||||||
logger.debug("There was a problem with a varint while checking to see whether it was appropriate to share an object with peers. Some details: %s" % e)
|
logger.debug(
|
||||||
except Exception as e:
|
'There was a problem with a varint while checking'
|
||||||
logger.critical('There was a problem while checking to see whether it was appropriate to share an object with peers. This is definitely a bug! \n%s' % traceback.format_exc())
|
' to see whether it was appropriate to share an object'
|
||||||
|
' with peers. Some details: %s' % e)
|
||||||
|
except Exception:
|
||||||
|
logger.critical(
|
||||||
|
'There was a problem while checking to see whether it was'
|
||||||
|
' appropriate to share an object with peers. This is'
|
||||||
|
' definitely a bug! \n%s' % traceback.format_exc())
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def _checkAndShareUndefinedObjectWithPeers(data):
|
def _checkAndShareUndefinedObjectWithPeers(data):
|
||||||
embeddedTime, = unpack('>Q', data[8:16])
|
embeddedTime, = unpack('>Q', data[8:16])
|
||||||
readPosition = 20 # bypass nonce, time, and object type
|
readPosition = 20 # bypass nonce, time, and object type
|
||||||
objectVersion, objectVersionLength = decodeVarint(
|
objectVersion, objectVersionLength = decodeVarint(
|
||||||
data[readPosition:readPosition + 9])
|
data[readPosition:readPosition + 9])
|
||||||
readPosition += objectVersionLength
|
readPosition += objectVersionLength
|
||||||
streamNumber, streamNumberLength = decodeVarint(
|
streamNumber, streamNumberLength = decodeVarint(
|
||||||
data[readPosition:readPosition + 9])
|
data[readPosition:readPosition + 9])
|
||||||
if not streamNumber in state.streamsInWhichIAmParticipating:
|
if streamNumber not in state.streamsInWhichIAmParticipating:
|
||||||
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
|
logger.debug(
|
||||||
|
'The streamNumber %i isn\'t one we are interested in.',
|
||||||
|
streamNumber
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
inventoryHash = calculateInventoryHash(data)
|
inventoryHash = calculateInventoryHash(data)
|
||||||
if inventoryHash in Inventory():
|
if inventoryHash in Inventory():
|
||||||
logger.debug('We have already received this undefined object. Ignoring.')
|
logger.debug(
|
||||||
|
'We have already received this undefined object. Ignoring.')
|
||||||
return
|
return
|
||||||
objectType, = unpack('>I', data[16:20])
|
objectType, = unpack('>I', data[16:20])
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, data, embeddedTime,'')
|
objectType, streamNumber, data, embeddedTime, '')
|
||||||
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
|
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
|
||||||
protocol.broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
protocol.broadcastToSendDataQueues(
|
||||||
|
(streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
|
|
||||||
def _checkAndShareMsgWithPeers(data):
|
def _checkAndShareMsgWithPeers(data):
|
||||||
embeddedTime, = unpack('>Q', data[8:16])
|
embeddedTime, = unpack('>Q', data[8:16])
|
||||||
readPosition = 20 # bypass nonce, time, and object type
|
readPosition = 20 # bypass nonce, time, and object type
|
||||||
objectVersion, objectVersionLength = decodeVarint(
|
objectVersion, objectVersionLength = \
|
||||||
data[readPosition:readPosition + 9])
|
decodeVarint(data[readPosition:readPosition + 9])
|
||||||
readPosition += objectVersionLength
|
readPosition += objectVersionLength
|
||||||
streamNumber, streamNumberLength = decodeVarint(
|
streamNumber, streamNumberLength = \
|
||||||
data[readPosition:readPosition + 9])
|
decodeVarint(data[readPosition:readPosition + 9])
|
||||||
if not streamNumber in state.streamsInWhichIAmParticipating:
|
if streamNumber not in state.streamsInWhichIAmParticipating:
|
||||||
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
|
logger.debug(
|
||||||
|
'The streamNumber %i isn\'t one we are interested in.',
|
||||||
|
streamNumber
|
||||||
|
)
|
||||||
return
|
return
|
||||||
readPosition += streamNumberLength
|
readPosition += streamNumberLength
|
||||||
inventoryHash = calculateInventoryHash(data)
|
inventoryHash = calculateInventoryHash(data)
|
||||||
|
@ -419,61 +546,73 @@ def _checkAndShareMsgWithPeers(data):
|
||||||
# This msg message is valid. Let's let our peers know about it.
|
# This msg message is valid. Let's let our peers know about it.
|
||||||
objectType = 2
|
objectType = 2
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, data, embeddedTime,'')
|
objectType, streamNumber, data, embeddedTime, '')
|
||||||
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
|
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
|
||||||
protocol.broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
protocol.broadcastToSendDataQueues(
|
||||||
|
(streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
# Now let's enqueue it to be processed ourselves.
|
# Now let's enqueue it to be processed ourselves.
|
||||||
objectProcessorQueue.put((objectType,data))
|
objectProcessorQueue.put((objectType, data))
|
||||||
|
|
||||||
|
|
||||||
def _checkAndShareGetpubkeyWithPeers(data):
|
def _checkAndShareGetpubkeyWithPeers(data):
|
||||||
if len(data) < 42:
|
if len(data) < 42:
|
||||||
logger.info('getpubkey message doesn\'t contain enough data. Ignoring.')
|
logger.info(
|
||||||
|
'getpubkey message doesn\'t contain enough data. Ignoring.')
|
||||||
return
|
return
|
||||||
embeddedTime, = unpack('>Q', data[8:16])
|
embeddedTime, = unpack('>Q', data[8:16])
|
||||||
readPosition = 20 # bypass the nonce, time, and object type
|
readPosition = 20 # bypass the nonce, time, and object type
|
||||||
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
|
requestedAddressVersionNumber, addressVersionLength = \
|
||||||
data[readPosition:readPosition + 10])
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += addressVersionLength
|
readPosition += addressVersionLength
|
||||||
streamNumber, streamNumberLength = decodeVarint(
|
streamNumber, streamNumberLength = \
|
||||||
data[readPosition:readPosition + 10])
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
if not streamNumber in state.streamsInWhichIAmParticipating:
|
if streamNumber not in state.streamsInWhichIAmParticipating:
|
||||||
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
|
logger.debug(
|
||||||
|
'The streamNumber %i isn\'t one we are interested in.',
|
||||||
|
streamNumber
|
||||||
|
)
|
||||||
return
|
return
|
||||||
readPosition += streamNumberLength
|
readPosition += streamNumberLength
|
||||||
|
|
||||||
inventoryHash = calculateInventoryHash(data)
|
inventoryHash = calculateInventoryHash(data)
|
||||||
if inventoryHash in Inventory():
|
if inventoryHash in Inventory():
|
||||||
logger.debug('We have already received this getpubkey request. Ignoring it.')
|
logger.debug(
|
||||||
|
'We have already received this getpubkey request. Ignoring it.')
|
||||||
return
|
return
|
||||||
|
|
||||||
objectType = 0
|
objectType = 0
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, data, embeddedTime,'')
|
objectType, streamNumber, data, embeddedTime, '')
|
||||||
# This getpubkey request is valid. Forward to peers.
|
# This getpubkey request is valid. Forward to peers.
|
||||||
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
|
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
|
||||||
protocol.broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
protocol.broadcastToSendDataQueues(
|
||||||
|
(streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
# Now let's queue it to be processed ourselves.
|
# Now let's queue it to be processed ourselves.
|
||||||
objectProcessorQueue.put((objectType,data))
|
objectProcessorQueue.put((objectType, data))
|
||||||
|
|
||||||
|
|
||||||
def _checkAndSharePubkeyWithPeers(data):
|
def _checkAndSharePubkeyWithPeers(data):
|
||||||
if len(data) < 146 or len(data) > 440: # sanity check
|
if len(data) < 146 or len(data) > 440: # sanity check
|
||||||
return
|
return
|
||||||
embeddedTime, = unpack('>Q', data[8:16])
|
embeddedTime, = unpack('>Q', data[8:16])
|
||||||
readPosition = 20 # bypass the nonce, time, and object type
|
readPosition = 20 # bypass the nonce, time, and object type
|
||||||
addressVersion, varintLength = decodeVarint(
|
addressVersion, varintLength = \
|
||||||
data[readPosition:readPosition + 10])
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
streamNumber, varintLength = decodeVarint(
|
streamNumber, varintLength = \
|
||||||
data[readPosition:readPosition + 10])
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += varintLength
|
readPosition += varintLength
|
||||||
if not streamNumber in state.streamsInWhichIAmParticipating:
|
if streamNumber not in state.streamsInWhichIAmParticipating:
|
||||||
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
|
logger.debug(
|
||||||
|
'The streamNumber %i isn\'t one we are interested in.',
|
||||||
|
streamNumber
|
||||||
|
)
|
||||||
return
|
return
|
||||||
if addressVersion >= 4:
|
if addressVersion >= 4:
|
||||||
tag = data[readPosition:readPosition + 32]
|
tag = data[readPosition:readPosition + 32]
|
||||||
logger.debug('tag in received pubkey is: %s' % hexlify(tag))
|
logger.debug('tag in received pubkey is: %s', hexlify(tag))
|
||||||
else:
|
else:
|
||||||
tag = ''
|
tag = ''
|
||||||
|
|
||||||
|
@ -485,28 +624,34 @@ def _checkAndSharePubkeyWithPeers(data):
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, data, embeddedTime, tag)
|
objectType, streamNumber, data, embeddedTime, tag)
|
||||||
# This object is valid. Forward it to peers.
|
# This object is valid. Forward it to peers.
|
||||||
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
|
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
|
||||||
protocol.broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
protocol.broadcastToSendDataQueues(
|
||||||
|
(streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
# Now let's queue it to be processed ourselves.
|
# Now let's queue it to be processed ourselves.
|
||||||
objectProcessorQueue.put((objectType,data))
|
objectProcessorQueue.put((objectType, data))
|
||||||
|
|
||||||
|
|
||||||
def _checkAndShareBroadcastWithPeers(data):
|
def _checkAndShareBroadcastWithPeers(data):
|
||||||
if len(data) < 180:
|
if len(data) < 180:
|
||||||
logger.debug('The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.')
|
logger.debug(
|
||||||
|
'The payload length of this broadcast packet is unreasonably low.'
|
||||||
|
' Someone is probably trying funny business. Ignoring message.')
|
||||||
return
|
return
|
||||||
embeddedTime, = unpack('>Q', data[8:16])
|
embeddedTime, = unpack('>Q', data[8:16])
|
||||||
readPosition = 20 # bypass the nonce, time, and object type
|
readPosition = 20 # bypass the nonce, time, and object type
|
||||||
broadcastVersion, broadcastVersionLength = decodeVarint(
|
broadcastVersion, broadcastVersionLength = \
|
||||||
data[readPosition:readPosition + 10])
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += broadcastVersionLength
|
readPosition += broadcastVersionLength
|
||||||
if broadcastVersion >= 2:
|
if broadcastVersion >= 2:
|
||||||
streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10])
|
streamNumber, streamNumberLength = \
|
||||||
|
decodeVarint(data[readPosition:readPosition + 10])
|
||||||
readPosition += streamNumberLength
|
readPosition += streamNumberLength
|
||||||
if not streamNumber in state.streamsInWhichIAmParticipating:
|
if streamNumber not in state.streamsInWhichIAmParticipating:
|
||||||
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
|
logger.debug(
|
||||||
|
'The streamNumber %i isn\'t one we are interested in.',
|
||||||
|
streamNumber
|
||||||
|
)
|
||||||
return
|
return
|
||||||
if broadcastVersion >= 3:
|
if broadcastVersion >= 3:
|
||||||
tag = data[readPosition:readPosition+32]
|
tag = data[readPosition:readPosition+32]
|
||||||
|
@ -514,24 +659,24 @@ def _checkAndShareBroadcastWithPeers(data):
|
||||||
tag = ''
|
tag = ''
|
||||||
inventoryHash = calculateInventoryHash(data)
|
inventoryHash = calculateInventoryHash(data)
|
||||||
if inventoryHash in Inventory():
|
if inventoryHash in Inventory():
|
||||||
logger.debug('We have already received this broadcast object. Ignoring.')
|
logger.debug(
|
||||||
|
'We have already received this broadcast object. Ignoring.')
|
||||||
return
|
return
|
||||||
# It is valid. Let's let our peers know about it.
|
# It is valid. Let's let our peers know about it.
|
||||||
objectType = 3
|
objectType = 3
|
||||||
Inventory()[inventoryHash] = (
|
Inventory()[inventoryHash] = (
|
||||||
objectType, streamNumber, data, embeddedTime, tag)
|
objectType, streamNumber, data, embeddedTime, tag)
|
||||||
# This object is valid. Forward it to peers.
|
# This object is valid. Forward it to peers.
|
||||||
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
|
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
|
||||||
protocol.broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
|
protocol.broadcastToSendDataQueues(
|
||||||
|
(streamNumber, 'advertiseobject', inventoryHash))
|
||||||
|
|
||||||
# Now let's queue it to be processed ourselves.
|
# Now let's queue it to be processed ourselves.
|
||||||
objectProcessorQueue.put((objectType,data))
|
objectProcessorQueue.put((objectType, data))
|
||||||
|
|
||||||
|
|
||||||
def openKeysFile():
|
def openKeysFile():
|
||||||
if 'linux' in sys.platform:
|
if 'linux' in sys.platform:
|
||||||
import subprocess
|
|
||||||
subprocess.call(["xdg-open", state.appdata + 'keys.dat'])
|
subprocess.call(["xdg-open", state.appdata + 'keys.dat'])
|
||||||
else:
|
else:
|
||||||
os.startfile(state.appdata + 'keys.dat')
|
os.startfile(state.appdata + 'keys.dat')
|
||||||
|
|
||||||
from debug import logger
|
|
||||||
|
|
Reference in New Issue
Block a user