make message sending work in Python 3

This commit is contained in:
Kashiko Koibumi 2024-05-15 11:50:38 +09:00
parent 88b14977b8
commit 4f0e34b4be
No known key found for this signature in database
GPG Key ID: 8F06E069E37C40C4
5 changed files with 60 additions and 57 deletions

View File

@ -150,38 +150,38 @@ class singleWorker(StoppableThread):
if command == 'sendmessage': if command == 'sendmessage':
try: try:
self.sendMsg() self.sendMsg()
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("sendMsg didn't work") self.logger.warning("sendMsg didn't work: {}".format(ex))
elif command == 'sendbroadcast': elif command == 'sendbroadcast':
try: try:
self.sendBroadcast() self.sendBroadcast()
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("sendBroadcast didn't work") self.logger.warning("sendBroadcast didn't work: {}".format(ex))
elif command == 'doPOWForMyV2Pubkey': elif command == 'doPOWForMyV2Pubkey':
try: try:
self.doPOWForMyV2Pubkey(data) self.doPOWForMyV2Pubkey(data)
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("doPOWForMyV2Pubkey didn't work") self.logger.warning("doPOWForMyV2Pubkey didn't work: {}".format(ex))
elif command == 'sendOutOrStoreMyV3Pubkey': elif command == 'sendOutOrStoreMyV3Pubkey':
try: try:
self.sendOutOrStoreMyV3Pubkey(data) self.sendOutOrStoreMyV3Pubkey(data)
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("sendOutOrStoreMyV3Pubkey didn't work") self.logger.warning("sendOutOrStoreMyV3Pubkey didn't work: {}".format(ex))
elif command == 'sendOutOrStoreMyV4Pubkey': elif command == 'sendOutOrStoreMyV4Pubkey':
try: try:
self.sendOutOrStoreMyV4Pubkey(data) self.sendOutOrStoreMyV4Pubkey(data)
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("sendOutOrStoreMyV4Pubkey didn't work") self.logger.warning("sendOutOrStoreMyV4Pubkey didn't work: {}".format(ex))
elif command == 'sendOnionPeerObj': elif command == 'sendOnionPeerObj':
try: try:
self.sendOnionPeerObj(data) self.sendOnionPeerObj(data)
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("sendOnionPeerObj didn't work") self.logger.warning("sendOnionPeerObj didn't work: {}".format(ex))
elif command == 'resetPoW': elif command == 'resetPoW':
try: try:
proofofwork.resetPoW() proofofwork.resetPoW()
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("proofofwork.resetPoW didn't work") self.logger.warning("proofofwork.resetPoW didn't work: {}".format(ex))
elif command == 'stopThread': elif command == 'stopThread':
self.busy = 0 self.busy = 0
return return
@ -603,7 +603,7 @@ class singleWorker(StoppableThread):
TTL = int(TTL + helper_random.randomrandrange(-300, 300)) 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 += b'\x00\x00\x00\x03' # object type: broadcast
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
payload += encodeVarint(4) # broadcast version payload += encodeVarint(4) # broadcast version
@ -619,7 +619,7 @@ class singleWorker(StoppableThread):
tag = doubleHashOfAddressData[32:] tag = doubleHashOfAddressData[32:]
payload += tag payload += tag
else: else:
tag = '' tag = b''
dataToEncrypt = encodeVarint(addressVersionNumber) dataToEncrypt = encodeVarint(addressVersionNumber)
dataToEncrypt += encodeVarint(streamNumber) dataToEncrypt += encodeVarint(streamNumber)
@ -702,7 +702,7 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Broadcast sent on %1" "Broadcast sent on %1"
).arg(l10n.formatTimestamp())) ).format(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
@ -792,7 +792,7 @@ class singleWorker(StoppableThread):
# We don't have the needed pubkey in the pubkeys table already. # We don't have the needed pubkey in the pubkeys table already.
else: else:
if toAddressVersionNumber <= 3: if toAddressVersionNumber <= 3:
toTag = '' toTag = b''
else: else:
toTag = highlevelcrypto.double_sha512( toTag = highlevelcrypto.double_sha512(
encodeVarint(toAddressVersionNumber) encodeVarint(toAddressVersionNumber)
@ -977,7 +977,7 @@ class singleWorker(StoppableThread):
" destination be included in the" " destination be included in the"
" message but this is disallowed in" " message but this is disallowed in"
" your settings. %1" " your settings. %1"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
# if the human changes their setting and then # if the human changes their setting and then
# sends another message or restarts their client, # sends another message or restarts their client,
@ -1042,14 +1042,13 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Doing work necessary to send message.\n" "Doing work necessary to send message.\n"
"Receiver\'s required difficulty: %1" "Receiver\'s required difficulty: {0}"
" and %2" " and {1}"
).arg( ).format(
str( str(
float(requiredAverageProofOfWorkNonceTrialsPerByte) float(requiredAverageProofOfWorkNonceTrialsPerByte)
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte / defaults.networkDefaultProofOfWorkNonceTrialsPerByte
) ),
).arg(
str( str(
float(requiredPayloadLengthExtraBytes) float(requiredPayloadLengthExtraBytes)
/ defaults.networkDefaultPayloadLengthExtraBytes / defaults.networkDefaultPayloadLengthExtraBytes
@ -1082,14 +1081,14 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Problem: The work demanded by" "Problem: The work demanded by"
" the recipient (%1 and %2) is" " the recipient ({0} and {1}) is"
" more difficult than you are" " more difficult than you are"
" willing to do. %3" " willing to do. {2}"
).arg(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) ).format(str(float(requiredAverageProofOfWorkNonceTrialsPerByte)
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte),
).arg(str(float(requiredPayloadLengthExtraBytes) str(float(requiredPayloadLengthExtraBytes)
/ defaults.networkDefaultPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes),
).arg(l10n.formatTimestamp())))) 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..
self.logger.info('Sending a message.') self.logger.info('Sending a message.')
@ -1110,8 +1109,8 @@ class singleWorker(StoppableThread):
" message to yourself or a chan but your" " message to yourself or a chan but your"
" encryption key could not be found in" " encryption key could not be found in"
" the keys.dat file. Could not encrypt" " the keys.dat file. Could not encrypt"
" message. %1" " message. {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
self.logger.error( self.logger.error(
'Error within sendMsg. Could not read the keys' 'Error within sendMsg. Could not read the keys'
@ -1208,14 +1207,14 @@ class singleWorker(StoppableThread):
'Not bothering to include ackdata because we are' 'Not bothering to include ackdata because we are'
' sending to ourselves or a chan.' ' sending to ourselves or a chan.'
) )
fullAckPayload = '' fullAckPayload = b''
elif not protocol.checkBitfield( elif not protocol.checkBitfield(
behaviorBitfield, protocol.BITFIELD_DOESACK): behaviorBitfield, protocol.BITFIELD_DOESACK):
self.logger.info( self.logger.info(
'Not bothering to include ackdata because' 'Not bothering to include ackdata because'
' the receiver said that they won\'t relay it anyway.' ' the receiver said that they won\'t relay it anyway.'
) )
fullAckPayload = '' fullAckPayload = b''
else: else:
# The fullAckPayload is a normal msg protocol message # The fullAckPayload is a normal msg protocol message
# with the proof of work already completed that the # with the proof of work already completed that the
@ -1224,7 +1223,7 @@ class singleWorker(StoppableThread):
ackdata, toStreamNumber, TTL) ackdata, toStreamNumber, TTL)
payload += encodeVarint(len(fullAckPayload)) payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload payload += fullAckPayload
dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02' + \ dataToSign = pack('>Q', embeddedTime) + b'\x00\x00\x00\x02' + \
encodeVarint(1) + encodeVarint(toStreamNumber) + payload encodeVarint(1) + encodeVarint(toStreamNumber) + payload
signature = highlevelcrypto.sign( signature = highlevelcrypto.sign(
dataToSign, privSigningKeyHex, self.digestAlg) dataToSign, privSigningKeyHex, self.digestAlg)
@ -1234,10 +1233,10 @@ class singleWorker(StoppableThread):
# We have assembled the data that will be encrypted. # We have assembled the data that will be encrypted.
try: try:
encrypted = highlevelcrypto.encrypt( encrypted = highlevelcrypto.encrypt(
payload, "04" + hexlify(pubEncryptionKeyBase256) payload, b"04" + hexlify(pubEncryptionKeyBase256)
) )
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("highlevelcrypto.encrypt didn't work") self.logger.warning("highlevelcrypto.encrypt didn't work: {}".format(ex))
sqlExecute( sqlExecute(
'''UPDATE sent SET status='badkey' WHERE ackdata=? AND folder='sent' ''', '''UPDATE sent SET status='badkey' WHERE ackdata=? AND folder='sent' ''',
ackdata ackdata
@ -1248,13 +1247,13 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Problem: The recipient\'s encryption key is" "Problem: The recipient\'s encryption key is"
" no good. Could not encrypt message. %1" " no good. Could not encrypt message. {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
continue continue
encryptedPayload = pack('>Q', embeddedTime) encryptedPayload = pack('>Q', embeddedTime)
encryptedPayload += '\x00\x00\x00\x02' # object type: msg encryptedPayload += b'\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 / ( target = 2 ** 64 / (
@ -1288,8 +1287,8 @@ class singleWorker(StoppableThread):
time.time() - powStartTime, time.time() - powStartTime,
sizeof_fmt(nonce / (time.time() - powStartTime)) sizeof_fmt(nonce / (time.time() - powStartTime))
) )
except: # noqa:E722 except Exception as ex: # noqa:E722
self.logger.warning("Proof of Work exception") self.logger.warning("Proof of Work exception: {}".format(ex))
encryptedPayload = pack('>Q', nonce) + encryptedPayload encryptedPayload = pack('>Q', nonce) + encryptedPayload
@ -1317,7 +1316,7 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Message sent. Sent at %1" "Message sent. Sent at %1"
).arg(l10n.formatTimestamp())))) ).format(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(( queues.UISignalQueue.put((
@ -1326,8 +1325,8 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Message sent. Waiting for acknowledgement." "Message sent. Waiting for acknowledgement."
" Sent on %1" " Sent on {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
self.logger.info( self.logger.info(
'Broadcasting inv for my msg(within sendmsg function): %s', 'Broadcasting inv for my msg(within sendmsg function): %s',
@ -1437,7 +1436,7 @@ class singleWorker(StoppableThread):
TTL = TTL + helper_random.randomrandrange(-300, 300) 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 += b'\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:
@ -1492,7 +1491,7 @@ class singleWorker(StoppableThread):
"MainWindow", "MainWindow",
"Sending public key request. Waiting for reply." "Sending public key request. Waiting for reply."
" Requested at %1" " Requested at %1"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
def generateFullAckMessage(self, ackdata, _, TTL): def generateFullAckMessage(self, ackdata, _, TTL):

View File

@ -71,12 +71,16 @@ class MsgEncode(object):
def encodeSimple(self, message): def encodeSimple(self, message):
"""Handle simple encoding""" """Handle simple encoding"""
self.data = 'Subject:%(subject)s\nBody:%(body)s' % message data = 'Subject:%(subject)s\nBody:%(body)s' % message
self.data = data.encode('utf-8', 'backslashreplace')
self.length = len(self.data) self.length = len(self.data)
def encodeTrivial(self, message): def encodeTrivial(self, message):
"""Handle trivial encoding""" """Handle trivial encoding"""
self.data = message['body'] data = message['body']
if isinstance(data, str):
data = data.encode('utf-8', 'backslashreplace')
self.data = data
self.length = len(self.data) self.length = len(self.data)

View File

@ -336,7 +336,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if now < self.skipUntil: if now < self.skipUntil:
return True return True
for i in items: for i in items:
self.pendingUpload[str(i)] = now self.pendingUpload[i] = now
return True return True
def _command_inv(self, dandelion=False): def _command_inv(self, dandelion=False):

View File

@ -6,7 +6,7 @@ from collections import namedtuple
from random import choice, expovariate, sample from random import choice, expovariate, sample
from threading import RLock from threading import RLock
from time import time from time import time
from binascii import hexlify from binascii import hexlify, unhexlify
import network.connectionpool as connectionpool import network.connectionpool as connectionpool
import state import state
@ -113,7 +113,7 @@ class Dandelion: # pylint: disable=old-style-class
}.items(): }.items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
connection, v.stream, self.poissonTimeout()) connection, v.stream, self.poissonTimeout())
invQueue.put((v.stream, k, v.child)) invQueue.put((v.stream, unhexlify(k), v.child))
def maybeRemoveStem(self, connection): def maybeRemoveStem(self, connection):
""" """
@ -174,7 +174,7 @@ class Dandelion: # pylint: disable=old-style-class
with self.lock: with self.lock:
deadline = time() deadline = time()
toDelete = [ toDelete = [
[v.stream, k, v.child] for k, v in self.hashMap.items() [v.stream, unhexlify(k), v.child] for k, v in self.hashMap.items()
if v.timeout < deadline if v.timeout < deadline
] ]

View File

@ -92,13 +92,13 @@ class InvThread(StoppableThread):
connection.append_write_buf(protocol.CreatePacket( connection.append_write_buf(protocol.CreatePacket(
b'inv', b'inv',
addresses.encodeVarint( addresses.encodeVarint(
len(fluffs)) + ''.join(fluffs))) len(fluffs)) + b''.join(fluffs)))
if stems: if stems:
random.shuffle(stems) random.shuffle(stems)
connection.append_write_buf(protocol.CreatePacket( connection.append_write_buf(protocol.CreatePacket(
b'dinv', b'dinv',
addresses.encodeVarint( addresses.encodeVarint(
len(stems)) + ''.join(stems))) len(stems)) + b''.join(stems)))
invQueue.iterate() invQueue.iterate()
for _ in range(len(chunk)): for _ in range(len(chunk)):