From 512bb41a03bcc08f4beb3e19415e122ae0a9ec75 Mon Sep 17 00:00:00 2001 From: Dmitri Bogomolov <4glitch@gmail.com> Date: Thu, 22 Feb 2018 15:09:40 +0200 Subject: [PATCH] No more arg() call on result of _translate() --- src/class_objectProcessor.py | 27 +++++----- src/class_singleWorker.py | 96 ++++++++++++++++-------------------- src/namecoin.py | 57 ++++++++++++++++----- src/upnp.py | 10 +++- 4 files changed, 109 insertions(+), 81 deletions(-) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 181ce30e..ba98075e 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -3,19 +3,16 @@ import threading import shared import hashlib import random -from struct import unpack, pack -import sys +from struct import unpack import string -from subprocess import call # used when the API must execute an outside program +# used when the API must execute an outside program +from subprocess import call import traceback from binascii import hexlify -from pyelliptic.openssl import OpenSSL import highlevelcrypto from addresses import * from bmconfigparser import BMConfigParser -import helper_generic -from helper_generic import addDataPadding import helper_bitcoin import helper_inbox import helper_msgcoding @@ -29,6 +26,7 @@ import tr from debug import logger import l10n + class objectProcessor(threading.Thread): """ The objectProcessor thread, of which there is only one, receives network @@ -105,15 +103,20 @@ class objectProcessor(threading.Thread): if data[readPosition:] in shared.ackdataForWhichImWatching: logger.info('This object is an acknowledgement bound for me.') del shared.ackdataForWhichImWatching[data[readPosition:]] - sqlExecute('UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?', - 'ackreceived', - int(time.time()), - data[readPosition:]) - queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (data[readPosition:], tr._translate("MainWindow",'Acknowledgement of the message received %1').arg(l10n.formatTimestamp())))) + sqlExecute( + 'UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?', + 'ackreceived', int(time.time()), data[readPosition:]) + queues.UISignalQueue.put(( + 'updateSentItemStatusByAckdata', ( + data[readPosition:], tr._translate( + "MainWindow", + "Acknowledgement of the message received {0}" + ).format(l10n.formatTimestamp())) + )) else: logger.debug('This object is not an acknowledgement bound for me.') - + def processgetpubkey(self, data): if len(data) > 200: logger.info('getpubkey is abnormally long. Sanity check failed. Ignoring object.') diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index c95d484a..1a159988 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -34,6 +34,7 @@ from helper_sql import sqlQuery, sqlExecute # This thread, of which there is only one, does the heavy lifting: # calculating POWs. + def sizeof_fmt(num, suffix='h/s'): for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: @@ -610,11 +611,9 @@ class singleWorker(threading.Thread, StoppableThread): queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( - "MainWindow", - "Broadcast sent on %1" - ).arg(l10n.formatTimestamp())) + ackdata, tr._translate( + "MainWindow", "Broadcast sent on {0}" + ).format(l10n.formatTimestamp())) )) # Update the status of the message in the 'sent' table to have @@ -881,8 +880,8 @@ class singleWorker(threading.Thread, StoppableThread): " 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, @@ -940,19 +939,16 @@ class singleWorker(threading.Thread, StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + 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 - ))))) + "Receiver\'s required difficulty: {0} and {1}" + ).format( + float(requiredAverageProofOfWorkNonceTrialsPerByte) + / defaults.networkDefaultProofOfWorkNonceTrialsPerByte, + float(requiredPayloadLengthExtraBytes) + / defaults.networkDefaultPayloadLengthExtraBytes)) + )) if status != 'forcepow': if (requiredAverageProofOfWorkNonceTrialsPerByte > BMConfigParser().getint( @@ -980,20 +976,18 @@ class singleWorker(threading.Thread, StoppableThread): ackdata) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + 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())) + "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.. @@ -1015,8 +1009,8 @@ class singleWorker(threading.Thread, StoppableThread): " 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())) )) logger.error( 'Error within sendMsg. Could not read the keys' @@ -1123,8 +1117,7 @@ class singleWorker(threading.Thread, 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=?''', @@ -1132,12 +1125,11 @@ class singleWorker(threading.Thread, StoppableThread): ) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( + ackdata, tr._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 @@ -1202,22 +1194,19 @@ class singleWorker(threading.Thread, StoppableThread): behaviorBitfield, protocol.BITFIELD_DOESACK): queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( - ackdata, - tr._translate( - "MainWindow", - "Message sent. Sent at %1" - ).arg(l10n.formatTimestamp())) + ackdata, tr._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, tr._translate( "MainWindow", "Message sent. Waiting for acknowledgement." - " Sent on %1" - ).arg(l10n.formatTimestamp())) + " Sent on {0}" + ).format(l10n.formatTimestamp())) )) logger.info( 'Broadcasting inv for my msg(within sendmsg function): %s', @@ -1372,23 +1361,22 @@ class singleWorker(threading.Thread, StoppableThread): int(time.time()), retryNumber + 1, sleeptill, toAddress) queues.UISignalQueue.put(( - 'updateStatusBar', - tr._translate( + 'updateStatusBar', tr._translate( "MainWindow", "Broadcasting the public key request. This program will" " auto-retry if they are offline.") )) queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( - toAddress, - tr._translate( + toAddress, tr._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, toStreamNumber, 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 diff --git a/src/namecoin.py b/src/namecoin.py index 9b3c3c3e..17c1f7dd 100644 --- a/src/namecoin.py +++ b/src/namecoin.py @@ -28,7 +28,7 @@ import os from bmconfigparser import BMConfigParser import defaults -import tr # translate +import tr # FIXME: from debug import logger crashes PyBitmessage due to a circular # dependency. The debug module will also override/disable logging.getLogger() @@ -37,6 +37,7 @@ import logging as logger configSection = "bitmessagesettings" + # Error thrown when the RPC call returns an error. class RPCError (Exception): error = None @@ -85,20 +86,25 @@ class namecoinConnection (object): # 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. - def query (self, string): - slashPos = string.find ("/") + def query(self, string): + slashPos = string.find("/") if slashPos < 0: string = "id/" + string try: if self.nmctype == "namecoind": - res = self.callRPC ("name_show", [string]) + res = self.callRPC("name_show", [string]) res = res["value"] elif self.nmctype == "nmcontrol": - res = self.callRPC ("data", ["getValue", string]) + res = self.callRPC("data", ["getValue", string]) res = res["reply"] - if res == False: - return (tr._translate("MainWindow",'The name %1 was not found.').arg(unicode(string)), None) + if res is False: + return ( + tr._translate( + "MainWindow", "The name {0} was not found." + ).format(string), + None + ) else: assert False except RPCError as exc: @@ -107,16 +113,29 @@ 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 ( + tr._translate( + "MainWindow", "The namecoin query failed ({0})" + ).format(errmsg), + None + ) except Exception as exc: logger.exception("Namecoin query exception") - return (tr._translate("MainWindow",'The namecoin query failed.'), None) + return ( + tr._translate("MainWindow", "The namecoin query failed."), + None + ) try: - val = json.loads (res) + val = json.loads(res) except: logger.exception("Namecoin query json exception") - return (tr._translate("MainWindow",'The name %1 has no valid JSON data.').arg(unicode(string)), None) + return ( + tr._translate( + "MainWindow", "The name {0} has no valid JSON data." + ).format(string), + None + ) if "bitmessage" in val: if "name" in val: @@ -124,7 +143,13 @@ class namecoinConnection (object): else: ret = val["bitmessage"] return (None, ret) - return (tr._translate("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None) + return ( + tr._translate( + "MainWindow", + "The name {0} has no associated Bitmessage address." + ).format(string), + None + ) # Test the connection settings. This routine tries to query a "getinfo" # command, and builds either an error message or a success message with @@ -146,7 +171,13 @@ class namecoinConnection (object): versStr = "0.%d.%d" % (v1, v2) else: versStr = "0.%d.%d.%d" % (v1, v2, v3) - return ('success', tr._translate("MainWindow",'Success! Namecoind version %1 running.').arg(unicode(versStr)) ) + return ( + 'success', + tr._translate( + "MainWindow", + "Success! Namecoind version {0} running." + ).format(versStr) + ) elif self.nmctype == "nmcontrol": res = self.callRPC ("data", ["status"]) diff --git a/src/upnp.py b/src/upnp.py index 46d55956..710cd72f 100644 --- a/src/upnp.py +++ b/src/upnp.py @@ -3,7 +3,7 @@ import httplib from random import randint import socket -from struct import unpack, pack +from struct import unpack import threading import time from bmconfigparser import BMConfigParser @@ -14,6 +14,7 @@ import shared import state import tr + def createRequestXML(service, action, arguments=None): from xml.dom.minidom import Document @@ -230,7 +231,12 @@ class uPnPThread(threading.Thread, StoppableThread): logger.debug("Found UPnP router at %s", ip) self.routers.append(newRouter) self.createPortMapping(newRouter) - 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) + )) # retry connections so that the submitted port is refreshed with shared.alreadyAttemptedConnectionsListLock: shared.alreadyAttemptedConnectionsList.clear()