diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 6fa31a47..c37c07fb 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -147,14 +147,11 @@ class objectProcessor(threading.Thread): ' WHERE ackdata=?', 'ackreceived', int(time.time()), data[readPosition:]) queues.UISignalQueue.put(( - 'updateSentItemStatusByAckdata', - ( - data[readPosition:], - tr._translate( + 'updateSentItemStatusByAckdata', ( + data[readPosition:], tr._translate( "MainWindow", - "Acknowledgement of the message received %1" - ).arg(l10n.formatTimestamp()) - ) + "Acknowledgement of the message received {0}" + ).format(l10n.formatTimestamp())) )) else: logger.debug('This object is not an acknowledgement bound for me.') diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 012313ac..cf94dbe2 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -24,14 +24,13 @@ import protocol import queues import shared import state -import tr from addresses import ( - calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint -) + calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint) from bmconfigparser import BMConfigParser from helper_sql import sqlExecute, sqlQuery from inventory import Inventory from network import knownnodes, StoppableThread +from tr import _translate def sizeof_fmt(num, suffix='h/s'): @@ -215,9 +214,8 @@ class singleWorker(StoppableThread): return privSigningKeyHex, privEncryptionKeyHex, \ pubSigningKey, pubEncryptionKey - def _doPOWDefaults(self, payload, TTL, - log_prefix='', - log_time=False): + def _doPOWDefaults( + self, payload, TTL, log_prefix='', log_time=False): target = 2 ** 64 / ( defaults.networkDefaultProofOfWorkNonceTrialsPerByte * ( len(payload) + 8 + @@ -243,14 +241,16 @@ class singleWorker(StoppableThread): 'PoW took %.1f seconds, speed %s.', delta, sizeof_fmt(nonce / delta) ) - except: # NameError + except NameError: pass payload = pack('>Q', nonce) + payload return payload def doPOWForMyV2Pubkey(self, adressHash): - """ 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 + """ # Look up my stream number based on my address hash myAddress = shared.myAddressesByHash[adressHash] # status @@ -306,13 +306,14 @@ class singleWorker(StoppableThread): def sendOutOrStoreMyV3Pubkey(self, adressHash): """ - If this isn't a chan address, this function assembles the pubkey data, does the necessary POW and sends it out. - If it *is* a chan then it assembles the pubkey and stores is in the pubkey table so that we can send messages - to "ourselves". + If this isn't a chan address, this function assembles the pubkey + data, does the necessary POW and sends it out. + If it *is* a chan then it assembles the pubkey and stores it in + the pubkey table so that we can send messages to "ourselves". """ try: myAddress = shared.myAddressesByHash[adressHash] - except: + except KeyError: # The address has been deleted. return if BMConfigParser().safeGetBoolean(myAddress, 'chan'): @@ -389,9 +390,10 @@ class singleWorker(StoppableThread): def sendOutOrStoreMyV4Pubkey(self, myAddress): """ - It doesn't send directly anymore. It put is to a queue for another thread to send at an appropriate time, - whereas in the past it directly appended it to the outgoing buffer, I think. Same with all the other methods in - this class. + It doesn't send directly anymore. It put is to a queue for + another thread to send at an appropriate time, whereas in the + past it directly appended it to the outgoing buffer, I think. + Same with all the other methods in this class. """ if not BMConfigParser().has_section(myAddress): # The address has been deleted. @@ -518,7 +520,10 @@ class singleWorker(StoppableThread): queues.invQueue.put((streamNumber, inventoryHash)) def sendBroadcast(self): - """Send a broadcast-type object (assemble the object, perform PoW and put it to the inv announcement queue)""" + """ + Send a broadcast-type object (assemble the object, perform PoW + and put it to the inv announcement queue) + """ # Reset just in case sqlExecute( '''UPDATE sent SET status='broadcastqueued' ''' @@ -549,8 +554,7 @@ class singleWorker(StoppableThread): except: queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Error! Could not find sender address" " (your address) in the keys.dat file.")) @@ -640,8 +644,7 @@ class singleWorker(StoppableThread): queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Doing work necessary to send broadcast...")) )) @@ -673,11 +676,9 @@ class singleWorker(StoppableThread): queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( - "MainWindow", - "Broadcast sent on %1" - ).arg(l10n.formatTimestamp())) + ackdata, _translate( + "MainWindow", "Broadcast sent on {0}" + ).format(l10n.formatTimestamp())) )) # Update the status of the message in the 'sent' table to have @@ -689,7 +690,10 @@ class singleWorker(StoppableThread): ) def sendMsg(self): - """Send a message-type object (assemble the object, perform PoW and put it to the inv announcement queue)""" + """ + Send a message-type object (assemble the object, perform PoW + and put it to the inv announcement queue) + """ # pylint: disable=too-many-nested-blocks # Reset just in case sqlExecute( @@ -785,8 +789,7 @@ class singleWorker(StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( - toaddress, - tr._translate( + toaddress, _translate( "MainWindow", "Encryption key was requested earlier.")) )) @@ -858,8 +861,7 @@ class singleWorker(StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( - toaddress, - tr._translate( + toaddress, _translate( "MainWindow", "Sending a request for the" " recipient\'s encryption key.")) @@ -883,8 +885,7 @@ class singleWorker(StoppableThread): state.ackdataForWhichImWatching[ackdata] = 0 queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Looking up the receiver\'s public key")) )) @@ -941,15 +942,14 @@ class singleWorker(StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _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())) + " your settings. {0}" + ).format(l10n.formatTimestamp())) )) # if the human changes their setting and then # sends another message or restarts their client, @@ -972,8 +972,7 @@ class singleWorker(StoppableThread): defaults.networkDefaultPayloadLengthExtraBytes queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Doing work necessary to send message.\n" "There is no required difficulty for" @@ -1005,32 +1004,18 @@ class singleWorker(StoppableThread): 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 - ) - ) - ) - ) - ) - + queues.UISignalQueue.put(( + 'updateSentItemStatusByAckdata', ( + ackdata, _translate( + "MainWindow", + "Doing work necessary to send message.\n" + "Receiver\'s required difficulty: {0} and {1}" + ).format( + float(requiredAverageProofOfWorkNonceTrialsPerByte) / + defaults.networkDefaultProofOfWorkNonceTrialsPerByte, + float(requiredPayloadLengthExtraBytes) / + defaults.networkDefaultPayloadLengthExtraBytes)) + )) if status != 'forcepow': maxacceptablenoncetrialsperbyte = BMConfigParser().getint( 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte') @@ -1050,18 +1035,19 @@ class singleWorker(StoppableThread): ackdata) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _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())))) + "Problem: The work demanded by the" + " recipient ({0} and {1}) is more" + " difficult than you are willing" + " to do. {2}" + ).format( + float(requiredAverageProofOfWorkNonceTrialsPerByte) / + defaults.networkDefaultProofOfWorkNonceTrialsPerByte, + float(requiredPayloadLengthExtraBytes) / + defaults.networkDefaultPayloadLengthExtraBytes, + l10n.formatTimestamp())) + )) continue else: # if we are sending a message to ourselves or a chan.. self.logger.info('Sending a message.') @@ -1075,15 +1061,14 @@ class singleWorker(StoppableThread): except Exception as err: queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _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())) + " message. {0}" + ).format(l10n.formatTimestamp())) )) self.logger.error( 'Error within sendMsg. Could not read the keys' @@ -1100,8 +1085,7 @@ class singleWorker(StoppableThread): defaults.networkDefaultPayloadLengthExtraBytes queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Doing work necessary to send message.")) )) @@ -1123,8 +1107,7 @@ class singleWorker(StoppableThread): except: queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Error! Could not find sender address" " (your address) in the keys.dat file.")) @@ -1177,8 +1160,7 @@ class singleWorker(StoppableThread): # 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( - ackdata, toStreamNumber, TTL) + fullAckPayload = self.generateFullAckMessage(ackdata, TTL) payload += encodeVarint(len(fullAckPayload)) payload += fullAckPayload dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02' + \ @@ -1190,8 +1172,7 @@ class singleWorker(StoppableThread): # We have assembled the data that will be encrypted. try: encrypted = highlevelcrypto.encrypt( - payload, "04" + hexlify(pubEncryptionKeyBase256) - ) + payload, "04" + hexlify(pubEncryptionKeyBase256)) except: sqlExecute( '''UPDATE sent SET status='badkey' WHERE ackdata=? AND folder='sent' ''', @@ -1199,12 +1180,11 @@ class singleWorker(StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Problem: The recipient\'s encryption key is" - " no good. Could not encrypt message. %1" - ).arg(l10n.formatTimestamp())) + " no good. Could not encrypt message. {0}" + ).format(l10n.formatTimestamp())) )) continue @@ -1268,21 +1248,19 @@ class singleWorker(StoppableThread): not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( - "MainWindow", - "Message sent. Sent at %1" - ).arg(l10n.formatTimestamp())))) + ackdata, _translate( + "MainWindow", "Message sent. Sent at {0}" + ).format(l10n.formatTimestamp())) + )) else: # not sending to a chan or one of my addresses queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, _translate( "MainWindow", "Message sent. Waiting for acknowledgement." - " Sent on %1" - ).arg(l10n.formatTimestamp())) + " Sent on {0}" + ).format(l10n.formatTimestamp())) )) self.logger.info( 'Broadcasting inv for my msg(within sendmsg function): %s', @@ -1411,8 +1389,7 @@ class singleWorker(StoppableThread): queues.UISignalQueue.put(('updateStatusBar', statusbar)) queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( - toAddress, - tr._translate( + toAddress, _translate( "MainWindow", "Doing work necessary to request encryption key.")) )) @@ -1436,30 +1413,31 @@ class singleWorker(StoppableThread): int(time.time()), retryNumber + 1, sleeptill, toAddress) queues.UISignalQueue.put(( - 'updateStatusBar', - tr._translate( + 'updateStatusBar', _translate( "MainWindow", "Broadcasting the public key request. This program will" " auto-retry if they are offline.") )) queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( - toAddress, - tr._translate( + toAddress, _translate( "MainWindow", "Sending public key request. Waiting for reply." - " Requested at %1" - ).arg(l10n.formatTimestamp())) + " Requested at {0}" + ).format(l10n.formatTimestamp())) )) - def generateFullAckMessage(self, ackdata, _, TTL): - """ - It might be perfectly fine to just use the same TTL for the ackdata that we use for the message. But I would - rather it be more difficult for attackers to associate ackData with the associated msg object. However, users - would want the TTL of the acknowledgement to be about the same as they set for the message itself. So let's set - the TTL of the acknowledgement to be in one of three 'buckets': 1 hour, 7 days, or 28 days, whichever is - relatively close to what the user specified. - """ + def generateFullAckMessage(self, ackdata, TTL): + """Create ACK packet""" + # It might be perfectly fine to just use the same TTL for + # the ackdata that we use for the message. But I would rather + # it be more difficult for attackers to associate ackData with + # the associated msg object. However, users would want the TTL + # of the acknowledgement to be about the same as they set + # for the message itself. So let's set the TTL of the + # acknowledgement to be in one of three 'buckets': 1 hour, 7 + # days, or 28 days, whichever is relatively close to what the + # user specified. if TTL < 24 * 60 * 60: # 1 day TTL = 24 * 60 * 60 # 1 day elif TTL < 7 * 24 * 60 * 60: # 1 week diff --git a/src/namecoin.py b/src/namecoin.py index ae2bde79..33319bda 100644 --- a/src/namecoin.py +++ b/src/namecoin.py @@ -11,10 +11,10 @@ import socket import sys import defaults -import tr # translate from addresses import decodeAddress from bmconfigparser import BMConfigParser from debug import logger +from tr import _translate configSection = "bitmessagesettings" @@ -22,7 +22,6 @@ configSection = "bitmessagesettings" class RPCError(Exception): """Error thrown when the RPC call returns an error.""" - error = None def __init__(self, data): @@ -47,8 +46,8 @@ class namecoinConnection(object): def __init__(self, options=None): """ - Initialise. If options are given, take the connection settings from - them instead of loading from the configs. This can be used to test + Initialise. If options are given, take the connection settings from + them instead of loading from the configs. This can be used to test currently entered connection settings in the config dialog without actually changing the values (yet). """ @@ -73,7 +72,7 @@ class namecoinConnection(object): def query(self, string): """ Query for the bitmessage address corresponding to the given identity - string. If it doesn't contain a slash, id/ is prepended. We return + string. If it doesn't contain a slash, id/ is prepended. We return the result as (Error, Address) pair, where the Error is an error message to display or None in case of success. """ @@ -92,9 +91,9 @@ class namecoinConnection(object): res = self.callRPC("data", ["getValue", string]) res = res["reply"] if not res: - return (tr._translate( - "MainWindow", 'The name %1 was not found.' - ).arg(unicode(string)), None) + return (_translate( + "MainWindow", "The name {0} was not found." + ).format(string), None) else: assert False except RPCError as exc: @@ -103,17 +102,17 @@ class namecoinConnection(object): errmsg = exc.error["message"] else: errmsg = exc.error - return (tr._translate( - "MainWindow", 'The namecoin query failed (%1)' - ).arg(unicode(errmsg)), None) + return (_translate( + "MainWindow", "The namecoin query failed ({0})" + ).format(errmsg), None) except AssertionError: - return (tr._translate( - "MainWindow", 'Unknown namecoin interface type: %1' - ).arg(unicode(self.nmctype)), None) + return (_translate( + "MainWindow", "Unknown namecoin interface type: {0}" + ).format(self.nmctype), None) except Exception: logger.exception("Namecoin query exception") - return (tr._translate( - "MainWindow", 'The namecoin query failed.'), None) + return (_translate( + "MainWindow", "The namecoin query failed."), None) try: res = json.loads(res) @@ -130,14 +129,16 @@ class namecoinConnection(object): return ( None, "%s <%s>" % (display_name, res) ) if valid else ( - tr._translate( + _translate( "MainWindow", - 'The name %1 has no associated Bitmessage address.' - ).arg(unicode(string)), None) + "The name {0} has no associated Bitmessage address." + ).format(string), + None + ) def test(self): """ - Test the connection settings. This routine tries to query a "getinfo" + Test the connection settings. This routine tries to query a "getinfo" command, and builds either an error message or a success message with some info from it. """ @@ -157,33 +158,36 @@ class namecoinConnection(object): versStr = "0.%d.%d" % (v1, v2) else: versStr = "0.%d.%d.%d" % (v1, v2, v3) - message = ( - 'success', - tr._translate( + return ( + 'success', _translate( "MainWindow", - 'Success! Namecoind version %1 running.').arg( - unicode(versStr))) + "Success! Namecoind version {0} running." + ).format(versStr) + ) elif self.nmctype == "nmcontrol": res = self.callRPC("data", ["status"]) prefix = "Plugin data running" if ("reply" in res) and res["reply"][:len(prefix)] == prefix: - return ('success', tr._translate("MainWindow", 'Success! NMControll is up and running.')) + return ( + 'success', _translate( + "MainWindow", + "Success! NMControll is up and running.") + ) logger.error("Unexpected nmcontrol reply: %s", res) - message = ('failed', tr._translate("MainWindow", 'Couldn\'t understand NMControl.')) + return ( + 'failed', _translate( + "MainWindow", "Couldn\'t understand NMControl.") + ) else: - print "Unsupported Namecoin type" - sys.exit(1) - - return message + sys.exit("Unsupported Namecoin type") except Exception: logger.info("Namecoin connection test failure") return ( - 'failed', - tr._translate( + 'failed', _translate( "MainWindow", "The connection to namecoin failed.") ) @@ -243,7 +247,9 @@ class namecoinConnection(object): return result def queryServer(self, data): - """Helper routine sending data to the RPC server and returning the result.""" + """ + Helper routine sending data to the RPC server and returning the result. + """ try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) diff --git a/src/network/tcp.py b/src/network/tcp.py index 1b30a0a2..fa2149b8 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -139,9 +139,10 @@ class TCPConnection(BMProto, TLSDispatcher): 'updateStatusBar', _translate( "MainWindow", - "The time on your computer, %1, may be wrong. " + "The time on your computer, {0}, may be wrong. " "Please verify your settings." - ).arg(l10n.formatTimestamp()))) + ).format(l10n.formatTimestamp()) + )) def state_connection_fully_established(self): """ diff --git a/src/upnp.py b/src/upnp.py index 34111afd..1891ef42 100644 --- a/src/upnp.py +++ b/src/upnp.py @@ -269,9 +269,12 @@ class uPnPThread(StoppableThread): with knownnodes.knownNodesLock: knownnodes.addKnownNode( 1, self_peer, is_self=True) - queues.UISignalQueue.put(('updateStatusBar', tr._translate( - "MainWindow", 'UPnP port mapping established on port %1' - ).arg(str(self.extPort)))) + queues.UISignalQueue.put(( + 'updateStatusBar', tr._translate( + "MainWindow", + "UPnP port mapping established on port {0}" + ).format(self.extPort) + )) break except socket.timeout: pass