From c904ea368ef5c399e2dacc5d92986cc607075964 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 21:27:47 -0800 Subject: [PATCH 01/16] Cleanup line spacing per PEP8 guidelines --- spmt.py | 34 +++++++-------- src/apiClient.py | 6 +-- src/blockbookClient.py | 11 ----- src/constants.py | 4 +- src/cryptoIDClient.py | 9 ---- src/database.py | 60 +------------------------ src/hwdevice.py | 10 ----- src/ledgerClient.py | 25 ----------- src/mainWindow.py | 65 ---------------------------- src/masternode.py | 10 ----- src/misc.py | 41 ------------------ src/pivx_b58.py | 1 - src/pivx_hashlib.py | 6 +-- src/pivx_parser.py | 1 + src/proposals.py | 1 + src/qt/dlg_budgetProjection.py | 24 ++++------ src/qt/dlg_configureRPCservers.py | 33 +++----------- src/qt/dlg_findCollTx.py | 13 ------ src/qt/dlg_mnStatus.py | 9 ++-- src/qt/dlg_pinMatrix.py | 9 +--- src/qt/dlg_proposalDetails.py | 3 -- src/qt/dlg_selectMNs.py | 25 +++++------ src/qt/dlg_signmessage.py | 20 +-------- src/qt/dlg_sweepAll.py | 27 ------------ src/qt/guiHeader.py | 1 + src/qt/gui_tabGovernance.py | 9 +--- src/qt/gui_tabMNConf.py | 20 +++------ src/qt/gui_tabMain.py | 8 ---- src/qt/gui_tabRewards.py | 5 --- src/rpcClient.py | 42 +----------------- src/spmtApp.py | 17 +------- src/tabGovernance.py | 36 +-------------- src/tabMNConf.py | 28 ------------ src/tabMain.py | 30 ------------- src/tabRewards.py | 40 ----------------- src/tests/testHwDeviceMethods.py | 65 +++++++++++----------------- src/tests/testMasternodeMethods.py | 21 +++------ src/tests/testPivx_b58Methods.py | 27 ++++-------- src/tests/testPivx_hashlibMethods.py | 13 +++--- src/tests/testUtilsMethods.py | 19 +++----- src/threads.py | 1 + src/trezorClient.py | 39 ----------------- src/txCache.py | 3 +- src/utils.py | 14 +----- src/watchdogThreads.py | 4 +- src/workerThread.py | 2 + 46 files changed, 128 insertions(+), 763 deletions(-) diff --git a/spmt.py b/spmt.py index db244b5..2f944e0 100644 --- a/spmt.py +++ b/spmt.py @@ -7,9 +7,9 @@ import os import sys import time - + if __name__ == '__main__': - + # parse input if there's `--clear[?]Data` flags import argparse parser = argparse.ArgumentParser(description='Secure PIVX Masternode Tool') @@ -27,12 +27,12 @@ parser.set_defaults(clearRpcData=False) parser.set_defaults(clearTxCache=False) args = parser.parse_args() - + if getattr( sys, 'frozen', False ) : # running in a bundle sys.path.append(os.path.join(sys._MEIPASS, 'src')) imgDir = os.path.join(sys._MEIPASS, 'img') - + # if linux export qt plugins path if sys.platform == 'linux': os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'PyQt5', 'Qt', 'plugins') @@ -41,24 +41,24 @@ # running live sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src')) imgDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img') - + from PyQt5.QtWidgets import QApplication from PyQt5.Qt import Qt, QPixmap, QSplashScreen, QProgressBar, QColor, QPalette, QLabel - + from misc import updateSplash from spmtApp import App - + # Create App app = QApplication(sys.argv) - + ### -- style stuff spmtLogo_file = os.path.join(imgDir, 'splashscreen.png') labelstyle = "QLabel { font-size: 14px; color: purple; font-style: italic; text-align: center;}" barStyle = "QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #372f43,stop: 0.6 #5c4c7a, stop: 0.8 #663399);border-bottom-right-radius: 7px;border-bottom-left-radius: 7px;border-top: 2px solid #8A2BE2;}" - + splash_pix = QPixmap(spmtLogo_file) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) - + progressBar = QProgressBar(splash) progressBar.setGeometry(0, splash_pix.height()-13, splash_pix.width(), 13) progressBar.setStyleSheet(barStyle) @@ -68,10 +68,10 @@ label.setStyleSheet(labelstyle) label.setGeometry((splash_pix.width()-500)/2, splash_pix.height()-40, 500, 20) label.setAlignment(Qt.AlignCenter) - + progressText = "loading..." label.setText(progressText) - + splash.show() for i in range(0, 100): @@ -81,12 +81,12 @@ t = time.time() while time.time() < t + 0.01: app.processEvents() - + ### -------------- - + # Create QMainWindow Widget ex = App(imgDir, app, args) - + # Close Splashscreen splash.close() @@ -102,7 +102,5 @@ app.deleteLater() except Exception as e: print(e) - + sys.exit() - - diff --git a/src/apiClient.py b/src/apiClient.py index 09457f0..2205db8 100644 --- a/src/apiClient.py +++ b/src/apiClient.py @@ -9,8 +9,8 @@ from misc import getCallerName, getFunctionName, printException, printError -def process_api_exceptions(func): +def process_api_exceptions(func): def process_api_exceptions_int(*args, **kwargs): client = args[0] try: @@ -28,19 +28,17 @@ def process_api_exceptions_int(*args, **kwargs): return process_api_exceptions_int + class ApiClient: def __init__(self, isTestnet=False): self.isTestnet = isTestnet self.api = BlockBookClient(isTestnet) - @process_api_exceptions def getAddressUtxos(self, address): return self.api.getAddressUtxos(address) - @process_api_exceptions def getBalance(self, address): return self.api.getBalance(address) - diff --git a/src/blockbookClient.py b/src/blockbookClient.py index eeba770..058bfbe 100644 --- a/src/blockbookClient.py +++ b/src/blockbookClient.py @@ -9,9 +9,7 @@ from misc import getCallerName, getFunctionName, printException - def process_blockbook_exceptions(func): - def process_blockbook_exceptions_int(*args, **kwargs): client = args[0] try: @@ -34,8 +32,6 @@ def process_blockbook_exceptions_int(*args, **kwargs): return process_blockbook_exceptions_int - - class BlockBookClient: def __init__(self, isTestnet=False): @@ -45,8 +41,6 @@ def __init__(self, isTestnet=False): else: self.url = "https://explorer.pivx.link" - - def checkResponse(self, method, param=""): url = self.url + "/api/%s" % method if param != "": @@ -57,8 +51,6 @@ def checkResponse(self, method, param=""): return data raise Exception("Invalid response") - - @process_blockbook_exceptions def getAddressUtxos(self, address): utxos = self.checkResponse("utxo", address) @@ -67,9 +59,6 @@ def getAddressUtxos(self, address): u["script"] = "" return utxos - - @process_blockbook_exceptions def getBalance(self, address): return self.checkResponse("address", address)["balance"] - diff --git a/src/constants.py b/src/constants.py index 7f1cb83..6754374 100644 --- a/src/constants.py +++ b/src/constants.py @@ -32,11 +32,13 @@ SECONDS_IN_2_MONTHS = 60 * 24 * 60 * 60 MAX_INPUTS_NO_WARNING = 75 + def NewSigsActive(nHeight, fTestnet=False): if fTestnet: return (nHeight >= NEW_SIGS_HEIGHT_TESTNET) return (nHeight >= NEW_SIGS_HEIGHT_MAINNET) + DEFAULT_MN_CONF = { "name": "", "ip": "", @@ -66,13 +68,11 @@ def NewSigsActive(nHeight, fTestnet=False): "isTestnetRPC": False } - trusted_RPC_Servers = [ ["https", "amsterdam.randomzebra.party:8080", "spmtUser_ams", "WUss6sr8956S5Paex254"], ["https", "losangeles.randomzebra.party:8080", "spmtUser_la", "8X88u7TuefPm7mQaJY52"], ["https", "singapore.randomzebra.party:8080", "spmtUser_sing", "ZyD936tm9dvqmMP8A777"]] - HW_devices = [ # (model name, api index) ("LEDGER Nano", 0), diff --git a/src/cryptoIDClient.py b/src/cryptoIDClient.py index 94cf62b..45fb180 100644 --- a/src/cryptoIDClient.py +++ b/src/cryptoIDClient.py @@ -13,7 +13,6 @@ def process_cryptoID_exceptions(func): - def process_cryptoID_exceptions_int(*args, **kwargs): try: return func(*args, **kwargs) @@ -25,7 +24,6 @@ def process_cryptoID_exceptions_int(*args, **kwargs): return process_cryptoID_exceptions_int - def UTXOS_cryptoID_to_trezor(utxos): # convert JSON labels new_utxos = [] @@ -50,8 +48,6 @@ def __init__(self, isTestnet=False): self.url = "http://chainz.cryptoid.info/pivx/api.dws" self.parameters = {} - - def checkResponse(self, parameters): key = choice(api_keys) parameters['key'] = key @@ -61,8 +57,6 @@ def checkResponse(self, parameters): return data return None - - @process_cryptoID_exceptions def getAddressUtxos(self, address): self.parameters = {} @@ -74,12 +68,9 @@ def getAddressUtxos(self, address): else: return UTXOS_cryptoID_to_trezor(res['unspent_outputs']) - - @process_cryptoID_exceptions def getBalance(self, address): self.parameters = {} self.parameters['q'] = 'getbalance' self.parameters['a'] = address return self.checkResponse(self.parameters) - diff --git a/src/database.py b/src/database.py index 19d54b3..64a5b32 100644 --- a/src/database.py +++ b/src/database.py @@ -12,6 +12,7 @@ from proposals import Proposal, vote_type, vote_index from misc import printDbg, getCallerName, getFunctionName, printException, add_defaultKeys_to_dict + class Database(): ''' @@ -26,8 +27,6 @@ def __init__(self, app): self.conn = None printDbg("DB: Initialized") - - def open(self): printDbg("DB: Opening...") if self.isOpen: @@ -49,8 +48,6 @@ def open(self): err_msg = 'SQLite initialization error' printException(getCallerName(), getFunctionName(), err_msg, e) - - def close(self): printDbg("DB: closing...") if not self.isOpen: @@ -71,8 +68,6 @@ def close(self): err_msg = 'SQLite closing error' printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def getCursor(self): if self.isOpen: self.lock.acquire() @@ -89,8 +84,6 @@ def getCursor(self): else: raise Exception("Database closed") - - def releaseCursor(self, rollingBack=False, vacuum=False): if self.isOpen: try: @@ -119,8 +112,6 @@ def releaseCursor(self, rollingBack=False, vacuum=False): else: raise Exception("Database closed") - - def initTables(self): printDbg("DB: Initializing tables...") try: @@ -171,13 +162,10 @@ def initTables(self): printDbg("DB: Tables initialized") - except Exception as e: err_msg = 'error initializing tables' printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def initTable_RPC(self, cursor): s = trusted_RPC_Servers # Insert Default public trusted servers @@ -194,7 +182,6 @@ def initTable_RPC(self, cursor): " (?, ?, ?, ?, ?);", (0, "http", "127.0.0.1:51473", "rpcUser", "rpcPass")) - ''' General methods ''' @@ -220,8 +207,6 @@ def clearTable(self, table_name): if cleared_RPC: self.app.sig_changed_rpcServers.emit() - - def removeTable(self, table_name): printDbg("DB: Dropping table %s..." % table_name) try: @@ -236,8 +221,6 @@ def removeTable(self, table_name): finally: self.releaseCursor(vacuum=True) - - ''' RPC servers methods ''' @@ -263,8 +246,6 @@ def addRPCServer(self, protocol, host, user, passwd): if added_RPC: self.app.sig_changed_rpcServers.emit() - - def editRPCServer(self, protocol, host, user, passwd, id): printDbg("DB: Editing RPC server with id %d" % id) changed_RPC = False @@ -286,8 +267,6 @@ def editRPCServer(self, protocol, host, user, passwd, id): if changed_RPC: self.app.sig_changed_rpcServers.emit() - - def getRPCServers(self, custom, id=None): tableName = "CUSTOM_RPC_SERVERS" if custom else "PUBLIC_RPC_SERVERS" if id is not None: @@ -325,8 +304,6 @@ def getRPCServers(self, custom, id=None): return server_list - - def removeRPCServer(self, id): printDbg("DB: Remove RPC server with id %d" % id) removed_RPC = False @@ -345,9 +322,6 @@ def removeRPCServer(self, id): if removed_RPC: self.app.sig_changed_rpcServers.emit() - - - ''' Masternode methods ''' @@ -391,8 +365,6 @@ def getMasternodeList(self): return mnlist - - def addNewMasternode(self, mn): printDbg("DB: Adding new masternode") try: @@ -413,8 +385,6 @@ def addNewMasternode(self, mn): finally: self.releaseCursor() - - def addMasternode(self, mn, old_mn=None): add_defaultKeys_to_dict(mn, DEFAULT_MN_CONF) @@ -444,8 +414,6 @@ def addMasternode(self, mn, old_mn=None): # Add new record to the table self.addNewMasternode(mn) - - def deleteMasternode(self, mn_name): printDbg("DB: Deleting masternode %s" % mn_name) try: @@ -458,8 +426,6 @@ def deleteMasternode(self, mn_name): finally: self.releaseCursor(vacuum=True) - - ''' Rewards methods ''' @@ -483,8 +449,6 @@ def rewards_from_rows(self, rows): return rewards - - def addReward(self, utxo): logging.debug("DB: Adding reward") try: @@ -503,8 +467,6 @@ def addReward(self, utxo): finally: self.releaseCursor() - - def deleteReward(self, tx_hash, tx_ouput_n): logging.debug("DB: Deleting reward") try: @@ -517,8 +479,6 @@ def deleteReward(self, tx_hash, tx_ouput_n): finally: self.releaseCursor(vacuum=True) - - def getReward(self, tx_hash, tx_ouput_n): logging.debug("DB: Getting reward") try: @@ -539,8 +499,6 @@ def getReward(self, tx_hash, tx_ouput_n): return self.rewards_from_rows(rows)[0] return None - - def getRewardsList(self, mn_name=None): try: cursor = self.getCursor() @@ -579,7 +537,6 @@ def txes_from_rows(self, rows): return txes - def addRawTx(self, tx_hash, rawtx, lastfetch=0): logging.debug("DB: Adding rawtx for %s" % tx_hash) try: @@ -597,7 +554,6 @@ def addRawTx(self, tx_hash, rawtx, lastfetch=0): finally: self.releaseCursor() - def deleteRawTx(self, tx_hash): logging.debug("DB: Deleting rawtx for %s" % tx_hash) try: @@ -610,7 +566,6 @@ def deleteRawTx(self, tx_hash): finally: self.releaseCursor(vacuum=True) - def getRawTx(self, tx_hash): logging.debug("DB: Getting rawtx for %s" % tx_hash) try: @@ -631,7 +586,6 @@ def getRawTx(self, tx_hash): return self.txes_from_rows(rows)[0] return None - def clearRawTxes(self, minTime): ''' removes txes with lastfetch older than mintime @@ -647,8 +601,6 @@ def clearRawTxes(self, minTime): finally: self.releaseCursor(vacuum=True) - - ''' Proposals methods ''' @@ -668,8 +620,6 @@ def myVotes_from_rows(self, rows): return myVotes - - def proposals_from_rows(self, rows): proposals = [] @@ -682,8 +632,6 @@ def proposals_from_rows(self, rows): return proposals - - def addMyVote(self, mn_name, p_hash, vote): logging.debug("DB: Adding vote") try: @@ -701,8 +649,6 @@ def addMyVote(self, mn_name, p_hash, vote): finally: self.releaseCursor() - - def addProposal(self, p): logging.debug("DB: Adding proposal") try: @@ -722,8 +668,6 @@ def addProposal(self, p): finally: self.releaseCursor() - - def getMyVotes(self, p_hash=None): try: cursor = self.getCursor() @@ -745,8 +689,6 @@ def getMyVotes(self, p_hash=None): return self.myVotes_from_rows(rows) - - def getProposalsList(self): printDbg("DB: Getting proposal list") try: diff --git a/src/hwdevice.py b/src/hwdevice.py index df257c8..7bf1b9e 100644 --- a/src/hwdevice.py +++ b/src/hwdevice.py @@ -26,7 +26,6 @@ def func_int(*args, **kwargs): return func_int - class HWdevice(QObject): # signal: sig1 (thread) is done - emitted by signMessageFinish sig1done = pyqtSignal(str) @@ -38,7 +37,6 @@ def __init__(self, main_wnd, *args, **kwargs): self.api = None printOK("HW: Class initialized") - def initDevice(self, hw_index): printDbg("HW: initializing hw device with index %d" % hw_index) if hw_index >= len(HW_devices): @@ -57,14 +55,12 @@ def initDevice(self, hw_index): self.api.sig_disconnected.connect(self.main_wnd.clearHWstatus) printOK("HW: hw device with index %d initialized" % hw_index) - @check_api_init def clearDevice(self): printDbg("HW: Clearing HW device...") self.api.closeDevice('') printOK("HW: device cleared") - # Status codes: # 0 - not connected # 1 - not initialized @@ -75,7 +71,6 @@ def getStatus(self): printOK("Status: %d" % self.api.status) return self.api.model, self.api.status, self.api.messages[self.api.status] - def prepare_transfer_tx(self, caller, bip32_path, utxos_to_spend, dest_address, tx_fee, isTestnet=False): rewardsArray = [] mnode = {} @@ -84,19 +79,16 @@ def prepare_transfer_tx(self, caller, bip32_path, utxos_to_spend, dest_address, rewardsArray.append(mnode) self.prepare_transfer_tx_bulk(caller, rewardsArray, dest_address, tx_fee, isTestnet) - @check_api_init def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, isTestnet=False): printDbg("HW: Preparing transfer TX") self.api.prepare_transfer_tx_bulk(caller, rewardsArray, dest_address, tx_fee, isTestnet) - @check_api_init def scanForAddress(self, account, spath, isTestnet=False): printOK("HW: Scanning for Address n. %d on account n. %d" % (spath, account)) return self.api.scanForAddress(account, spath, isTestnet) - @check_api_init def scanForBip32(self, account, address, starting_spath=0, spath_count=10, isTestnet=False): printOK("HW: Scanning for Bip32 path of address: %s" % address) @@ -116,13 +108,11 @@ def scanForBip32(self, account, address, starting_spath=0, spath_count=10, isTes return (found, spath) - @check_api_init def scanForPubKey(self, account, spath, isTestnet=False): printOK("HW: Scanning for PubKey of address n. %d on account n. %d" % (spath, account)) return self.api.scanForPubKey(account, spath, isTestnet) - @check_api_init def signMess(self, caller, path, message, isTestnet=False): printDbg("HW: Signing message...") diff --git a/src/ledgerClient.py b/src/ledgerClient.py index 1a4dbaa..81703a5 100644 --- a/src/ledgerClient.py +++ b/src/ledgerClient.py @@ -64,7 +64,6 @@ class LedgerApi(QObject): # signal: sig_disconnected -emitted with DisconnectedException sig_disconnected = pyqtSignal(str) - def __init__(self, main_wnd, *args, **kwargs): QObject.__init__(self, *args, **kwargs) self.main_wnd = main_wnd @@ -80,9 +79,6 @@ def __init__(self, main_wnd, *args, **kwargs): self.dongle = None printDbg("Creating HW device class") - - - @process_ledger_exceptions def initDevice(self): printDbg("Initializing Ledger") @@ -101,8 +97,6 @@ def initDevice(self): self.status = 2 self.sig_progress.connect(self.updateSigProgress) - - def closeDevice(self, message=''): printDbg("Closing LEDGER client") self.sig_disconnected.emit(message) @@ -115,7 +109,6 @@ def closeDevice(self, message=''): pass self.dongle = None - @process_ledger_exceptions def append_inputs_to_TX(self, utxo, bip32_path): self.amount += int(utxo['satoshis']) @@ -152,8 +145,6 @@ def append_inputs_to_TX(self, utxo, bip32_path): 'p2cs': (utxo['staker'] != "") }) - - @process_ledger_exceptions def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, isTestnet=False): with self.lock: @@ -215,8 +206,6 @@ def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, i ThreadFuns.runInThread(self.signTxSign, (), self.signTxFinish) - - @process_ledger_exceptions def scanForAddress(self, account, spath, isTestnet=False): with self.lock: @@ -230,8 +219,6 @@ def scanForAddress(self, account, spath, isTestnet=False): return curr_addr - - @process_ledger_exceptions def scanForPubKey(self, account, spath, isTestnet=False): hwpath = "%d'/0/%d" % (account, spath) @@ -245,8 +232,6 @@ def scanForPubKey(self, account, spath, isTestnet=False): return compress_public_key(nodeData.get('publicKey')).hex() - - @process_ledger_exceptions def signMess(self, caller, hwpath, message, isTestnet=False): if isTestnet: @@ -294,8 +279,6 @@ def signMess(self, caller, hwpath, message, isTestnet=False): # Sign message ThreadFuns.runInThread(self.signMessageSign, (), self.signMessageFinish) - - @process_ledger_exceptions def signMessageSign(self, ctrl): self.signature = None @@ -305,8 +288,6 @@ def signMessageSign(self, ctrl): except: pass - - def signMessageFinish(self): with self.lock: self.mBox.accept() @@ -341,8 +322,6 @@ def signMessageFinish(self): self.sig1done.emit(sig1) - - @process_ledger_exceptions def signTxSign(self, ctrl): self.tx_raw = None @@ -388,8 +367,6 @@ def signTxSign(self, ctrl): self.tx_raw = bytearray(self.new_transaction.serialize()) self.sig_progress.emit(100) - - def signTxFinish(self): self.mBox2.accept() @@ -400,8 +377,6 @@ def signTxFinish(self): printOK("Transaction refused by the user") self.sigTxabort.emit() - - def updateSigProgress(self, percent): messageText = self.messageText + "Signature Progress: " + str(percent) + " %" self.mBox2.setText(messageText) diff --git a/src/mainWindow.py b/src/mainWindow.py index 8ad5266..49d1249 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -31,7 +31,6 @@ class MainWindow(QWidget): - # signal: clear RPC status label and icons (emitted by updateRPCstatus) sig_clearRPCstatus = pyqtSignal() @@ -151,14 +150,10 @@ def __init__(self, parent, masternode_list, imgDir): self.mnode_to_change = None printOK("Hello! Welcome to " + parent.title) - - def append_to_console(self, text): self.consoleArea.moveCursor(QTextCursor.End) self.consoleArea.insertHtml(text) - - def clearHWstatus(self, message=''): self.hwStatus = 0 self.hwStatusMess = "Not Connected" @@ -167,8 +162,6 @@ def clearHWstatus(self, message=''): self.hwStatus = 1 myPopUp_sb(self, "crit", "hw device Disconnected", message) - - def clearRPCstatus(self): with self.lock: self.rpcConnected = False @@ -180,8 +173,6 @@ def clearRPCstatus(self): self.header.responseTimeLabel.setStyleSheet("color: red") self.header.lastPingIcon.setStyleSheet("color: red") - - def connButtons(self): self.header.button_checkRpc.clicked.connect(lambda: self.onCheckRpc()) self.header.button_checkHw.clicked.connect(lambda: self.onCheckHw()) @@ -193,8 +184,6 @@ def connButtons(self): self.parent.sig_changed_rpcServers.connect(self.updateRPClist) self.tabMain.myList.model().rowsMoved.connect(self.saveMNListOrder) - - def getRPCserver(self): itemData = self.header.rpcClientsBox.itemData(self.header.rpcClientsBox.currentIndex()) rpc_index = self.header.rpcClientsBox.currentIndex() @@ -205,13 +194,9 @@ def getRPCserver(self): return rpc_index, rpc_protocol, rpc_host, rpc_user, rpc_password - - def getServerListIndex(self, server): return self.header.rpcClientsBox.findData(server) - - def initConsole(self): self.console = QGroupBox() self.console.setTitle("Console Log") @@ -248,21 +233,15 @@ def initConsole(self): layout.addWidget(self.consoleArea) self.console.setLayout(layout) - - def initSettings(self): self.splitter.setSizes([self.parent.cache.get("splitter_x"), self.parent.cache.get("splitter_y")]) ###-- Hide console if it was previously hidden if self.parent.cache.get("console_hidden"): self.onToggleConsole() - - def isMasternodeInList(self, mn_alias): return (mn_alias in [x['name'] for x in self.masternode_list]) - - def loadIcons(self): # Load Icons self.ledPurpleH_icon = QPixmap(os.path.join(self.imgDir, 'icon_purpleLedH.png')).scaledToHeight(17, Qt.SmoothTransformation) @@ -276,8 +255,6 @@ def loadIcons(self): self.connRed_icon = QPixmap(os.path.join(self.imgDir, 'icon_redConn.png')).scaledToHeight(15, Qt.SmoothTransformation) self.connOrange_icon = QPixmap(os.path.join(self.imgDir, 'icon_orangeConn.png')).scaledToHeight(15, Qt.SmoothTransformation) - - def loadMNConf(self, fileName): hot_masternodes = loadMNConfFile(fileName) if hot_masternodes == None: @@ -314,27 +291,19 @@ def loadMNConf(self, fileName): final_message += str([x['name'] for x in skip_masternodes]) + ". " printOK(final_message) - - def onCheckHw(self): printDbg("Checking for HW device...") self.updateHWstatus(None) self.showHWstatus() - - def onCheckRpc(self): self.runInThread(self.updateRPCstatus, (True,),) - - def onCheckVersion(self): printDbg("Checking SPMT version...") self.versionLabel.setText("--") self.runInThread(self.checkVersion, (), self.updateVersion) - - def checkVersion(self, ctrl): local_version = self.parent.version['number'].split('.') self.gitVersion = getRemoteSPMTversion() @@ -348,15 +317,11 @@ def checkVersion(self, ctrl): else: self.versionMess = "You have the latest version of SPMT" - - def updateVersion(self): if self.versionMess is not None: self.versionLabel.setText(self.versionMess) printOK("Remote version: %s" % str(self.gitVersion)) - - def onChangeSelectedHW(self, i): # Clear status self.clearHWstatus() @@ -364,8 +329,6 @@ def onChangeSelectedHW(self, i): # Persist setting self.parent.cache['selectedHW_index'] = persistCacheSetting('cache_HWindex',i) - - def onChangeSelectedRPC(self, i): # Don't update when we are clearing the box if not self.updatingRPCbox: @@ -373,13 +336,9 @@ def onChangeSelectedRPC(self, i): self.parent.cache['selectedRPC_index'] = persistCacheSetting('cache_RPCindex',i) self.runInThread(self.updateRPCstatus, (True,), ) - - def onCleanConsole(self): self.consoleArea.clear() - - def onSaveConsole(self): timestamp = strftime('%Y-%m-%d_%H-%M-%S', gmtime(now())) options = QFileDialog.Options() @@ -397,8 +356,6 @@ def onSaveConsole(self): err_msg = "error writing Log file" printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def onTabChange(self): # tabRewards if self.tabs.currentWidget() == self.tabRewards: @@ -410,8 +367,6 @@ def onTabChange(self): # update selectedMNlabel (since we might have edited them) self.t_governance.updateSelectedMNlabel() - - def onToggleConsole(self): if self.btn_consoleToggle.text() == 'Hide': self.btn_consoleToggle.setText('Show') @@ -424,8 +379,6 @@ def onToggleConsole(self): self.btn_consoleToggle.setText('Hide') self.consoleArea.show() - - def saveMNListOrder(self): # Update mnList order to cache settings and sort mnOrder = {} @@ -438,14 +391,10 @@ def saveMNListOrder(self): # reload MnSelect in tabRewards self.t_rewards.loadMnSelect() - - def showHWstatus(self): self.updateHWleds() myPopUp_sb(self, "info", 'SPMT - hw check', "%s" % self.hwStatusMess) - - def showRPCstatus(self, server_index, fDebug): # Update displayed status only if selected server is not changed if server_index == self.header.rpcClientsBox.currentIndex(): @@ -453,8 +402,6 @@ def showRPCstatus(self, server_index, fDebug): if fDebug: myPopUp_sb(self, "info", 'SPMT - rpc check', "%s" % self.rpcStatusMess) - - def updateHWleds(self): if self.hwStatus == 1: self.header.hwLed.setPixmap(self.ledHalfPurpleH_icon) @@ -464,8 +411,6 @@ def updateHWleds(self): self.header.hwLed.setPixmap(self.ledGrayH_icon) self.header.hwLed.setToolTip(self.hwStatusMess) - - def updateHWstatus(self, ctrl): # re-initialize device try: @@ -477,8 +422,6 @@ def updateHWstatus(self, ctrl): printDbg("status:%s - mess: %s" % (self.hwStatus, self.hwStatusMess)) - - def updateLastBlockLabel(self): text = '--' if self.rpcLastBlock == 1: @@ -490,8 +433,6 @@ def updateLastBlockLabel(self): self.header.lastBlockLabel.setText(text) - - def updateLastBlockPing(self): if not self.rpcConnected: self.header.lastPingBox.setHidden(True) @@ -511,8 +452,6 @@ def updateLastBlockPing(self): self.header.responseTimeLabel.setStyleSheet("color: %s" % color) self.header.lastPingIcon.setStyleSheet("color: %s" % color) - - def updateRPCled(self, fDebug=False): if self.rpcConnected: self.header.rpcLed.setPixmap(self.ledPurpleH_icon) @@ -532,8 +471,6 @@ def updateRPCled(self, fDebug=False): self.updateLastBlockLabel() self.updateLastBlockPing() - - def updateRPClist(self): # Clear old stuff self.updatingRPCbox = True @@ -566,8 +503,6 @@ def updateRPClist(self): # reload servers in configure dialog self.sig_RPClistReloaded.emit() - - def updateRPCstatus(self, ctrl, fDebug=False): rpc_index, rpc_protocol, rpc_host, rpc_user, rpc_password = self.getRPCserver() if fDebug: diff --git a/src/masternode.py b/src/masternode.py index 7aa2696..f7a4fa2 100644 --- a/src/masternode.py +++ b/src/masternode.py @@ -46,7 +46,6 @@ def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral = {}, Masternode.mnCount += 1 printOK("Initializing MNode with collateral: %s" % self.nodePath) - def getOldBroadcastMessage(self): self.sig_time = int(time.time()) serializedData = ipport(self.ip, self.port) @@ -56,7 +55,6 @@ def getOldBroadcastMessage(self): serializedData += str(self.protocol_version) return serializedData - def getNewBroadcastMessage(self): self.sig_time = int(time.time()) pk1 = bytes.fromhex(self.collateral['pubKey']) @@ -70,7 +68,6 @@ def getNewBroadcastMessage(self): res = bitcoin.bin_dbl_sha256(ss)[::-1] return res.hex() - def signature1(self, device): try: fNewSigs = NewSigsActive(self.currHeight, self.isTestnet) @@ -90,8 +87,6 @@ def signature1(self, device): printException(getCallerName(), getFunctionName(), err_msg, '') return None - - def getPingMessage(self, fNewSigs, block_hash): if fNewSigs: ss = bytes.fromhex(self.collateral["txid"])[::-1] @@ -106,7 +101,6 @@ def getPingMessage(self, fNewSigs, block_hash): return serialize_input_str(self.collateral['txid'], self.collateral['txidn'], sequence, scriptSig) + \ block_hash + str(self.sig_time) - def signature2(self, block_hash): try: fNewSigs = NewSigsActive(self.currHeight, self.isTestnet) @@ -124,8 +118,6 @@ def signature2(self, block_hash): err_msg = "error in signature2" printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def finalizeStartMessage(self, text): sig1 = text if sig1 == "None": @@ -184,8 +176,6 @@ def finalizeStartMessage(self, text): printDbg("EMITTING: %s" % work) self.sigdone.emit(work) - - def startMessage(self, device, rpcClient): # setuo rpc connection self.rpcClient = rpcClient diff --git a/src/misc.py b/src/misc.py index 6413370..f62132c 100644 --- a/src/misc.py +++ b/src/misc.py @@ -65,8 +65,6 @@ def appendMasternode(mainWnd, mn): printDbg("saved") - - def checkRPCstring(urlstring, action_msg="Malformed credentials"): try: o = urlparse(urlstring) @@ -88,7 +86,6 @@ def checkRPCstring(urlstring, action_msg="Malformed credentials"): return False - def checkTxInputs(parentWindow, num_of_inputs): if num_of_inputs == 0: myPopUp_sb(parentWindow, "warn", 'Transaction NOT sent', "No UTXO to send") @@ -163,21 +160,16 @@ def clean_v4_migration(wnd): printDbg("old lastLogs.html file deleted") - - - def clean_for_html(text): if text is None: return "" return text.replace("<", "{").replace(">","}") - def clear_screen(): os.system('clear') - def getCallerName(inDecorator=False): try: if inDecorator: @@ -187,7 +179,6 @@ def getCallerName(inDecorator=False): return None - def getFunctionName(inDecorator=False): try: if inDecorator: @@ -212,7 +203,6 @@ def getRemoteSPMTversion(): return "0.0.0" - def getSPMTVersion(): version_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'version.txt') @@ -222,7 +212,6 @@ def getSPMTVersion(): return data - def getTxidTxidn(txid, txidn): if txid is None or txidn is None: return None @@ -230,7 +219,6 @@ def getTxidTxidn(txid, txidn): return txid + '-' + str(txidn) - def initLogs(): filename = log_File filemode = 'w' @@ -243,7 +231,6 @@ def initLogs(): ) - def ipport(ip, port): if ip is None or port is None: return None @@ -259,7 +246,6 @@ def ipport(ip, port): raise Exception("invalid IP version number") - def is_hex(s): try: int(s, 16) @@ -268,9 +254,7 @@ def is_hex(s): return False - def loadMNConfFile(fileName): - hot_masternodes = [] try: with open(fileName) as f: @@ -321,7 +305,6 @@ def loadMNConfFile(fileName): printException(getCallerName(), getFunctionName(), errorMsg, e.args) - def myPopUp(parentWindow, messType, messTitle, messText, defaultButton=QMessageBox.No): if messType in QT_MESSAGE_TYPE: type = QT_MESSAGE_TYPE[messType] @@ -333,7 +316,6 @@ def myPopUp(parentWindow, messType, messTitle, messText, defaultButton=QMessageB return mess.exec_() - def myPopUp_sb(parentWindow, messType, messTitle, messText, singleButton=QMessageBox.Ok): if messType in QT_MESSAGE_TYPE: type = QT_MESSAGE_TYPE[messType] @@ -344,13 +326,10 @@ def myPopUp_sb(parentWindow, messType, messTitle, messText, singleButton=QMessag return mess.exec_() - def now(): return int(time.time()) - - def persistCacheSetting(cache_key, cache_value): settings = QSettings('PIVX', 'SecurePivxMasternodeTool') if not settings.contains(cache_key): @@ -365,14 +344,12 @@ def persistCacheSetting(cache_key, cache_value): return cache_value - def printDbg(what): logging.info(what) log_line = printDbg_msg(what) redirect_print(log_line) - def printDbg_msg(what): what = clean_for_html(what) timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(now())) @@ -380,7 +357,6 @@ def printDbg_msg(what): return log_line - def printError( caller_name, function_name, @@ -391,7 +367,6 @@ def printError( redirect_print(log_line) - def printException( caller_name, function_name, @@ -406,7 +381,6 @@ def printException( redirect_print(text) - def printException_msg( caller_name, function_name, @@ -428,14 +402,12 @@ def printException_msg( return msg - def printOK(what): logging.debug(what) msg = '===> ' + what + '
' redirect_print(msg) - def readCacheSettings(): settings = QSettings('PIVX', 'SecurePivxMasternodeTool') try: @@ -482,8 +454,6 @@ def removeMNfromList(mainWnd, mn, removeFromDB=True): mainWnd.t_governance.clear() - - def saveCacheSettings(cache): settings = QSettings('PIVX', 'SecurePivxMasternodeTool') settings.setValue('cache_lastAddress', cache.get('lastAddress')) @@ -503,8 +473,6 @@ def saveCacheSettings(cache): settings.setValue('cache_isTestnetRPC', cache.get('isTestnetRPC')) - - def sec_to_time(seconds): days = seconds//86400 seconds -= days*86400 @@ -515,15 +483,11 @@ def sec_to_time(seconds): return "{} days, {} hrs, {} mins, {} secs".format(days, hrs, mins, seconds) - - def splitString(text, n): arr = [text[i:i+n] for i in range(0, len(text), n)] return '\n'.join(arr) - - def timeThis(function, *args): try: start = time.clock() @@ -534,8 +498,6 @@ def timeThis(function, *args): return None, None - - def updateSplash(label, i): if i==10: progressText = "Loading configuration data..." @@ -564,8 +526,6 @@ def __init__(self, message, hwDevice): hwDevice.closeDevice(message) - - # Stream object to redirect sys.stdout and sys.stderr to a queue class WriteStream(object): def __init__(self, queue): @@ -578,7 +538,6 @@ def flush(self): pass - # QObject (to be run in QThread) that blocks until data is available # and then emits a QtSignal to the main thread. class WriteStreamReceiver(QObject): diff --git a/src/pivx_b58.py b/src/pivx_b58.py index 52de24a..ebc9522 100644 --- a/src/pivx_b58.py +++ b/src/pivx_b58.py @@ -42,7 +42,6 @@ def b58encode(v): return (__b58chars[0] * nPad) + result - def b58decode(v, length=None): """ decode v into a string of len bytes """ diff --git a/src/pivx_hashlib.py b/src/pivx_hashlib.py index 7f60a83..7d49592 100644 --- a/src/pivx_hashlib.py +++ b/src/pivx_hashlib.py @@ -13,16 +13,15 @@ STAKE_MAGIC_BYTE, TESTNET_STAKE_MAGIC_BYTE from pivx_b58 import b58encode, b58decode + def double_sha256(data): return hashlib.sha256(hashlib.sha256(data).digest()).digest() - def single_sha256(data): return hashlib.sha256(data).digest() - def generate_privkey(isTestnet=False): """ Based on Andreas Antonopolous work from 'Mastering Bitcoin'. @@ -49,7 +48,6 @@ def pubkey_to_address(pubkey, isTestnet=False, isCold=False): return pubkeyhash_to_address(pkey_hash, isTestnet, isCold) - def pubkeyhash_to_address(pkey_hash, isTestnet=False, isCold=False): if isCold: base58_secret = TESTNET_STAKE_MAGIC_BYTE if isTestnet else STAKE_MAGIC_BYTE @@ -60,8 +58,6 @@ def pubkeyhash_to_address(pkey_hash, isTestnet=False, isCold=False): return b58encode(data + checksum) - - def wif_to_privkey(string): wif_compressed = 52 == len(string) pvkeyencoded = b58decode(string).hex() diff --git a/src/pivx_parser.py b/src/pivx_parser.py index 6e06f7f..b2b79a4 100644 --- a/src/pivx_parser.py +++ b/src/pivx_parser.py @@ -8,6 +8,7 @@ import utils from pivx_hashlib import pubkeyhash_to_address + class HexParser(): def __init__(self, hex_str): self.cursor = 0 diff --git a/src/proposals.py b/src/proposals.py index 31f444d..6393b6f 100644 --- a/src/proposals.py +++ b/src/proposals.py @@ -16,6 +16,7 @@ "-1": "NO" } + class Proposal(): def __init__(self, name, URL, Hash, FeeHash, BlockStart, BlockEnd, TotalPayCount, RemainingPayCount, PayMentAddress, Yeas, Nays, Abstains, TotalPayment, MonthlyPayment): diff --git a/src/qt/dlg_budgetProjection.py b/src/qt/dlg_budgetProjection.py index 1b881b0..7ec12f4 100644 --- a/src/qt/dlg_budgetProjection.py +++ b/src/qt/dlg_budgetProjection.py @@ -11,6 +11,7 @@ from misc import printException, sec_to_time from threads import ThreadFuns + class BudgetProjection_dlg(QDialog): def __init__(self, main_wnd): QDialog.__init__(self, parent=main_wnd.ui) @@ -20,23 +21,20 @@ def __init__(self, main_wnd): self.ui.ok_btn.clicked.connect(lambda: self.accept()) self.next_superBlock = 0 ThreadFuns.runInThread(self.loadBudgetProjection_thread, (), self.displayBudgetProjection) - - + def initUI(self): self.ui = Ui_BudgetProjectionDlg() self.ui.setupUi(self) - - - + def displayBudgetProjection(self): total_num_of_proposals = len(self.projection) if total_num_of_proposals == 0 or self.next_superBlock == 0: return - + # header ## blocks to next superBlock (== minutes) blocks_to_SB = self.next_superBlock - self.main_wnd.caller.rpcLastBlock - + self.ui.nextSuperBlock_label.setText("%s" % str(self.next_superBlock)) timeToNextSB = "%s" % sec_to_time(60*blocks_to_SB) self.ui.timeToNextSB_label.setText(timeToNextSB) @@ -45,21 +43,19 @@ def displayBudgetProjection(self): self.ui.allottedBudget_label.setText(total_label) self.ui.remainingBudget_label.setText("%s PIV" % str(round(43200.0-total,8))) self.ui.passingProposals_label.setText("%s" % str(len(self.projection))) - + def item(value): item = QTableWidgetItem(str(value)) item.setTextAlignment(Qt.AlignCenter) return item - + self.ui.proposals_lst.setRowCount(total_num_of_proposals) for row, prop in enumerate(self.projection): self.ui.proposals_lst.setItem(row, 0, item(self.projection[row].get('Name'))) self.ui.proposals_lst.setItem(row, 1, item(self.projection[row].get('Allotted'))) self.ui.proposals_lst.setItem(row, 2, item(self.projection[row].get('Votes'))) self.ui.proposals_lst.setItem(row, 3, item(self.projection[row].get('Total_Allotted'))) - - - + def loadBudgetProjection_thread(self, ctrl): self.projection = [] if not self.main_wnd.caller.rpcConnected: @@ -69,8 +65,6 @@ def loadBudgetProjection_thread(self, ctrl): self.next_superBlock = self.main_wnd.caller.rpcClient.getNextSuperBlock() ## get budget projection self.projection = self.main_wnd.caller.rpcClient.getProposalsProjection() - - class Ui_BudgetProjectionDlg(object): @@ -142,4 +136,4 @@ def setupUi(self, BudgetProjectionDlg): ## button ok self.ok_btn = QPushButton("Ok") layout.addWidget(self.ok_btn) - BudgetProjectionDlg.resize(650, 500) \ No newline at end of file + BudgetProjectionDlg.resize(650, 500) diff --git a/src/qt/dlg_configureRPCservers.py b/src/qt/dlg_configureRPCservers.py index 137bda3..e0a0b75 100644 --- a/src/qt/dlg_configureRPCservers.py +++ b/src/qt/dlg_configureRPCservers.py @@ -11,6 +11,7 @@ from misc import myPopUp, checkRPCstring from threads import ThreadFuns + class ConfigureRPCservers_dlg(QDialog): def __init__(self, main_wnd): QDialog.__init__(self, parent=main_wnd) @@ -20,21 +21,17 @@ def __init__(self, main_wnd): self.initUI() self.loadServers() self.main_wnd.mainWindow.sig_RPClistReloaded.connect(self.loadServers) - - - + def clearEditFrame(self): self.ui.user_edt.clear() self.ui.passwd_edt.clear() self.ui.protocol_select.setCurrentIndex(0) self.ui.host_edt.clear() - def initUI(self): self.ui = Ui_ConfigureRPCserversDlg() self.ui.setupUi(self) - - + def insert_server_list(self, server): id = server['id'] index = self.main_wnd.mainWindow.getServerListIndex(server) @@ -75,8 +72,7 @@ def insert_server_list(self, server): self.serverItems[id].setSizeHint(server_line.sizeHint()) self.ui.serversBox.addItem(self.serverItems[id]) self.ui.serversBox.setItemWidget(self.serverItems[id], server_line) - - + def loadServers(self): # Clear serversBox self.ui.serversBox.clear() @@ -84,8 +80,7 @@ def loadServers(self): self.serverItems = {} for server in self.main_wnd.mainWindow.rpcServersList: self.insert_server_list(server) - - + def loadEditFrame(self, index): server = self.main_wnd.mainWindow.rpcServersList[index] self.ui.user_edt.setText(server['user']) @@ -95,8 +90,6 @@ def loadEditFrame(self, index): else: self.ui.protocol_select.setCurrentIndex(0) self.ui.host_edt.setText(server['host']) - - def onAddServer(self, index=None): # Save current index (None for new entry) @@ -113,8 +106,6 @@ def onAddServer(self, index=None): # else pre-load data else: self.loadEditFrame(index) - - def onCancel(self): # Show 'Add' and 'Close' buttons and enable serversBox @@ -125,14 +116,10 @@ def onCancel(self): self.ui.editFrame.setHidden(True) # Clear edit-frame self.clearEditFrame() - - def onClose(self): # close dialog self.close() - - def onRemoveServer(self, index): mess = "Are you sure you want to remove server with index %d (%s) from list?" % ( @@ -143,8 +130,6 @@ def onRemoveServer(self, index): id = self.main_wnd.mainWindow.rpcServersList[index].get('id') self.main_wnd.db.removeRPCServer(id) - - def onSave(self): # Get new config data protocol = "http" if self.ui.protocol_select.currentIndex() == 0 else "https" @@ -169,10 +154,8 @@ def onSave(self): # call onCancel self.onCancel() - - - - + + class Ui_ConfigureRPCserversDlg(object): def setupUi(self, ConfigureRPCserversDlg): ConfigureRPCserversDlg.setModal(True) @@ -226,5 +209,3 @@ def setupUi(self, ConfigureRPCserversDlg): self.close_btn.clicked.connect(lambda: ConfigureRPCserversDlg.onClose()) self.cancel_btn.clicked.connect(lambda: ConfigureRPCserversDlg.onCancel()) self.save_btn.clicked.connect(lambda: ConfigureRPCserversDlg.onSave()) - - \ No newline at end of file diff --git a/src/qt/dlg_findCollTx.py b/src/qt/dlg_findCollTx.py index 4f9a924..f7fbc3e 100644 --- a/src/qt/dlg_findCollTx.py +++ b/src/qt/dlg_findCollTx.py @@ -20,8 +20,6 @@ def __init__(self, mainTab): self.blockCount = 0 self.setupUI() - - def setupUI(self): Ui_FindCollateralTxDlg.setupUi(self, self) self.setWindowTitle('Find Collateral Tx') @@ -30,8 +28,6 @@ def setupUI(self): self.lblMessage.setVisible(True) self.lblMessage.setText('Checking explorer...') - - def load_data(self, pivx_addr): self.pivx_addr = pivx_addr ##--- PIVX Address @@ -39,8 +35,6 @@ def load_data(self, pivx_addr): ##--- Load utxos ThreadFuns.runInThread(self.load_utxos_thread, (), self.display_utxos) - - def display_utxos(self): def item(value): item = QTableWidgetItem(value) @@ -65,8 +59,6 @@ def item(value): self.lblMessage.setText('No UTXO found for current address.\nEnter tx manually') self.lblMessage.setVisible(True) - - def load_utxos_thread(self, ctrl): try: if not self.mainTab.caller.rpcClient.getStatus(): @@ -84,8 +76,6 @@ def load_utxos_thread(self, ctrl): except Exception as e: pass - - def getSelection(self): items = self.tableW.selectedItems() if len(items): @@ -95,9 +85,6 @@ def getSelection(self): return None, 0 - - - class Ui_FindCollateralTxDlg(object): def setupUi(self, FindCollateralTxDlg): self.dlg = FindCollateralTxDlg diff --git a/src/qt/dlg_mnStatus.py b/src/qt/dlg_mnStatus.py index 1e78553..013c0af 100644 --- a/src/qt/dlg_mnStatus.py +++ b/src/qt/dlg_mnStatus.py @@ -11,6 +11,7 @@ from misc import sec_to_time + class MnStatus_dlg(QDialog): def __init__(self, main_wnd, mnAlias, statusData): QDialog.__init__(self, parent=main_wnd) @@ -19,12 +20,10 @@ def __init__(self, main_wnd, mnAlias, statusData): self.statusData = statusData self.setWindowTitle('Masternode Details') self.setupUI() - - + def setupUI(self): Ui_MnStatusDlg.setupUi(self, self) - - + class Ui_MnStatusDlg(object): def setupUi(self, MnStatusDlg): @@ -52,4 +51,4 @@ def setupUi(self, MnStatusDlg): self.okButton.clicked.connect(self.accept) layout.addWidget(self.okButton) sh = layout.sizeHint() - self.setFixedSize(sh) \ No newline at end of file + self.setFixedSize(sh) diff --git a/src/qt/dlg_pinMatrix.py b/src/qt/dlg_pinMatrix.py index 541780b..e62caba 100644 --- a/src/qt/dlg_pinMatrix.py +++ b/src/qt/dlg_pinMatrix.py @@ -10,6 +10,7 @@ from misc import myPopUp_sb + class PinMatrix_dlg(QDialog): def __init__(self, text='', title='Enter PIN', fHideBtns=True): QDialog.__init__(self) @@ -19,26 +20,21 @@ def __init__(self, text='', title='Enter PIN', fHideBtns=True): self.setWindowTitle(title) self.setupUI() - def btn_clicked(self, num): self.pin += num self.lbl_pin.setText('*' * len(self.pin)) - def getPin(self): return self.pin - def onCancel(self): self.pin = '' self.reject() - def onDel(self): self.pin = self.pin[:-1] self.lbl_pin.setText('*' * len(self.pin)) - def onOK(self): if self.pin: if len(self.pin) > 9: @@ -50,7 +46,6 @@ def onOK(self): text = "No PIN entered" myPopUp_sb(self, "warn", 'Wrong PIN!', text) - def setupUI(self): Ui_pinMatrixDlg.setupUi(self, self) # Connect buttons matrix @@ -62,8 +57,6 @@ def setupUI(self): self.btn_cancel.clicked.connect(self.onCancel) - - class Ui_pinMatrixDlg(object): def setupUi(self, PinMatrixDlg): PinMatrixDlg.setModal(True) diff --git a/src/qt/dlg_proposalDetails.py b/src/qt/dlg_proposalDetails.py index cfe65f8..4ba3620 100644 --- a/src/qt/dlg_proposalDetails.py +++ b/src/qt/dlg_proposalDetails.py @@ -25,7 +25,6 @@ def __init__(self, main_wnd, proposal): def setupUI(self): Ui_proposalDetailsDlg.setupUi(self, self) - def selectable_line(self, item): line = QLineEdit(item) line.setMinimumWidth(420) @@ -34,7 +33,6 @@ def selectable_line(self, item): line.setFrame(QFrame.NoFrame) return line - def scroll(self, item): if isinstance(item, list): item = item if len(item) > 0 else "" @@ -50,7 +48,6 @@ def scroll(self, item): return scroll - class Ui_proposalDetailsDlg(object): def setupUi(self, PropDetailsDlg): PropDetailsDlg.setModal(True) diff --git a/src/qt/dlg_selectMNs.py b/src/qt/dlg_selectMNs.py index 47d4673..272bed5 100644 --- a/src/qt/dlg_selectMNs.py +++ b/src/qt/dlg_selectMNs.py @@ -7,14 +7,16 @@ from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog, QTableWidget, QVBoxLayout, QAbstractItemView, QHeaderView,\ QTableWidgetItem, QLabel, QHBoxLayout, QPushButton - + from misc import persistCacheSetting - + + class masternodeItem(QTableWidgetItem): def __init__(self, name, txid): super().__init__(name) self.txid = txid + class SelectMNs_dlg(QDialog): def __init__(self, main_wnd): QDialog.__init__(self, parent=main_wnd.ui) @@ -26,16 +28,15 @@ def __init__(self, main_wnd): self.ui.selectAll_btn.clicked.connect(lambda: self.selectAll()) self.ui.deselectAll_btn.clicked.connect(lambda: self.ui.mnList.clearSelection()) self.ui.ok_btn.clicked.connect(lambda: self.onOK()) - - + def getSelection(self): items = self.ui.mnList.selectedItems() return [[x.txid, x.text()] for x in items] - + def initUI(self): self.ui = Ui_SelectMNsDlg() self.ui.setupUi(self) - + def loadMasternodes(self): for row, mn in enumerate(self.main_wnd.caller.masternode_list): name = mn.get('name') @@ -47,21 +48,19 @@ def loadMasternodes(self): # check if already selected if name in [x[1] for x in self.main_wnd.votingMasternodes]: item.setSelected(True) - - + def onOK(self): self.main_wnd.votingMasternodes = self.getSelection() self.main_wnd.updateSelectedMNlabel() # persist voting masternodes to cache self.main_wnd.caller.parent.cache['votingMasternodes'] = persistCacheSetting('cache_votingMNs', self.main_wnd.votingMasternodes) self.accept() - - + def selectAll(self): self.ui.mnList.selectAll() self.ui.mnList.setFocus() - - + + class Ui_SelectMNsDlg(object): def setupUi(self, SelectMNsDlg): SelectMNsDlg.setModal(True) @@ -93,4 +92,4 @@ def setupUi(self, SelectMNsDlg): hBox.addStretch(1) hBox.addWidget(self.ok_btn) layout.addLayout(hBox) - self.layout = layout \ No newline at end of file + self.layout = layout diff --git a/src/qt/dlg_signmessage.py b/src/qt/dlg_signmessage.py index b1d7ecc..9f39496 100644 --- a/src/qt/dlg_signmessage.py +++ b/src/qt/dlg_signmessage.py @@ -31,6 +31,7 @@ from threads import ThreadFuns from utils import checkPivxAddr, ecdsa_verify_addr + class SignMessage_dlg(QDialog): def __init__(self, main_wnd): QDialog.__init__(self, parent=main_wnd) @@ -72,7 +73,6 @@ def __init__(self, main_wnd): self.ui.fromSpathRadioBtn.toggled.connect(lambda: self.onToggleRadio(False)) self.ui.searchPKBtn.clicked.connect(lambda: self.onSearchPK()) - def loadAddressComboBox(self, mn_list): comboBox = self.ui.addressComboBox for x in mn_list: @@ -92,7 +92,6 @@ def loadAddressComboBox(self, mn_list): # init selection self.onChangeSelectedAddress() - def displaySignature(self, sig): if sig == "None": self.ui.signatureTextEdt.setText("Signature refused by the user") @@ -107,7 +106,6 @@ def displaySignature(self, sig): mess = "Signature doesn't verify." myPopUp_sb(self.main_wnd, QMessageBox.Warning, 'SPMT - no signature', mess) - def findPubKey(self): device = self.main_wnd.hwdevice @@ -120,7 +118,6 @@ def findPubKey(self): return self.updateGenericAddress(pk) - def findSpath(self, ctrl, starting_spath, spath_count): addy = self.ui.addressLineEdit.text().strip() device = self.main_wnd.hwdevice @@ -129,7 +126,6 @@ def findSpath(self, ctrl, starting_spath, spath_count): self.curr_starting_spath = starting_spath self.curr_spath_count = spath_count - def findSpath_done(self): if self.spath_found: self.findPubKey() @@ -147,7 +143,6 @@ def findSpath_done(self): starting_spath += spath_count ThreadFuns.runInThread(self.findSpath, (starting_spath, spath_count), self.findSpath_done) - def onChangeSelectedAddress(self): self.currName = None self.ui.editBtn.setVisible(False) @@ -165,7 +160,6 @@ def onChangeSelectedAddress(self): # generic address self.setSignEnabled(False) - def onCopy(self): if self.ui.signatureTextEdt.document().isEmpty(): mess = "Nothing to copy. Sign message first." @@ -176,12 +170,10 @@ def onCopy(self): cb.setText(self.ui.signatureTextEdt.toPlainText(), mode=cb.Clipboard) myPopUp_sb(self.main_wnd, QMessageBox.Information, 'SPMT - copied', "Signature copied to the clipboard") - def onEdit(self): visible = self.ui.hiddenLine.isVisible() self.ui.hiddenLine.setVisible(not visible) - def onSave(self): if self.ui.signatureTextEdt.document().isEmpty(): mess = "Nothing to save. Sign message first." @@ -203,7 +195,6 @@ def onSave(self): printException(getCallerName(), getFunctionName(), err_msg, e.args) myPopUp_sb(self.main_wnd, QMessageBox.Warning, 'SPMT - NOT saved', "Signature NOT saved to file") - def onSearchPK(self): fromAddress = self.ui.fromAddressRadioBtn.isChecked() self.hwAcc = self.ui.hwAccountSpingBox.value() @@ -239,7 +230,6 @@ def onSearchPK(self): self.spath = self.ui.spathSpinBox.value() self.findPubKey() - def onSign(self): # check message if self.ui.messageTextEdt.document().isEmpty(): @@ -272,12 +262,10 @@ def onSign(self): err_msg = "Keyboard Interrupt" printException(getCallerName(), getFunctionName(), err_msg, '') - def onToggleRadio(self, isFromAddress): self.ui.fromAddressBox.setVisible(isFromAddress) self.ui.fromSpathBox.setVisible(not isFromAddress) - def setSignEnabled(self, enabled): self.ui.signBtn.setEnabled(enabled) self.ui.hiddenLine.setVisible(not enabled) @@ -289,7 +277,6 @@ def setSignEnabled(self, enabled): self.ui.addressLabel.setText("") self.ui.signBtn.setToolTip(tooltip) - def updateGenericAddress(self, pk): genericAddy = pubkey_to_address(pk, self.currIsTestnet) if self.ui.fromAddressRadioBtn.isChecked(): @@ -308,9 +295,6 @@ def updateGenericAddress(self, pk): self.ui.editBtn.setVisible(True) - - - class TabVerify: def __init__(self, main_wnd): self.main_wnd = main_wnd @@ -506,4 +490,4 @@ def __init__(self): self.resultLabel.setVisible(False) layout.addWidget(self.resultLabel) # --- - self.setLayout(layout) \ No newline at end of file + self.setLayout(layout) diff --git a/src/qt/dlg_sweepAll.py b/src/qt/dlg_sweepAll.py index 58faab5..177656a 100644 --- a/src/qt/dlg_sweepAll.py +++ b/src/qt/dlg_sweepAll.py @@ -37,8 +37,6 @@ def __init__(self, main_tab): # Connect Signals self.main_tab.caller.sig_UTXOsLoading.connect(self.update_loading_utxos) - - # Called each time before exec_ in showDialog def load_data(self): # clear table @@ -51,26 +49,18 @@ def load_data(self): # Reload UTXOs ThreadFuns.runInThread(self.main_tab.caller.t_rewards.load_utxos_thread, ()) - - def showDialog(self): self.load_data() self.exec_() - - def connectButtons(self): self.ui.buttonSend.clicked.connect(lambda: self.onButtonSend()) self.ui.buttonCancel.clicked.connect(lambda: self.onButtonCancel()) - - def setupUI(self): self.ui = Ui_SweepAllDlg() self.ui.setupUi(self) - - def display_utxos(self): required_confs = 16 if self.main_tab.caller.isTestnetRPC else 101 rewards = self.main_tab.caller.parent.db.getRewardsList() @@ -129,14 +119,10 @@ def item(value): self.suggestedFee = round(self.feePerKb * estimatedTxSize, 8) self.updateFee() - - def onButtonCancel(self): self.AbortSend() self.close() - - def onButtonSend(self): t_rewards = self.main_tab.caller.t_rewards t_rewards.dest_addr = self.ui.edt_destination.text().strip() @@ -155,8 +141,6 @@ def onButtonSend(self): # SEND t_rewards.SendRewards(self.rewardsArray, self) - - # Activated by signal sigTxabort from hwdevice def AbortSend(self): self.ui.buttonSend.setEnabled(True) @@ -164,29 +148,21 @@ def AbortSend(self): self.ui.loadingLine.hide() self.ui.loadingLinePercent.hide() - - # Activated by signal sigTxdone from hwdevice def FinishSend(self, serialized_tx, amount_to_send): self.AbortSend() self.main_tab.caller.t_rewards.FinishSend_int(serialized_tx, amount_to_send) self.close() - - def removeSpentRewards(self): for mn in self.rewardsArray: for utxo in mn['utxos']: self.main_tab.caller.parent.db.deleteReward(utxo['txid'], utxo['vout']) - - def updateFee(self): self.ui.feeLine.setValue(self.suggestedFee) self.ui.feeLine.setEnabled(True) - - def update_loading_utxos(self, percent): if percent < 100: self.ui.buttonSend.setEnabled(False) @@ -197,8 +173,6 @@ def update_loading_utxos(self, percent): self.ui.lblMessage.hide() self.display_utxos() - - # Activated by signal tx_progress from hwdevice def updateProgressPercent(self, percent): if percent < 100: @@ -209,7 +183,6 @@ def updateProgressPercent(self, percent): QApplication.processEvents() - class Ui_SweepAllDlg(object): def setupUi(self, SweepAllDlg): SweepAllDlg.setModal(True) diff --git a/src/qt/guiHeader.py b/src/qt/guiHeader.py index 44c81ab..8821c1f 100644 --- a/src/qt/guiHeader.py +++ b/src/qt/guiHeader.py @@ -13,6 +13,7 @@ from constants import HW_devices from PyQt5.Qt import QSizePolicy + class GuiHeader(QWidget): def __init__(self, caller, *args, **kwargs): QWidget.__init__(self) diff --git a/src/qt/gui_tabGovernance.py b/src/qt/gui_tabGovernance.py index f1b65cf..64872fa 100644 --- a/src/qt/gui_tabGovernance.py +++ b/src/qt/gui_tabGovernance.py @@ -12,6 +12,7 @@ QTableWidget, QTableWidgetItem, QHBoxLayout, QPushButton, QCheckBox, QLabel, QProgressBar,\ QSpinBox, QScrollArea, QDialog + class TabGovernance_gui(QWidget): def __init__(self, caller, *args, **kwargs): QWidget.__init__(self) @@ -24,7 +25,6 @@ def __init__(self, caller, *args, **kwargs): self.questionLabel.setPixmap(self.question_icon.scaledToHeight(15, Qt.SmoothTransformation)) self.loadCacheData() - def initLayout(self): layout = QVBoxLayout(self) @@ -134,8 +134,6 @@ def initLayout(self): row.addWidget(self.voteNo_btn) layout.addLayout(row) - - def loadCacheData(self): if self.caller.parent.cache.get("votingDelayCheck"): negative_delay = self.caller.parent.cache.get("votingDelayNeg") @@ -144,7 +142,6 @@ def loadCacheData(self): self.randomDelayNeg_edt.setValue(negative_delay) self.randomDelayPos_edt.setValue(positive_delay) - def setProposalBoxHeader(self): item = QTableWidgetItem() item.setTextAlignment(Qt.AlignCenter) @@ -194,7 +191,6 @@ def setProposalBoxHeader(self): item.setToolTip("Check Proposal Details") self.proposalBox.setHorizontalHeaderItem(7, item) - def loadIcons(self): self.refresh_icon = QIcon(os.path.join(self.caller.imgDir, 'icon_refresh.png')) self.time_icon = QPixmap(os.path.join(self.caller.imgDir, 'icon_clock.png')) @@ -203,8 +199,6 @@ def loadIcons(self): self.list_icon = QIcon(os.path.join(self.caller.imgDir, 'icon_list.png')) self.question_icon = QPixmap(os.path.join(self.caller.imgDir, 'icon_question.png')) - - def resetStatusLabel(self, message=None): if message is None: self.statusLabel.setText('Loading proposals...') @@ -213,7 +207,6 @@ def resetStatusLabel(self, message=None): self.statusLabel.setVisible(True) - class ScrollMessageBox(QDialog): def __init__(self, main_wnd, message): QDialog.__init__(self, parent=main_wnd) diff --git a/src/qt/gui_tabMNConf.py b/src/qt/gui_tabMNConf.py index 01d6763..879b0ce 100644 --- a/src/qt/gui_tabMNConf.py +++ b/src/qt/gui_tabMNConf.py @@ -7,7 +7,7 @@ from PyQt5.Qt import QLabel, QFormLayout, QSpinBox from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, QCheckBox,\ QFrame, QLineEdit - + class TabMNConf_gui(QWidget): def __init__(self, masternode_alias=None, *args, **kwargs): @@ -22,10 +22,7 @@ def __init__(self, masternode_alias=None, *args, **kwargs): mainVertical2.addLayout(vBox) mainVertical2.addLayout(self.footer) self.setLayout(mainVertical2) - - - - + def clearConfigForm(self): self.testnetCheck.setChecked(False) self.edt_name.setText('') @@ -39,10 +36,7 @@ def clearConfigForm(self): self.edt_txid.setText('') self.edt_txidn.setValue(0) self.configForm.setTitle('New Masternode') - - - - + def fillConfigForm(self, masternode): self.edt_name.setText(masternode['name']) self.edt_masternodeIp.setText(masternode['ip']) @@ -59,17 +53,14 @@ def fillConfigForm(self, masternode): self.edt_txid.setText(masternode['collateral'].get('txid')) self.edt_txidn.setValue(masternode['collateral'].get('txidn')) self.configForm.setTitle("Edit Masternode") - - - - + def initConfigForm(self, masternode_alias=None): self.configForm = QGroupBox() if not masternode_alias: self.configForm.setTitle("New Masternode") else: self.configForm.setTitle("Edit Masternode [%s]" % masternode_alias) - + layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) layout.setContentsMargins(10, 20, 10, 10) @@ -168,4 +159,3 @@ def initConfigForm(self, masternode_alias=None): self.btn_saveMNConf = QPushButton('Save') self.btn_saveMNConf.setToolTip("save configuration and go back to main list") self.footer.addWidget(self.btn_saveMNConf) - \ No newline at end of file diff --git a/src/qt/gui_tabMain.py b/src/qt/gui_tabMain.py index dd1db2b..7f7cd4a 100644 --- a/src/qt/gui_tabMain.py +++ b/src/qt/gui_tabMain.py @@ -29,8 +29,6 @@ def __init__(self, caller, *args, **kwargs): ###-- Set Layout self.setLayout(mainVertical) - - def initGlobalButtons(self): ###-- Global Buttons globalButtons = QHBoxLayout() @@ -42,8 +40,6 @@ def initGlobalButtons(self): globalButtons.addWidget(self.button_sweepAllRewards) self.globalButtons = globalButtons - - def initBody(self): ###-- CENTRAL PART self.body = QGroupBox() @@ -76,8 +72,6 @@ def initBody(self): vBox.stretch(1) self.body.setLayout(vBox) - - def insert_mn_list(self, name, ip, port, row=None, isHardware=True): mnRow = QWidget() mnRow.alias = name @@ -167,8 +161,6 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): self.myList.addItem(self.current_mn[name]) self.myList.setItemWidget(self.current_mn[name], mnRow) - - def loadIcons(self): self.removeMN_icon = QIcon(os.path.join(self.caller.imgDir, 'icon_delete.png')) self.editMN_icon = QIcon(os.path.join(self.caller.imgDir, 'icon_edit.png')) diff --git a/src/qt/gui_tabRewards.py b/src/qt/gui_tabRewards.py index 98dec47..8ea0e49 100644 --- a/src/qt/gui_tabRewards.py +++ b/src/qt/gui_tabRewards.py @@ -26,8 +26,6 @@ def __init__(self, imgDir, *args, **kwargs): mainVertical.addLayout(buttonbox) self.setLayout(mainVertical) - - def initRewardsForm(self): self.collateralHidden = True self.rewardsForm = QGroupBox() @@ -143,12 +141,9 @@ def initRewardsForm(self): #--- ROW 5 self.btn_Cancel = QPushButton("Clear/Reload") - - def resetStatusLabel(self, message=None): if message is None: self.rewardsList.statusLabel.setText('Checking explorer...') else: self.rewardsList.statusLabel.setText(message) self.rewardsList.statusLabel.setVisible(True) - diff --git a/src/rpcClient.py b/src/rpcClient.py index 06b9b17..6f12f42 100644 --- a/src/rpcClient.py +++ b/src/rpcClient.py @@ -16,8 +16,8 @@ from misc import getCallerName, getFunctionName, printException, printDbg, now, timeThis from proposals import Proposal -def process_RPC_exceptions(func): +def process_RPC_exceptions(func): def process_RPC_exceptions_int(*args, **kwargs): try: args[0].httpConnection.connect() @@ -36,7 +36,6 @@ def process_RPC_exceptions_int(*args, **kwargs): return process_RPC_exceptions_int - class RpcClient: def __init__(self, rpc_protocol, rpc_host, rpc_user, rpc_password): @@ -53,9 +52,6 @@ def __init__(self, rpc_protocol, rpc_host, rpc_user, rpc_password): self.conn = AuthServiceProxy(self.rpc_url, timeout=1000, connection=self.httpConnection) - - - @process_RPC_exceptions def getBlockCount(self): n = 0 @@ -64,8 +60,6 @@ def getBlockCount(self): return n - - @process_RPC_exceptions def getBlockHash(self, blockNum): h = None @@ -74,8 +68,6 @@ def getBlockHash(self, blockNum): return h - - @process_RPC_exceptions def getBudgetVotes(self, proposal): votes = {} @@ -84,8 +76,6 @@ def getBudgetVotes(self, proposal): return votes - - @process_RPC_exceptions def getFeePerKb(self): res = MINIMUM_FEE @@ -96,8 +86,6 @@ def getFeePerKb(self): return res - - @process_RPC_exceptions def getMNStatus(self, address): mnStatus = None @@ -110,8 +98,6 @@ def getMNStatus(self, address): return mnStatus - - @process_RPC_exceptions def getMasternodeCount(self): ans = None @@ -120,8 +106,6 @@ def getMasternodeCount(self): return ans - - @process_RPC_exceptions def getMasternodes(self): printDbg("RPC: Getting masternode list...") @@ -156,8 +140,6 @@ def getMasternodes(self): return mnList - - @process_RPC_exceptions def getNextSuperBlock(self): n = 0 @@ -166,8 +148,6 @@ def getNextSuperBlock(self): return n - - @process_RPC_exceptions def getProposals(self): printDbg("RPC: Getting proposals list...") @@ -189,8 +169,6 @@ def getProposals(self): # return proposals list return proposals - - @process_RPC_exceptions def getProposalsProjection(self): printDbg("RPC: Getting proposals projection...") @@ -213,8 +191,6 @@ def getProposalsProjection(self): # return proposals list return proposals - - @process_RPC_exceptions def getProtocolVersion(self): res = DEFAULT_PROTOCOL_VERSION @@ -224,8 +200,6 @@ def getProtocolVersion(self): return res - - @process_RPC_exceptions def getRawTransaction(self, txid): res = None @@ -234,8 +208,6 @@ def getRawTransaction(self, txid): return res - - @process_RPC_exceptions def getStatus(self): status = False @@ -255,8 +227,6 @@ def getStatus(self): return status, statusMess, n, response_time, isTestnet - - @process_RPC_exceptions def isBlockchainSynced(self): res = False @@ -268,8 +238,6 @@ def isBlockchainSynced(self): return res, response_time - - @process_RPC_exceptions def mnBudgetRawVote(self, mn_tx_hash, mn_tx_index, proposal_hash, vote, time, vote_sig): res = None @@ -278,8 +246,6 @@ def mnBudgetRawVote(self, mn_tx_hash, mn_tx_index, proposal_hash, vote, time, vo return res - - @process_RPC_exceptions def decodemasternodebroadcast(self, work): printDbg("RPC: Decoding masternode broadcast...") @@ -289,8 +255,6 @@ def decodemasternodebroadcast(self, work): return res - - @process_RPC_exceptions def relaymasternodebroadcast(self, work): printDbg("RPC: Relaying masternode broadcast...") @@ -300,8 +264,6 @@ def relaymasternodebroadcast(self, work): return res - - @process_RPC_exceptions def sendRawTransaction(self, tx_hex): dbg_mess = "RPC: Sending raw transaction" @@ -313,8 +275,6 @@ def sendRawTransaction(self, tx_hex): return tx_id - - @process_RPC_exceptions def verifyMessage(self, pivxaddress, signature, message): printDbg("RPC: Verifying message...") diff --git a/src/spmtApp.py b/src/spmtApp.py index de54554..dba07e0 100644 --- a/src/spmtApp.py +++ b/src/spmtApp.py @@ -21,6 +21,7 @@ from qt.dlg_configureRPCservers import ConfigureRPCservers_dlg from qt.dlg_signmessage import SignMessage_dlg + class ServiceExit(Exception): """ Custom exception which is used to trigger the clean exit @@ -29,13 +30,11 @@ class ServiceExit(Exception): pass - def service_shutdown(signum, frame): print('Caught signal %d' % signum) raise ServiceExit - class App(QMainWindow): # Signal emitted from database sig_changed_rpcServers = pyqtSignal() @@ -91,8 +90,6 @@ def __init__(self, imgDir, app, start_args): # Initialize user interface self.initUI(masternode_list, imgDir) - - def initUI(self, masternode_list, imgDir): # Set title and geometry self.setWindowTitle(self.title) @@ -137,16 +134,12 @@ def initUI(self, masternode_list, imgDir): self.show() self.activateWindow() - - def extract_name(self, json): try: return json['name'].lower() except KeyError: return 0 - - def extract_order(self, json): try: name = json['name'] @@ -157,8 +150,6 @@ def extract_order(self, json): except KeyError: return 0 - - def closeEvent(self, *args, **kwargs): # Terminate the running threads. # Set the shutdown flag on each thread to trigger a clean shutdown of each thread. @@ -205,8 +196,6 @@ def closeEvent(self, *args, **kwargs): # Return return QMainWindow.closeEvent(self, *args, **kwargs) - - def loadMNConf(self): options = QFileDialog.Options() fileName, _ = QFileDialog.getOpenFileName(self, 'Open masternode.conf', 'masternode.conf', 'Text Files (*.conf)', options=options) @@ -214,16 +203,12 @@ def loadMNConf(self): if fileName: self.mainWindow.loadMNConf(fileName) - - def onEditRPCServer(self): # Create Dialog ui = ConfigureRPCservers_dlg(self) if ui.exec(): printDbg("Configuring RPC Servers...") - - def onSignVerifyMessage(self): # Create Dialog ui = SignMessage_dlg(self.mainWindow) diff --git a/src/tabGovernance.py b/src/tabGovernance.py index 2190144..08da8d6 100644 --- a/src/tabGovernance.py +++ b/src/tabGovernance.py @@ -22,6 +22,7 @@ from threads import ThreadFuns from utils import ecdsa_sign, ecdsa_sign_bin + class TabGovernance(): def __init__(self, caller): self.caller = caller @@ -50,16 +51,11 @@ def __init__(self, caller): # Connect Signals self.caller.sig_ProposalsLoaded.connect(self.displayProposals) - - def clear(self): # Clear voting masternodes and update cache self.votingMasternodes = [] self.caller.parent.cache['votingMasternodes'] = persistCacheSetting('cache_votingMNs', self.votingMasternodes) - - - def coutMyVotes(self, prop): myVotes = self.caller.parent.db.getMyVotes(prop.Hash) myYeas = 0 @@ -76,8 +72,6 @@ def coutMyVotes(self, prop): return myYeas, myAbstains, myNays - - def displayProposals(self): # clear box self.ui.proposalBox.setRowCount(0) @@ -177,8 +171,6 @@ def itemButton(value, icon_num): self.ui.proposalBox.setSortingEnabled(True) self.ui.proposalBox.sortByColumn(3, Qt.DescendingOrder) - - def loadProposals_thread(self, ctrl): if not self.caller.rpcConnected: printException(getCallerName(), getFunctionName(), "RPC server not connected", "") @@ -208,8 +200,6 @@ def loadProposals_thread(self, ctrl): self.proposalsLoaded = True self.caller.sig_ProposalsLoaded.emit() - - def getSelection(self): proposals = self.caller.parent.db.getProposalsList() items = self.ui.proposalBox.selectedItems() @@ -222,15 +212,10 @@ def getSelection(self): hashesList = [self.ui.proposalBox.item(row,1).text() for row in rowsList] return [p for p in proposals if p.Hash in hashesList] - - - def onRefreshProposals(self): self.ui.resetStatusLabel() ThreadFuns.runInThread(self.loadProposals_thread, (),) - - def onToggleExpiring(self): if self.ui.toggleExpiring_btn.text() == "Hide Expiring": # Hide expiring proposals @@ -250,8 +235,6 @@ def onToggleExpiring(self): self.ui.toggleExpiring_btn.setToolTip("Hide expiring proposals (yellow background) from list") self.ui.toggleExpiring_btn.setText("Hide Expiring") - - def onVote(self, vote_code): if len(self.selectedProposals) == 0: message = "NO PROPOSAL SELECTED. Select proposals from the list." @@ -267,8 +250,6 @@ def onVote(self, vote_code): if reply == 1: ThreadFuns.runInThread(self.vote_thread, ([vote_code]), self.vote_thread_end) - - def summaryDlg(self, vote_code): message = "Voting %s on the following proposal(s):

" % str(self.vote_codes[vote_code]).upper() for prop in self.selectedProposals: @@ -282,8 +263,6 @@ def summaryDlg(self, vote_code): return dlg.exec_() - - def updateMyVotes(self): proposals = self.caller.parent.db.getProposalsList() for prop in proposals: @@ -295,13 +274,9 @@ def updateMyVotes(self): for v in myVotes: self.caller.parent.db.addMyVote(v[0], prop.Hash, v[1]) - - def updateMyVotes_thread(self, ctrl): self.updateMyVotes() - - def updateSelectedMNlabel(self): selected_MN = len(self.votingMasternodes) if selected_MN == 1: @@ -310,8 +285,6 @@ def updateSelectedMNlabel(self): label = "%d masternodes selected for voting" % selected_MN self.ui.selectedMNlabel.setText(label) - - def updateSelection(self): self.selectedProposals = self.getSelection() if len(self.selectedProposals) == 1: @@ -319,8 +292,6 @@ def updateSelection(self): else: self.ui.selectedPropLabel.setText("%d proposals selected" % len(self.selectedProposals)) - - def getBudgetVoteMess(self, fNewSigs, txid, txidn, hash, vote_code, sig_time): if fNewSigs: ss = bytes.fromhex(txid)[::-1] @@ -335,8 +306,6 @@ def getBudgetVoteMess(self, fNewSigs, txid, txidn, hash, vote_code, sig_time): serialize_for_sig += hash + str(vote_code) + str(sig_time) return serialize_for_sig - - def vote_thread(self, ctrl, vote_code): # vote_code index for ["yes", "abstain", "no"] if not isinstance(vote_code, int) or vote_code not in range(3): @@ -391,7 +360,6 @@ def vote_thread(self, ctrl, vote_code): else: vote_sig = ecdsa_sign(serialize_for_sig, mnPrivKey) - # Broadcast the vote v_res = self.caller.rpcClient.mnBudgetRawVote( mn_tx_hash=currNode['collateral'].get('txid'), @@ -412,8 +380,6 @@ def vote_thread(self, ctrl, vote_code): err_msg = "Exception in vote_thread - check MN privKey" printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def vote_thread_end(self): message = '

Votes sent

' if self.successVotes > 0: diff --git a/src/tabMNConf.py b/src/tabMNConf.py index 9de2815..4129067 100644 --- a/src/tabMNConf.py +++ b/src/tabMNConf.py @@ -36,8 +36,6 @@ def __init__(self, caller, masternode_alias=None): self.ui.btn_spathToAddress.clicked.connect(lambda: self.spathToAddress()) self.ui.testnetCheck.clicked.connect(lambda: self.onChangeTestnet()) - - def addressToSpath(self): printOK("addressToSpath pressed") self.spath_found = False @@ -48,8 +46,6 @@ def addressToSpath(self): return None self.runInThread(self.findSpath, (0, 10), self.findSpath_done) - - def findSpath(self, ctrl, starting_spath, spath_count): currAddr = self.ui.edt_address.text().strip() currHwAcc = self.ui.edt_hwAccount.value() @@ -59,8 +55,6 @@ def findSpath(self, ctrl, starting_spath, spath_count): self.curr_starting_spath = starting_spath self.curr_spath_count = spath_count - - def findSpath_done(self): currAddr = self.ui.edt_address.text().strip() currHwAcc = self.ui.edt_hwAccount.value() @@ -84,8 +78,6 @@ def findSpath_done(self): starting_spath += spath_count self.runInThread(self.findSpath, (starting_spath, spath_count), self.findSpath_done) - - def findPubKey(self): printDbg("Computing public key...") currSpath = self.ui.edt_spath.value() @@ -120,36 +112,26 @@ def findPubKey(self): printOK("Public Key: %s" % result) self.ui.edt_pubKey.setText(result) - - def findRow_mn_list(self, name): row = 0 while self.caller.tabMain.myList.item(row)['name'] < name: row += 1 return row - - def isTestnet(self): return self.ui.testnetCheck.isChecked() - - def onCancelMNConfig(self): self.caller.tabs.setCurrentIndex(0) self.caller.tabs.removeTab(1) self.caller.mnode_to_change = None - - def onChangeTestnet(self): if self.isTestnet(): self.ui.edt_masternodePort.setValue(51474) else: self.ui.edt_masternodePort.setValue(51472) - - def onEditTx(self): if not self.ui.edt_txid.isEnabled(): self.ui.btn_editTxid.setText("OK") @@ -165,15 +147,11 @@ def onEditTx(self): self.ui.btn_findTxid.setEnabled(True) self.ui.btn_saveMNConf.setEnabled(True) - - def onFindSpathAndPrivKey(self): self.ui.edt_spath.setValue(0) self.ui.edt_pubKey.setText('') self.addressToSpath() - - def onLookupTx(self): # address check currAddr = self.ui.edt_address.text().strip() @@ -194,8 +172,6 @@ def onLookupTx(self): except Exception as e: printDbg(e) - - def onGenerateMNkey(self): printDbg("Generate MNkey pressed") reply = QMessageBox.Yes @@ -210,8 +186,6 @@ def onGenerateMNkey(self): newkey = generate_privkey(self.isTestnet()) self.ui.edt_mnPrivKey.setText(newkey) - - def onSaveMNConf(self): try: if self.ui.edt_pubKey.text() == "" or self.ui.edt_txid.text() == "" or self.ui.edt_mnPrivKey.text() == "": @@ -274,8 +248,6 @@ def onSaveMNConf(self): printDbg(error_msg) myPopUp_sb(self.caller, "crit", 'ERROR', error_msg) - - def spathToAddress(self): printOK("spathToAddress pressed") currHwAcc = self.ui.edt_hwAccount.value() diff --git a/src/tabMain.py b/src/tabMain.py index dfc2d22..e38ca01 100644 --- a/src/tabMain.py +++ b/src/tabMain.py @@ -40,16 +40,12 @@ def __init__(self, caller): self.ui.btn_start[name].clicked.connect(lambda: self.onStartMN()) self.ui.btn_rewards[name].clicked.connect(lambda: self.onRewardsMN()) - - def displayMNlistUpdated(self): for masternode in self.caller.masternode_list: printDbg("Checking %s (%s)..." % (masternode['name'], masternode['collateral'].get('txid'))) self.displayMNStatus(masternode) time.sleep(0.1) - - def displayMNStatus(self, currMN): statusData = None for mn in self.all_masternodes.get('masternodes'): @@ -99,8 +95,6 @@ def displayMNStatus(self, currMN): self.ui.btn_details[masternode_alias].setEnabled(True) QApplication.processEvents() - - def onCheckAllMN(self): if not self.caller.rpcConnected: myPopUp_sb(self.caller, "crit", 'SPMT - hw device check', "RPC server must be connected to perform this action.") @@ -117,8 +111,6 @@ def onCheckAllMN(self): err_msg = "error in checkAllMN" printException(getCallerName(), getFunctionName(), err_msg, e) - - def onDisplayStatusDetails(self, masternode_alias, statusData): try: ui = MnStatus_dlg(self.ui, masternode_alias, statusData) @@ -128,8 +120,6 @@ def onDisplayStatusDetails(self, masternode_alias, statusData): err_msg = "error in displayStatusDetails" printException(getCallerName(), getFunctionName(), err_msg, e.args) - - def onEditMN(self, data=None): if not data: target = self.ui.sender() @@ -143,15 +133,11 @@ def onEditMN(self, data=None): self.caller.tabMNConf.fillConfigForm(masternode) break - - def onNewMasternode(self): self.caller.tabs.insertTab(1, self.caller.tabMNConf, "Configuration") self.caller.tabMNConf.clearConfigForm() self.caller.tabs.setCurrentIndex(1) - - def onRemoveMN(self, data=None): if not data: target = self.ui.sender() @@ -169,8 +155,6 @@ def onRemoveMN(self, data=None): removeMNfromList(self.caller, masternode) break - - def onRewardsMN(self, data=None): if not data: target = self.ui.sender() @@ -179,8 +163,6 @@ def onRewardsMN(self, data=None): self.caller.tabs.setCurrentIndex(tab_index) self.caller.tabRewards.mnSelect.setCurrentText(masternode_alias) - - def onStartAllMN(self): printOK("Start-All pressed") # Check RPC & HW device @@ -207,8 +189,6 @@ def onStartAllMN(self): err_msg = "error before starting node" printException(getCallerName(), getFunctionName(), err_msg, e) - - def onStartMN(self, data=None): # Check RPC & HW device if not self.caller.rpcConnected or self.caller.hwStatus != 2: @@ -237,8 +217,6 @@ def onStartMN(self, data=None): err_msg = "error before starting node" printException(getCallerName(), getFunctionName(), err_msg, e) - - def onSweepAllRewards(self): if not self.caller.rpcConnected: myPopUp_sb(self.caller, "crit", 'SPMT - rpc check', "Connect to wallet / RPC server first") @@ -250,8 +228,6 @@ def onSweepAllRewards(self): err_msg = "exception in SweepAll_dlg" printException(getCallerName(), getFunctionName(), err_msg, e) - - # Activated by signal 'sigdone' from masternode def sendBroadcast(self, text): if text == "None": @@ -288,15 +264,11 @@ def sendBroadcast(self, text): self.sendBroadcastCheck() - - def sendBroadcastCheck(self): # If list is not empty, start other masternodes if self.mnToStartList: self.startMN() - - def startMN(self): if self.caller.hwStatus != 2: myPopUp_sb(self.caller, "warn", 'SPMT - hw device check', self.caller.hwStatusMess) @@ -308,7 +280,5 @@ def startMN(self): self.masternodeToStart.startMessage(self.caller.hwdevice, self.caller.rpcClient) # wait for signal when masternode.work is ready then ---> sendBroadcast - - def updateAllMasternodes_thread(self, ctrl): self.all_masternodes = self.caller.rpcClient.getMasternodes() diff --git a/src/tabRewards.py b/src/tabRewards.py index 144d899..a01b49c 100644 --- a/src/tabRewards.py +++ b/src/tabRewards.py @@ -59,8 +59,6 @@ def __init__(self, caller): # Connect Signals self.caller.sig_UTXOsLoading.connect(self.update_loading_utxos) - - def display_mn_utxos(self): if self.curr_name is None: return @@ -131,8 +129,6 @@ def item(value): else: self.ui.resetStatusLabel('Found no Rewards for %s' % self.curr_addr) - - def getSelection(self): # Get selected rows indexes items = self.ui.rewardsList.box.selectedItems() @@ -150,8 +146,6 @@ def getSelection(self): return selection - - def loadMnSelect(self, isInitializing=False): # save previous index index = 0 @@ -177,8 +171,6 @@ def loadMnSelect(self, isInitializing=False): self.onChangeSelectedMN(isInitializing) - - def load_utxos_thread(self, ctrl): with self.Lock: # clear rewards DB @@ -234,8 +226,6 @@ def load_utxos_thread(self, ctrl): printDbg("--# REWARDS table updated") self.caller.sig_UTXOsLoading.emit(100) - - def onCancel(self): self.ui.rewardsList.box.clearSelection() self.selectedRewards = None @@ -246,16 +236,12 @@ def onCancel(self): self.ui.collateralHidden = True self.AbortSend() - - def onChangedMNlist(self): # reload MnSelect self.loadMnSelect() # reload utxos self.onReloadUTXOs() - - def onChangeSelectedMN(self, isInitializing=False): self.curr_name = None if self.ui.mnSelect.currentIndex() >= 0: @@ -271,26 +257,19 @@ def onChangeSelectedMN(self, isInitializing=False): self.ui.resetStatusLabel() self.display_mn_utxos() - - def onSelectAllRewards(self): self.ui.rewardsList.box.selectAll() self.updateSelection() - - def onDeselectAllRewards(self): self.ui.rewardsList.box.clearSelection() self.updateSelection() - - def onReloadUTXOs(self): if not self.Lock.locked(): self.ui.resetStatusLabel() self.runInThread(self.load_utxos_thread, ()) - def onSendRewards(self): self.dest_addr = self.ui.destinationLine.text().strip() self.currFee = self.ui.feeLine.value() * 1e8 @@ -323,7 +302,6 @@ def onSendRewards(self): # SEND self.SendRewards() - def SendRewards(self, inputs=None, gui=None): # Default slots on tabRewards if gui is None: @@ -404,7 +382,6 @@ def SendRewards(self, inputs=None, gui=None): err_msg += "Wait for full synchronization then hit 'Clear/Reload'" printException(getCallerName(), getFunctionName(), err_msg, e.args) - def onToggleCollateral(self): if self.ui.rewardsList.box.collateralRow is not None: if not self.ui.collateralHidden: @@ -431,8 +408,6 @@ def onToggleCollateral(self): else: myPopUp_sb(self.caller, "warn", 'No Collateral', "No collateral selected") - - def removeSpentRewards(self): if self.selectedRewards is not None: for utxo in self.selectedRewards: @@ -440,14 +415,11 @@ def removeSpentRewards(self): else: self.caller.parent.db.clearTable('REWARDS') - - # Activated by signal sigTxdone from hwdevice def FinishSend(self, serialized_tx, amount_to_send): self.AbortSend() self.FinishSend_int(serialized_tx, amount_to_send) - def FinishSend_int(self, serialized_tx, amount_to_send): if not self.txFinished: try: @@ -502,29 +474,21 @@ def FinishSend_int(self, serialized_tx, amount_to_send): err_msg = "Exception in FinishSend" printException(getCallerName(), getFunctionName(), err_msg, e.args) - - # Activated by signal sigTxabort from hwdevice def AbortSend(self): self.ui.loadingLine.hide() self.ui.loadingLinePercent.setValue(0) self.ui.loadingLinePercent.hide() - - def updateFee(self): self.ui.feeLine.setValue(self.suggestedFee) self.ui.feeLine.setEnabled(True) - - # Activated by signal tx_progress from hwdevice def updateProgressPercent(self, percent): self.ui.loadingLinePercent.setValue(percent) QApplication.processEvents() - - def updateSelection(self, clicked_item=None): total = 0 self.selectedRewards = self.getSelection() @@ -546,16 +510,12 @@ def updateSelection(self, clicked_item=None): self.updateFee() - - def update_loading_utxos(self, percent): if percent < 100: self.ui.resetStatusLabel('Checking explorer... %d%%' % percent) else: self.display_mn_utxos() - - def updateTotalBalance(self, rewards): nAmount = 0 if rewards is not None: diff --git a/src/tests/testHwDeviceMethods.py b/src/tests/testHwDeviceMethods.py index 6f8350e..1075a6d 100644 --- a/src/tests/testHwDeviceMethods.py +++ b/src/tests/testHwDeviceMethods.py @@ -11,6 +11,7 @@ from bitcoin import bin_hash160 from utils import extract_pkh_from_locking_script, compose_tx_locking_script + class TestHwDeviceMethods(unittest.TestCase): def setUp(self): self.device = HWdevice() @@ -21,9 +22,7 @@ def setUp(self): self.skipTest("Ledger not connected or pivx app closed") if not rpcStatus: self.skipTest("RPC not connected") - - - + def tearDown(self): if hasattr(self.device, 'dongle'): self.device.dongle.close() @@ -31,16 +30,14 @@ def tearDown(self): print("Dongle Closed") if hasattr(self.rpcClient, 'conn'): self.rpcClient.parent = None - - def test_transaction(self): # Read input data from file import simplejson as json with open('test_transaction.data.json') as data_file: input_data = json.load(data_file) data_file.close() - + # Rename input data path = input_data['path'] pivx_address_to = input_data['address_from'] @@ -66,8 +63,6 @@ def test_transaction(self): self.assertIn(input_tx, decoded_inputs) decoded_inputs.remove(input_tx) - - def test_scanForBip32(self): # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) @@ -78,13 +73,11 @@ def test_scanForBip32(self): for account_n in range(5): for address_n in range(5): address = datafile.readline().split()[0] - + result, _ = self.device.scanForBip32(account_n, address, starting_spath=address_n, spath_count=1) # Address found in account_n with index. self.assertTrue(result) - - - + def test_scanForPubKey(self): # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) @@ -95,35 +88,33 @@ def test_scanForPubKey(self): for account_n in range(5): for address_n in range(5): pubkey = datafile.readline().split()[1] - + result = self.device.scanForPubKey(account_n, address_n) # Pubkey checks out self.assertEqual(result, pubkey) - - - + def test_signature(self): # Get message and path from datafile import simplejson as json with open('test_signature.data.json') as data_file: input_data = json.load(data_file) - + # Rename input data message = input_data['message'] path = input_data['path'] pivx_address = self.device.chip.getWalletPublicKey(path).get('address')[12:-2] - + # sign message on ledger print("=================================") print(" Press 'OK' on Ledger device ") print("---------------------------------") signature = self.signMess(path, message) - + # verify with rpc client result = self.rpcClient.verifyMessage(pivx_address, signature, message) print("sig = %s\naddress=%s" % (signature, pivx_address)) self.assertTrue(result) - + ## ----------------------------------------------------------------------------------- # from: # -- hwdevice.signMess @@ -149,7 +140,7 @@ def signMess(self, path, message): r = r[1:] if sLength == 33: s = s[1:] - + work = bytes(chr(27 + 4 + (signature[0] & 0x01)), "utf-8") + r + s print("Message signed") sig1 = work.hex() @@ -165,12 +156,9 @@ def signMess(self, path, message): else: print("Signature refused by the user") sig1 = "None" - + return b64encode(sig1) - - - - + # from: # -- hwdevice.prepare_transfer_tx # -- hwdevice.signTxSign @@ -181,17 +169,17 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt self.trusted_inputs = [] # https://klmoney.wordpress.com/bitcoin-dissecting-transactions-part-2-building-a-transaction-by-hand) self.arg_inputs = [] - + self.amount = 0 for idx, utxo in enumerate(utxos_to_spend): - + self.amount += int(utxo['value']) raw_tx = bytearray.fromhex(rawtransactions[utxo['tx_hash']]) if not raw_tx: raise Exception("Can't find raw transaction for txid: " + rawtransactions[utxo['tx_hash']]) - + # parse the raw transaction, so that we can extract the UTXO locking script we refer to prev_transaction = bitcoinTransaction(raw_tx) @@ -201,7 +189,7 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt trusted_input = self.device.chip.getTrustedInput(prev_transaction, utxo_tx_index) self.trusted_inputs.append(trusted_input) - + # Hash check curr_pubkey = compress_public_key(device.chip.getWalletPublicKey(bip32_path)['publicKey']) pubkey_hash = bin_hash160(curr_pubkey) @@ -236,20 +224,20 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt raise # join all outputs - will be used by Ledger for signing transaction self.all_outputs_raw = self.new_transaction.serializeOutputs() - + starting = True # sign all inputs on Ledger and add inputs in the self.new_transaction object for serialization for idx, new_input in enumerate(self.arg_inputs): device.chip.startUntrustedTransaction(starting, idx, self.trusted_inputs, new_input['locking_script']) - + device.chip.finalizeInputFull(self.all_outputs_raw) sig = device.chip.untrustedHashSign(new_input['bip32_path'], lockTime=0) - + new_input['signature'] = sig inputTx = bitcoinInput() inputTx.prevOut = bytearray.fromhex(new_input['txid'])[::-1] + int.to_bytes(new_input['outputIndex'], 4, byteorder='little') - + inputTx.script = bytearray([len(sig)]) + sig + bytearray([0x21]) + new_input['pubkey'] inputTx.sequence = bytearray([0xFF, 0xFF, 0xFF, 0xFF]) @@ -257,7 +245,7 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt self.new_transaction.inputs.append(inputTx) starting = False - + self.new_transaction.lockTime = bytearray([0, 0, 0, 0]) self.tx_raw = bytearray(self.new_transaction.serialize()) @@ -266,9 +254,6 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt else: # transaction refused by user return (None, "") - - - - + if __name__ == '__main__': - unittest.main(verbosity=2) \ No newline at end of file + unittest.main(verbosity=2) diff --git a/src/tests/testMasternodeMethods.py b/src/tests/testMasternodeMethods.py index 18df298..b55b7d3 100644 --- a/src/tests/testMasternodeMethods.py +++ b/src/tests/testMasternodeMethods.py @@ -15,17 +15,18 @@ from utils import b64encode import time + class TestMasternodeMethods(unittest.TestCase): def setUp(self): self.rpcClient = RpcClient() rpcStatus, _ = self.rpcClient.getStatus() if not rpcStatus: self.skipTest("RPC not connected") - + # read masternode data from file with open('test_masternode.data.json') as data_file: input_data_list = json.load(data_file) - + self.mnode_list = [] for input_data in input_data_list: # Rename input data @@ -43,24 +44,17 @@ def setUp(self): mnode.protocol_version = self.rpcClient.getProtocolVersion() # Add it to list self.mnode_list.append(mnode) - - - + def tearDown(self): if hasattr(self.rpcClient, 'conn'): self.rpcClient.parent = None - - - + def test_finalizeStartMessage(self): for mnode in self.mnode_list: # Test message construction mnode.finalizeStartMessage(mnode.sig1) sleep(3) - - - - + # Activated by signal from masternode @pyqtSlot(str) def finalizeStartMessage_end(self, text): @@ -86,7 +80,6 @@ def finalizeStartMessage_end(self, text): # check masternode signature node_sig = b64encode(text[320:450]) self.assertEqual(ret['vchSig'], node_sig) - - + if __name__ == '__main__': unittest.main(verbosity=2) \ No newline at end of file diff --git a/src/tests/testPivx_b58Methods.py b/src/tests/testPivx_b58Methods.py index 47272c3..823d437 100644 --- a/src/tests/testPivx_b58Methods.py +++ b/src/tests/testPivx_b58Methods.py @@ -8,8 +8,9 @@ from pivx_b58 import b58chars, b58encode, b58decode from random import randint + class TestPivx_b58Methods(unittest.TestCase): - + def test_encodeDecode(self): # get 32 random bytes text = self.randomBytesString(32) @@ -19,9 +20,7 @@ def test_encodeDecode(self): print("\nEncoded Text: %s\n" % encoded_text) # verify self.assertEqual(b58decode(encoded_text), text) - - - + def test_decodeEncode(self): # get 10 random base58 chars text = self.randomB58String(10) @@ -31,28 +30,20 @@ def test_decodeEncode(self): print("\nDecoded Text: %s\n" % decoded_text) # verify self.assertEqual(b58encode(decoded_text), text) - - - - + def randomBytesString(self, length): randomString = bytes() for _ in range(length): randomString += bytes([randint(0, 256)]) - + return randomString - - - + def randomB58String(self, length): randomString = '' for _ in range(length): randomString += b58chars[randint(0, len(b58chars))] - + return randomString - - - - + if __name__ == '__main__': - unittest.main(verbosity=2) \ No newline at end of file + unittest.main(verbosity=2) diff --git a/src/tests/testPivx_hashlibMethods.py b/src/tests/testPivx_hashlibMethods.py index 48a37d5..1a0ee7f 100644 --- a/src/tests/testPivx_hashlibMethods.py +++ b/src/tests/testPivx_hashlibMethods.py @@ -9,8 +9,9 @@ import bitcoin from pivx_b58 import b58decode + class TestPivx_hashlibMethods(unittest.TestCase): - + def test_generate_privkey(self): # generate random private key randomKey = generate_privkey() @@ -22,9 +23,7 @@ def test_generate_privkey(self): randomKey_bin = bytes.fromhex(b58decode(randomKey).hex()) randomKey_bin_check = bitcoin.bin_dbl_sha256(randomKey_bin[0:-4])[0:4] self.assertEqual(randomKey_bin[-4:], randomKey_bin_check) - - - + def test_pubkey_to_address(self): # generate random private key and convert to public randomPubKey = bitcoin.privkey_to_pubkey(generate_privkey()) @@ -36,8 +35,6 @@ def test_pubkey_to_address(self): randomPivxAddr_bin = bytes.fromhex(b58decode(randomPivxAddr).hex()) randomPivxAddr_bin_check = bitcoin.bin_dbl_sha256(randomPivxAddr_bin[0:-4])[0:4] self.assertEqual(randomPivxAddr_bin[-4:], randomPivxAddr_bin_check) - - - + if __name__ == '__main__': - unittest.main(verbosity=2) \ No newline at end of file + unittest.main(verbosity=2) diff --git a/src/tests/testUtilsMethods.py b/src/tests/testUtilsMethods.py index b5e055b..8d2c318 100644 --- a/src/tests/testUtilsMethods.py +++ b/src/tests/testUtilsMethods.py @@ -10,8 +10,9 @@ from bitcoin import privkey_to_pubkey from bitcoin.main import b58check_to_hex + class TestUtilsMethods(unittest.TestCase): - + def test_checkPivxAddr(self): # Generate Valid PIVX address pK = privkey_to_pubkey(generate_privkey()) @@ -28,9 +29,7 @@ def test_checkPivxAddr(self): for _ in range(10): pivxAddr3 += self.getRandomChar() self.assertFalse(checkPivxAddr(pivxAddr3)) - - - + def test_compose_tx_locking_script(self): # check with P2PKH addresses # Generate Valid PIVX address @@ -50,17 +49,11 @@ def test_compose_tx_locking_script(self): self.assertEqual(result[23], int('88', 16)) # check OP_CHECKSIG self.assertEqual(result[24], int('AC', 16)) - - - - - + def getRandomChar(self): import string import random return random.choice(string.ascii_letters) - - - + if __name__ == '__main__': - unittest.main(verbosity=2) \ No newline at end of file + unittest.main(verbosity=2) diff --git a/src/threads.py b/src/threads.py index 7781970..f1b6797 100644 --- a/src/threads.py +++ b/src/threads.py @@ -13,6 +13,7 @@ from functools import partial from workerThread import WorkerThread + class ThreadFuns: @staticmethod def runInThread(worker_fun, worker_fun_args, on_thread_finish=None, on_thread_exception=None, diff --git a/src/trezorClient.py b/src/trezorClient.py index da6c690..25efa9b 100644 --- a/src/trezorClient.py +++ b/src/trezorClient.py @@ -46,7 +46,6 @@ def process_trezor_exceptions_int(*args, **kwargs): return process_trezor_exceptions_int - class TrezorApi(QObject): # signal: sig1 (thread) is done - emitted by signMessageFinish sig1done = pyqtSignal(str) @@ -61,7 +60,6 @@ class TrezorApi(QObject): # signal: sig_disconnected -emitted with DisconnectedException sig_disconnected = pyqtSignal(str) - def __init__(self, model, main_wnd, *args, **kwargs): QObject.__init__(self, *args, **kwargs) self.model = model # index of HW_devices @@ -80,8 +78,6 @@ def __init__(self, model, main_wnd, *args, **kwargs): printDbg("Creating HW device class") self.sig_progress.connect(self.updateSigProgress) - - @process_trezor_exceptions def append_inputs_to_TX(self, utxo, bip32_path, inputs): if utxo['staker'] != "": @@ -99,15 +95,12 @@ def append_inputs_to_TX(self, utxo, bip32_path, inputs): ) inputs.append(it) - - def checkModel(self, model): if HW_devices[self.model][0] == "TREZOR One": return model == "1" else: return model == "T" - def closeDevice(self, message=''): printDbg("Closing TREZOR client") self.sig_disconnected.emit(message) @@ -120,8 +113,6 @@ def closeDevice(self, message=''): pass self.client = None - - @process_trezor_exceptions def initDevice(self): printDbg("Initializing Trezor") @@ -158,8 +149,6 @@ def initDevice(self): _ = btc.get_address(self.client, 'PIVX', bip32_path, False) self.status = 2 - - def load_prev_txes(self, rewardsArray): curr_utxo_checked = 0 txes = {} @@ -179,7 +168,6 @@ def load_prev_txes(self, rewardsArray): self.tx_progress.emit(100) return txes - def json_to_tx(self, jtx): t = trezor_proto.TransactionType() t.version = jtx["version"] @@ -188,7 +176,6 @@ def json_to_tx(self, jtx): t.bin_outputs = [self.json_to_bin_output(output) for output in jtx["vout"]] return t - def json_to_input(self, input): i = trezor_proto.TxInputType() if "coinbase" in input: @@ -202,14 +189,12 @@ def json_to_input(self, input): i.sequence = input["sequence"] return i - def json_to_bin_output(self, output): o = trezor_proto.TxOutputBinType() o.amount = int(output["value"]) o.script_pubkey = bytes.fromhex(output["scriptPubKey"]["hex"]) return o - def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, isTestnet=False): inputs = [] outputs = [] @@ -261,8 +246,6 @@ def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, i ThreadFuns.runInThread(self.signTxSign, (inputs, outputs, txes, isTestnet), self.signTxFinish) - - @process_trezor_exceptions def scanForAddress(self, account, spath, isTestnet=False): with self.lock: @@ -275,8 +258,6 @@ def scanForAddress(self, account, spath, isTestnet=False): return curr_addr - - @process_trezor_exceptions def scanForPubKey(self, account, spath, isTestnet=False): hwpath = "%d'/0/%d" % (account, spath) @@ -291,16 +272,12 @@ def scanForPubKey(self, account, spath, isTestnet=False): return result.node.public_key.hex() - - def setBoxIcon(self, box, caller): if HW_devices[self.model][0] == "TREZOR One": box.setIconPixmap(caller.tabMain.trezorOneImg.scaledToHeight(200, Qt.SmoothTransformation)) else: box.setIconPixmap(caller.tabMain.trezorImg.scaledToHeight(200, Qt.SmoothTransformation)) - - def signMess(self, caller, hwpath, message, isTestnet=False): if isTestnet: path = MPATH_TESTNET + hwpath @@ -319,8 +296,6 @@ def signMess(self, caller, hwpath, message, isTestnet=False): # Sign message ThreadFuns.runInThread(self.signMessageSign, (path, message, isTestnet), self.signMessageFinish) - - @process_trezor_exceptions def signMessageSign(self, ctrl, path, mess, isTestnet): self.signature = None @@ -333,9 +308,6 @@ def signMessageSign(self, ctrl, path, mess, isTestnet): signed_mess = btc.sign_message(self.client, hw_coin, bip32_path, mess) self.signature = signed_mess.signature - - - def signMessageFinish(self): with self.lock: self.mBox.accept() @@ -345,8 +317,6 @@ def signMessageFinish(self): else: self.sig1done.emit(self.signature.hex()) - - @process_trezor_exceptions def signTxSign(self, ctrl, inputs, outputs, txes, isTestnet=False): self.tx_raw = None @@ -360,8 +330,6 @@ def signTxSign(self, ctrl, inputs, outputs, txes, isTestnet=False): self.tx_raw = bytearray(signed[1]) self.sig_progress.emit(100) - - def signTxFinish(self): self.mBox2.accept() if self.tx_raw is not None: @@ -372,8 +340,6 @@ def signTxFinish(self): printOK("Transaction refused by the user") self.sigTxabort.emit() - - def updateSigProgress(self, percent): # -1 simply adds a waiting message to the actual progress if percent == -1: @@ -385,7 +351,6 @@ def updateSigProgress(self, percent): QApplication.processEvents() - # From trezorlib.btc def sign_tx(sig_percent, client, coin_name, inputs, outputs, details=None, prev_txes=None): # set up a transactions dict @@ -503,8 +468,6 @@ def copy_tx_meta(tx): return signatures, serialized_tx - - class TrezorUi(object): def __init__(self): self.prompt_shown = False @@ -538,8 +501,6 @@ def button_request(self, msg_code): self.prompt_shown = True - - def ask_for_pin_callback(msg, hide_numbers=True): dlg = PinMatrix_dlg(title=msg, fHideBtns=hide_numbers) if dlg.exec_(): diff --git a/src/txCache.py b/src/txCache.py index 8b21189..ebddf29 100644 --- a/src/txCache.py +++ b/src/txCache.py @@ -9,12 +9,13 @@ ''' Connects with database and rpc clients to keep a cache for rawtxes ''' + + class TxCache(): def __init__(self, main_wnd): self.main_wnd = main_wnd - ''' tries to fetch rawtx from database. if not found, tries with rpc (and if successful, updates the database) diff --git a/src/utils.py b/src/utils.py index 5c6c81e..d6c833e 100644 --- a/src/utils.py +++ b/src/utils.py @@ -15,7 +15,6 @@ from pivx_b58 import b58decode from pivx_hashlib import wif_to_privkey, pubkey_to_address - # Bitcoin opcodes used in the application OP_DUP = b'\x76' OP_HASH160 = b'\xA9' @@ -36,7 +35,6 @@ def b64encode(text): return base64.b64encode(bytearray.fromhex(text)).decode('utf-8') - def checkPivxAddr(address, isTestnet=False): try: # check leading char 'D' or (for testnet) 'x' or 'y' @@ -56,7 +54,6 @@ def checkPivxAddr(address, isTestnet=False): return False - def compose_tx_locking_script(dest_address, isTestnet): """ Create a Locking script (ScriptPubKey) that will be assigned to a transaction output. @@ -91,7 +88,6 @@ def compose_tx_locking_script(dest_address, isTestnet): return scr - def compose_tx_locking_script_OR(message): """ Create a Locking script (ScriptPubKey) that will be assigned to a transaction output. @@ -104,7 +100,6 @@ def compose_tx_locking_script_OR(message): return scr - def ecdsa_sign(msg, priv): return ecdsa_sign_bin(electrum_sig_hash(msg), priv) @@ -120,7 +115,6 @@ def ecdsa_verify_addr(msg, sig, addr): return pubkey_to_address(Qenc, isTestnet) == addr - def electrum_sig_hash(message): """ Based on project: https://github.com/chaeplin/dashmnb. @@ -129,7 +123,6 @@ def electrum_sig_hash(message): return dbl_sha256(padded) - def ecdsa_sign_bin(msgbin, priv): v, r, s = ecdsa_raw_sign(msgbin, priv) sig = encode_sig(v, r, s) @@ -141,7 +134,6 @@ def ecdsa_sign_bin(msgbin, priv): return sig - def extract_pkh_from_locking_script(script): if len(script) == 25: if script[0:1] == OP_DUP and script[1:2] == OP_HASH160: @@ -171,6 +163,7 @@ def IsPayToColdStaking(script): script[49] == int.from_bytes(OP_EQUALVERIFY, 'little') and script[50] == int.from_bytes(OP_CHECKSIG, 'little')) + def GetDelegatedStaker(script): return script[6:26] @@ -179,7 +172,6 @@ def from_string_to_bytes(a): return a if isinstance(a, bytes) else bytes(a, 'utf-8') - def ipmap(ip, port): try: ipv6map = '' @@ -207,7 +199,6 @@ def ipmap(ip, port): else: raise Exception("invalid version number (%d)" % ipAddr.version) - ipv6map += int(port).to_bytes(2, byteorder='big').hex() if len(ipv6map) != 36: raise Exception("Problems! len is %d" % len(ipv6map)) @@ -218,7 +209,6 @@ def ipmap(ip, port): printException(getCallerName(), getFunctionName(), err_msg, e.args) - def num_to_varint(a): """ Based on project: https://github.com/chaeplin/dashmnb @@ -234,7 +224,6 @@ def num_to_varint(a): return int(255).to_bytes(1, byteorder='big') + x.to_bytes(8, byteorder='little') - def read_varint(buffer, offset): if (buffer[offset] < 0xfd): value_size = 1 @@ -253,7 +242,6 @@ def read_varint(buffer, offset): return value, value_size - def serialize_input_str(tx, prevout_n, sequence, script_sig): """ Based on project: https://github.com/chaeplin/dashmnb. diff --git a/src/watchdogThreads.py b/src/watchdogThreads.py index 8c97088..bab745c 100644 --- a/src/watchdogThreads.py +++ b/src/watchdogThreads.py @@ -17,6 +17,7 @@ class CtrlObject(object): pass + class RpcWatchdog(QObject): def __init__(self, control_tab, timer_off=10, timer_on=120, *args, **kwargs): QObject.__init__(self, *args, **kwargs) @@ -28,8 +29,6 @@ def __init__(self, control_tab, timer_off=10, timer_on=120, *args, **kwargs): self.ctrl_obj = CtrlObject() self.ctrl_obj.finish = False - - def run(self): while not self.shutdown_flag.is_set(): # update status without printing on debug @@ -43,4 +42,3 @@ def run(self): sleep(self.timer_on) printOK("Exiting Rpc Watchdog Thread") - diff --git a/src/workerThread.py b/src/workerThread.py index 55cfdbd..fcbebb9 100644 --- a/src/workerThread.py +++ b/src/workerThread.py @@ -13,9 +13,11 @@ from misc import printError + class CtrlObject(object): pass + class WorkerThread(QThread): """ Helper class for running function inside a thread. From 2b91bd5f16603c631d4cf8c81f3e28eea67725cd Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 21:57:48 -0800 Subject: [PATCH 02/16] Make comment lines adhere to PEP8 standards --- spmt.py | 6 ++-- src/database.py | 6 ++-- src/mainWindow.py | 50 ++++++++++++++++--------------- src/masternode.py | 8 ++--- src/proposals.py | 2 +- src/qt/dlg_budgetProjection.py | 24 +++++++-------- src/qt/dlg_configureRPCservers.py | 12 ++++---- src/qt/dlg_findCollTx.py | 6 ++-- src/qt/dlg_selectMNs.py | 4 +-- src/qt/dlg_sweepAll.py | 6 ++-- src/qt/gui_tabGovernance.py | 10 +++---- src/qt/gui_tabMNConf.py | 20 ++++++------- src/qt/gui_tabMain.py | 36 +++++++++++----------- src/qt/gui_tabRewards.py | 16 +++++----- src/tabGovernance.py | 2 +- src/tabRewards.py | 6 ++-- src/tests/testHwDeviceMethods.py | 2 +- 17 files changed, 108 insertions(+), 108 deletions(-) diff --git a/spmt.py b/spmt.py index 2f944e0..c845ccd 100644 --- a/spmt.py +++ b/spmt.py @@ -51,7 +51,7 @@ # Create App app = QApplication(sys.argv) - ### -- style stuff + # -- style stuff spmtLogo_file = os.path.join(imgDir, 'splashscreen.png') labelstyle = "QLabel { font-size: 14px; color: purple; font-style: italic; text-align: center;}" barStyle = "QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #372f43,stop: 0.6 #5c4c7a, stop: 0.8 #663399);border-bottom-right-radius: 7px;border-bottom-left-radius: 7px;border-top: 2px solid #8A2BE2;}" @@ -82,8 +82,6 @@ while time.time() < t + 0.01: app.processEvents() - ### -------------- - # Create QMainWindow Widget ex = App(imgDir, app, args) @@ -91,7 +89,7 @@ splash.close() try: - ##-- Launch RPC watchdog + # -- Launch RPC watchdog ex.mainWindow.rpc_watchdogThread.start() except Exception as e: print(e) diff --git a/src/database.py b/src/database.py index 64a5b32..7720467 100644 --- a/src/database.py +++ b/src/database.py @@ -152,7 +152,7 @@ def initTables(self): " yeas INTEGER, nays INTEGER, abstains INTEGER, " " totalPayment REAL, monthlyPayment REAL)") - #cursor.execute("CREATE TABLE IF NOT EXISTS PROJECTED_PROPOSALS(" + # cursor.execute("CREATE TABLE IF NOT EXISTS PROJECTED_PROPOSALS(" # " name TEXT, hash TEXT PRIMARY KEY, " # " allotted REAL, votes INTEGER, totaAllotted REAL)") @@ -587,9 +587,9 @@ def getRawTx(self, tx_hash): return None def clearRawTxes(self, minTime): - ''' + """ removes txes with lastfetch older than mintime - ''' + """ printDbg("Pruning table RAWTXES") try: cursor = self.getCursor() diff --git a/src/mainWindow.py b/src/mainWindow.py index 49d1249..c2b55fb 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -53,10 +53,10 @@ def __init__(self, parent, masternode_list, imgDir): self.runInThread = ThreadFuns.runInThread self.lock = threading.Lock() - ###-- Masternode list + # -- Masternode list self.masternode_list = masternode_list - ###-- Create clients and statuses + # -- Create clients and statuses self.hwStatus = 0 self.hwModel = 0 self.hwStatusMess = "Not Connected" @@ -68,33 +68,34 @@ def __init__(self, parent, masternode_list, imgDir): # Changes when an RPC client is connected (affecting API client) self.isTestnetRPC = self.parent.cache['isTestnetRPC'] - ###-- Load icons & images + # -- Load icons & images self.loadIcons() - ###-- Create main layout + + # -- Create main layout self.layout = QVBoxLayout() self.header = GuiHeader(self) self.initConsole() self.layout.addWidget(self.header) - ##-- Load RPC Servers list (init selection and self.isTestnet) + # -- Load RPC Servers list (init selection and self.isTestnet) self.updateRPClist() - ##-- Init HW selection + # -- Init HW selection self.header.hwDevices.setCurrentIndex(self.parent.cache['selectedHW_index']) - ##-- init HW Client + # -- init HW Client self.hwdevice = HWdevice(self) - ##-- init Api Client + # -- init Api Client self.apiClient = ApiClient(self.isTestnetRPC) - ###-- Create Queue to redirect stdout + # -- Create Queue to redirect stdout self.queue = wqueue - ###-- Init last logs + # -- Init last logs logging.debug("STARTING SPMT") - ###-- Create the thread to update console log for stdout + # -- Create the thread to update console log for stdout self.consoleLogThread = QThread() self.myWSReceiver = WriteStreamReceiver(self.queue) self.myWSReceiver.mysignal.connect(self.append_to_console) @@ -103,24 +104,24 @@ def __init__(self, parent, masternode_list, imgDir): self.consoleLogThread.start() printDbg("Console Log thread started") - ###-- Initialize tabs + # -- Initialize tabs self.tabs = QTabWidget() self.t_main = TabMain(self) self.t_mnconf = TabMNConf(self) self.t_rewards = TabRewards(self) self.t_governance = TabGovernance(self) - ###-- Add tabs + # -- Add tabs self.tabs.setTabPosition(QTabWidget.West) self.tabs.addTab(self.tabMain, "Masternode List") - #self.tabs.addTab(self.tabMNConf, "MN Configuration") + # self.tabs.addTab(self.tabMNConf, "MN Configuration") self.tabs.addTab(self.tabRewards, "Rewards") self.tabs.addTab(self.tabGovernance, "Governance") - ###-- Connect change action + # -- Connect change action self.tabs.currentChanged.connect(lambda: self.onTabChange()) - ###-- Add tabs and console to Layout + # -- Add tabs and console to Layout self.splitter = QSplitter(Qt.Vertical) self.splitter.addWidget(self.tabs) self.splitter.addWidget(self.console) @@ -128,25 +129,25 @@ def __init__(self, parent, masternode_list, imgDir): self.splitter.setStretchFactor(1,1) self.layout.addWidget(self.splitter) - ###-- Set Layout + # -- Set Layout self.setLayout(self.layout) - ###-- Init Settings + # -- Init Settings self.initSettings() - ###-- Connect buttons/signals + # -- Connect buttons/signals self.connButtons() - ##-- Check version + # -- Check version self.onCheckVersion() - ###-- Create RPC Whatchdog + # -- Create RPC Whatchdog self.rpc_watchdogThread = QThread() self.myRpcWd = RpcWatchdog(self) self.myRpcWd.moveToThread(self.rpc_watchdogThread) self.rpc_watchdogThread.started.connect(self.myRpcWd.run) - ###-- Let's go + # -- Let's go self.mnode_to_change = None printOK("Hello! Welcome to " + parent.title) @@ -178,7 +179,8 @@ def connButtons(self): self.header.button_checkHw.clicked.connect(lambda: self.onCheckHw()) self.header.rpcClientsBox.currentIndexChanged.connect(self.onChangeSelectedRPC) self.header.hwDevices.currentIndexChanged.connect(self.onChangeSelectedHW) - ##-- Connect signals + + # -- Connect signals self.sig_clearRPCstatus.connect(self.clearRPCstatus) self.sig_RPCstatusUpdated.connect(self.showRPCstatus) self.parent.sig_changed_rpcServers.connect(self.updateRPClist) @@ -235,7 +237,7 @@ def initConsole(self): def initSettings(self): self.splitter.setSizes([self.parent.cache.get("splitter_x"), self.parent.cache.get("splitter_y")]) - ###-- Hide console if it was previously hidden + # -- Hide console if it was previously hidden if self.parent.cache.get("console_hidden"): self.onToggleConsole() diff --git a/src/masternode.py b/src/masternode.py index f7a4fa2..02d2bc8 100644 --- a/src/masternode.py +++ b/src/masternode.py @@ -21,9 +21,9 @@ class Masternode(QObject): - ''' + """ Base class for all masternodes - ''' + """ mnCount = 0 # signal: sig (thread) is done - emitted by finalizeStartMessage sigdone = pyqtSignal(str) @@ -78,7 +78,7 @@ def signature1(self, device): printDbg("SerializedData: %s" % serializedData) # HW wallet signature device.signMess(self.tab_main.caller, self.nodePath, serializedData, self.isTestnet) - #wait for signal when device.sig1 is ready then --> finalizeStartMessage + # wait for signal when device.sig1 is ready then --> finalizeStartMessage except Exception as e: err_msg = "error in signature1" printException(getCallerName(), getFunctionName(), err_msg, e.args) @@ -177,7 +177,7 @@ def finalizeStartMessage(self, text): self.sigdone.emit(work) def startMessage(self, device, rpcClient): - # setuo rpc connection + # setup rpc connection self.rpcClient = rpcClient try: # update protocol version diff --git a/src/proposals.py b/src/proposals.py index 6393b6f..a4a44aa 100644 --- a/src/proposals.py +++ b/src/proposals.py @@ -34,7 +34,7 @@ def __init__(self, name, URL, Hash, FeeHash, BlockStart, BlockEnd, TotalPayCount self.Abstains = int(Abstains) self.ToalPayment = TotalPayment self.MonthlyPayment = MonthlyPayment - ## list of personal masternodes voting + # list of personal masternodes voting self.MyYeas = [] self.MyAbstains = [] self.MyNays = [] diff --git a/src/qt/dlg_budgetProjection.py b/src/qt/dlg_budgetProjection.py index 7ec12f4..17ada1f 100644 --- a/src/qt/dlg_budgetProjection.py +++ b/src/qt/dlg_budgetProjection.py @@ -32,7 +32,7 @@ def displayBudgetProjection(self): return # header - ## blocks to next superBlock (== minutes) + # blocks to next superBlock (== minutes) blocks_to_SB = self.next_superBlock - self.main_wnd.caller.rpcLastBlock self.ui.nextSuperBlock_label.setText("%s" % str(self.next_superBlock)) @@ -61,9 +61,9 @@ def loadBudgetProjection_thread(self, ctrl): if not self.main_wnd.caller.rpcConnected: printException(getCallerName(), getFunctionName(), "RPC server not connected", "") return - ## get next superBlock + # get next superBlock self.next_superBlock = self.main_wnd.caller.rpcClient.getNextSuperBlock() - ## get budget projection + # get budget projection self.projection = self.main_wnd.caller.rpcClient.getProposalsProjection() @@ -72,15 +72,15 @@ def setupUi(self, BudgetProjectionDlg): BudgetProjectionDlg.setModal(True) layout = QVBoxLayout(BudgetProjectionDlg) layout.setContentsMargins(8, 8, 8, 8) - ## tile + # tile title = QLabel("Budget Projection Overview") title.setAlignment(Qt.AlignCenter) layout.addWidget(title) - ## header + # header header = QGroupBox("Budget Projection Details") header_layout = QFormLayout() header_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) - ## row 1 + # row 1 row = QHBoxLayout() self.availableBudget_label = QLabel("43200.0 PIV") row.addWidget(self.availableBudget_label) @@ -89,14 +89,14 @@ def setupUi(self, BudgetProjectionDlg): self.nextSuperBlock_label = QLabel("--") row.addWidget(self.nextSuperBlock_label) header_layout.addRow(QLabel("Available Budget: "), row) - ## row 2 + # row 2 row = QHBoxLayout() self.allottedBudget_label = QLabel("--") row.addWidget(self.allottedBudget_label) row.addStretch(1) row.addWidget(QLabel("Time to next SuperBlock (approx): ")) header_layout.addRow(QLabel("Total Allotted Budget: "), row) - ## row 3 + # row 3 row = QHBoxLayout() self.remainingBudget_label = QLabel("--") row.addWidget(self.remainingBudget_label) @@ -104,13 +104,13 @@ def setupUi(self, BudgetProjectionDlg): self.timeToNextSB_label = QLabel("--") row.addWidget(self.timeToNextSB_label) header_layout.addRow(QLabel("Remaining Budget: "), row) - ## row 4 + # row 4 self.passingProposals_label = QLabel("--") header_layout.addRow(QLabel("Passing Proposals: "), self.passingProposals_label) - ## + # header.setLayout(header_layout) layout.addWidget(header) - ## LIST + # LIST self.proposals_lst = QTableWidget() self.proposals_lst.setSelectionMode(QAbstractItemView.NoSelection) self.proposals_lst.setColumnCount(4) @@ -133,7 +133,7 @@ def setupUi(self, BudgetProjectionDlg): self.proposals_lst.setColumnWidth(2, 130) self.proposals_lst.setColumnWidth(3, 160) layout.addWidget(self.proposals_lst) - ## button ok + # button ok self.ok_btn = QPushButton("Ok") layout.addWidget(self.ok_btn) BudgetProjectionDlg.resize(650, 500) diff --git a/src/qt/dlg_configureRPCservers.py b/src/qt/dlg_configureRPCservers.py index e0a0b75..d17c72e 100644 --- a/src/qt/dlg_configureRPCservers.py +++ b/src/qt/dlg_configureRPCservers.py @@ -45,7 +45,7 @@ def insert_server_list(self, server): server_text = "%s" % server_text server_row.addWidget(QLabel(server_text)) server_row.addStretch(1) - ## -- Edit button + # -- Edit button editBtn = QPushButton() editBtn.setIcon(self.main_wnd.mainWindow.tabMain.editMN_icon) editBtn.setToolTip("Edit server configuration") @@ -54,7 +54,7 @@ def insert_server_list(self, server): editBtn.setToolTip('Default servers are not editable') editBtn.clicked.connect(lambda: self.onAddServer(index)) server_row.addWidget(editBtn) - ## -- Remove button + # -- Remove button removeBtn = QPushButton() removeBtn.setIcon(self.main_wnd.mainWindow.tabMain.removeMN_icon) removeBtn.setToolTip("Remove server configuration") @@ -66,7 +66,7 @@ def insert_server_list(self, server): removeBtn.setToolTip('Cannot remove default servers') removeBtn.clicked.connect(lambda: self.onRemoveServer(index)) server_row.addWidget(removeBtn) - ## -- + # -- server_line.setLayout(server_row) self.serverItems[id] = QListWidgetItem() self.serverItems[id].setSizeHint(server_line.sizeHint()) @@ -162,19 +162,19 @@ def setupUi(self, ConfigureRPCserversDlg): ## -- Layout self.layout = QVBoxLayout(ConfigureRPCserversDlg) self.layout.setSpacing(10) - ## -- Servers List + # -- Servers List self.serversBox = QListWidget() self.layout.addWidget(self.serversBox) ## -- 'Add Server' button self.addServer_btn = QPushButton("Add RPC Server") self.layout.addWidget(self.addServer_btn) - ## -- 'Close' button + # -- 'Close' button hBox = QHBoxLayout() hBox.addStretch(1) self.close_btn = QPushButton("Close") hBox.addWidget(self.close_btn) self.layout.addLayout(hBox) - ## -- Edit section + # -- Edit section self.editFrame = QFrame() frameLayout = QFormLayout() frameLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) diff --git a/src/qt/dlg_findCollTx.py b/src/qt/dlg_findCollTx.py index f7fbc3e..efaee34 100644 --- a/src/qt/dlg_findCollTx.py +++ b/src/qt/dlg_findCollTx.py @@ -23,16 +23,16 @@ def __init__(self, mainTab): def setupUI(self): Ui_FindCollateralTxDlg.setupUi(self, self) self.setWindowTitle('Find Collateral Tx') - ##--- feedback + # --- feedback self.lblMessage.setVisible(False) self.lblMessage.setVisible(True) self.lblMessage.setText('Checking explorer...') def load_data(self, pivx_addr): self.pivx_addr = pivx_addr - ##--- PIVX Address + # --- PIVX Address self.edtAddress.setText(self.pivx_addr) - ##--- Load utxos + # --- Load utxos ThreadFuns.runInThread(self.load_utxos_thread, (), self.display_utxos) def display_utxos(self): diff --git a/src/qt/dlg_selectMNs.py b/src/qt/dlg_selectMNs.py index 272bed5..1592a04 100644 --- a/src/qt/dlg_selectMNs.py +++ b/src/qt/dlg_selectMNs.py @@ -24,7 +24,7 @@ def __init__(self, main_wnd): self.setWindowTitle('Masternode List') self.initUI() self.loadMasternodes() - ## connect buttons + # connect buttons self.ui.selectAll_btn.clicked.connect(lambda: self.selectAll()) self.ui.deselectAll_btn.clicked.connect(lambda: self.ui.mnList.clearSelection()) self.ui.ok_btn.clicked.connect(lambda: self.onOK()) @@ -80,7 +80,7 @@ def setupUi(self, SelectMNsDlg): item.setTextAlignment(Qt.AlignCenter) self.mnList.setHorizontalHeaderItem(0, item) layout.addWidget(self.mnList) - ## buttons + # buttons hBox = QHBoxLayout() self.selectAll_btn = QPushButton("Select All") self.selectAll_btn.setToolTip("Select all masternodes") diff --git a/src/qt/dlg_sweepAll.py b/src/qt/dlg_sweepAll.py index 177656a..c2cf9d9 100644 --- a/src/qt/dlg_sweepAll.py +++ b/src/qt/dlg_sweepAll.py @@ -26,15 +26,15 @@ def __init__(self, main_tab): QDialog.__init__(self, parent=main_tab.ui) self.main_tab = main_tab self.setWindowTitle('Sweep All Rewards') - ##--- Initialize Selection + # --- Initialize Selection self.loading_txes = False self.feePerKb = MINIMUM_FEE self.suggestedFee = MINIMUM_FEE - ##--- Initialize GUI + # --- Initialize GUI self.setupUI() # Connect GUI buttons self.connectButtons() - # Connect Signals + # Connect Signals self.main_tab.caller.sig_UTXOsLoading.connect(self.update_loading_utxos) # Called each time before exec_ in showDialog diff --git a/src/qt/gui_tabGovernance.py b/src/qt/gui_tabGovernance.py index 64872fa..e0bd43e 100644 --- a/src/qt/gui_tabGovernance.py +++ b/src/qt/gui_tabGovernance.py @@ -28,7 +28,7 @@ def __init__(self, caller, *args, **kwargs): def initLayout(self): layout = QVBoxLayout(self) - ## -- ROW 1 + # -- ROW 1 row = QHBoxLayout() self.budgetProjection_btn = QPushButton() self.budgetProjection_btn.setToolTip("Check Budget Projection...") @@ -53,7 +53,7 @@ def initLayout(self): row.addWidget(self.toggleExpiring_btn) layout.addLayout(row) - ## -- ROW 2 + # -- ROW 2 self.proposalBox = QTableWidget() self.proposalBox.setMinimumHeight(280) self.proposalBox.setSelectionMode(QAbstractItemView.MultiSelection) @@ -63,7 +63,7 @@ def initLayout(self): self.proposalBox.setRowCount(0) self.proposalBox.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.proposalBox.setSortingEnabled(True) - #self.proposalBox.verticalHeader().hide + # self.proposalBox.verticalHeader().hide self.setProposalBoxHeader() self.proposalBox.setColumnWidth(1, 50) self.proposalBox.setColumnWidth(2, 50) @@ -74,7 +74,7 @@ def initLayout(self): self.proposalBox.setColumnWidth(7, 50) layout.addWidget(self.proposalBox) - ## -- ROW 3 + # -- ROW 3 row = QHBoxLayout() self.timeIconLabel = QLabel() self.timeIconLabel.setToolTip("Check to add a randomized time offset (positive or negative) to enhance privacy") @@ -121,7 +121,7 @@ def initLayout(self): row.addWidget(self.questionLabel) layout.addLayout(row) - ## -- ROW 4 + # -- ROW 4 row = QHBoxLayout() self.voteYes_btn = QPushButton("Vote YES") self.voteYes_btn.setToolTip("Vote YES on selected proposals") diff --git a/src/qt/gui_tabMNConf.py b/src/qt/gui_tabMNConf.py index 879b0ce..eff0efb 100644 --- a/src/qt/gui_tabMNConf.py +++ b/src/qt/gui_tabMNConf.py @@ -13,7 +13,7 @@ class TabMNConf_gui(QWidget): def __init__(self, masternode_alias=None, *args, **kwargs): QWidget.__init__(self) self.initConfigForm(masternode_alias) - ###-- Compose tab2 layout + # -- Compose tab2 layout mainVertical2 = QVBoxLayout() mainVertical2.setSpacing(10) mainVertical2.addWidget(self.configForm) @@ -65,11 +65,11 @@ def initConfigForm(self, masternode_alias=None): layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) layout.setContentsMargins(10, 20, 10, 10) layout.setSpacing(13) - ##--- ROW 1 + # --- ROW 1 self.edt_name = QLineEdit() self.edt_name.setToolTip("masternode Alias.\n-- example: My Masternode 1") layout.addRow(QLabel("Name"), self.edt_name) - ##--- ROW 2 + # --- ROW 2 line1 = QHBoxLayout() self.edt_masternodeIp = QLineEdit() self.edt_masternodeIp.setToolTip("masternode IP address\n-- example [IPv4] 88.172.23.1\n-- example [IPv6] 2001:db8:85a3::8a2e:370:7334") @@ -82,7 +82,7 @@ def initConfigForm(self, masternode_alias=None): self.edt_masternodePort.setFixedWidth(180) line1.addWidget(self.edt_masternodePort) layout.addRow(QLabel("IP Address"), line1) - ##--- ROW 3 + # --- ROW 3 self.edt_mnPrivKey = QLineEdit() self.edt_mnPrivKey.setToolTip("masternode private key \n-- output of 'masternode genkey' command") self.btn_genKey = QPushButton("Generate") @@ -90,13 +90,13 @@ def initConfigForm(self, masternode_alias=None): hBox2 = QHBoxLayout() hBox2.addWidget(self.edt_mnPrivKey) hBox2.addWidget(self.btn_genKey) - ## Testnet check + # Testnet check self.testnetCheck = QCheckBox() self.testnetCheck.setToolTip("check for TESTNET masternode setup") hBox2.addWidget(QLabel("testnet")) hBox2.addWidget(self.testnetCheck) layout.addRow(QLabel("MN Priv Key"), hBox2) - ##--- ROW 4/5 + # --- ROW 4/5 layout.addRow(QFrame()) layout.addRow(QLabel("Masternode Collateral")) hBox3 = QHBoxLayout() @@ -122,12 +122,12 @@ def initConfigForm(self, masternode_alias=None): hBox3.addWidget(QLabel("spath_id")) hBox3.addWidget(self.edt_spath) layout.addRow(QLabel("Account"), hBox3) - ##--- ROW 6 + # --- ROW 6 self.edt_pubKey = QLineEdit() self.edt_pubKey.setToolTip("public key corresponding to address") self.edt_pubKey.setEnabled(False) layout.addRow(QLabel("Public Key"), self.edt_pubKey) - ##--- ROW 7 + # --- ROW 7 hBox5 = QHBoxLayout() self.btn_findTxid = QPushButton("Lookup") self.btn_findTxid.setToolTip("look for txid and txidn on explorer") @@ -148,9 +148,9 @@ def initConfigForm(self, masternode_alias=None): self.edt_txidn.setEnabled(False) hBox5.addWidget(self.edt_txidn) layout.addRow(QLabel("Transaction"), hBox5) - ##--- Set Layout + # --- Set Layout self.configForm.setLayout(layout) - ##--- Footer + # --- Footer self.footer = QHBoxLayout() self.footer.addStretch(1) self.btn_cancelMNConf = QPushButton('Cancel') diff --git a/src/qt/gui_tabMain.py b/src/qt/gui_tabMain.py index 7f7cd4a..0bfceec 100644 --- a/src/qt/gui_tabMain.py +++ b/src/qt/gui_tabMain.py @@ -17,20 +17,20 @@ class TabMain_gui(QWidget): def __init__(self, caller, *args, **kwargs): QWidget.__init__(self) self.caller = caller - ###-- Initialize + # -- Initialize self.loadIcons() self.initGlobalButtons() self.initBody() - ###-- Compose layout + # -- Compose layout mainVertical = QVBoxLayout() mainVertical.setSpacing(10) mainVertical.addLayout(self.globalButtons) mainVertical.addWidget(self.body) - ###-- Set Layout + # -- Set Layout self.setLayout(mainVertical) def initGlobalButtons(self): - ###-- Global Buttons + # -- Global Buttons globalButtons = QHBoxLayout() self.button_startAll = QPushButton("Start All Masternodes") globalButtons.addWidget(self.button_startAll) @@ -41,7 +41,7 @@ def initGlobalButtons(self): self.globalButtons = globalButtons def initBody(self): - ###-- CENTRAL PART + # -- CENTRAL PART self.body = QGroupBox() self.body.setTitle("My Masternodes") # masternode list @@ -80,11 +80,11 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): else: mnRow.setToolTip("EXTERNAL MASTERNODE - Drag rows to re-order.") mnRowLayout = QHBoxLayout() - ##--- Led + # --- Led self.mnLed[name] = QLabel() self.mnLed[name].setPixmap(self.caller.ledGrayV_icon) mnRowLayout.addWidget(self.mnLed[name]) - ##--- Label & Balance + # --- Label & Balance self.mnLabel[name] = QLabel() if isHardware: self.mnLabel[name].setText("%s [%s]" % (name, ip)) @@ -95,24 +95,24 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): mnRowLayout.addWidget(self.mnBalance[name]) self.mnBalance[name].hide() mnRowLayout.addStretch(1) - ##--- Status Label + # --- Status Label self.mnStatusLabel[name] = QLabel() mnRowLayout.addWidget(self.mnStatusLabel[name]) self.mnStatusLabel[name].hide() - ##--- Rank bar + # --- Rank bar self.mnStatusProgress[name] = QProgressBar() self.mnStatusProgress[name].setMaximumHeight(15) self.mnStatusProgress[name].setMaximumWidth(40) self.mnStatusProgress[name].setTextVisible(False) mnRowLayout.addWidget(self.mnStatusProgress[name]) self.mnStatusProgress[name].hide() - ##--- Details button + # --- Details button self.btn_details[name] = QToolButton() self.btn_details[name].setIcon(self.details_icon) self.btn_details[name].setToolTip('Check status details of masternode "%s"' % name) mnRowLayout.addWidget(self.btn_details[name]) self.btn_details[name].hide() - ##--- Rewards button + # --- Rewards button self.btn_rewards[name] = QPushButton() self.btn_rewards[name].setToolTip('Transfer rewards from "%s"' % name) self.btn_rewards[name].setIcon(self.rewards_icon) @@ -121,7 +121,7 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): self.btn_rewards[name].setDisabled(True) self.btn_rewards[name].setToolTip("EXTERNAL MN: unable to move rewards with SPMT") mnRowLayout.addWidget(self.btn_rewards[name]) - ##--- Start button + # --- Start button self.btn_start[name] = QPushButton() self.btn_start[name].setToolTip('Start masternode "%s"' % name) self.btn_start[name].setIcon(self.startMN_icon) @@ -130,7 +130,7 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): self.btn_start[name].setDisabled(True) self.btn_start[name].setToolTip("EXTERNAL MN: unable to start with SPMT") mnRowLayout.addWidget(self.btn_start[name]) - ##--- Edit button + # --- Edit button self.btn_edit[name] = QPushButton() self.btn_edit[name].setToolTip('Edit masternode "%s"' % name) self.btn_edit[name].setIcon(self.editMN_icon) @@ -139,21 +139,21 @@ def insert_mn_list(self, name, ip, port, row=None, isHardware=True): self.btn_edit[name].setDisabled(True) self.btn_edit[name].setToolTip("EXTERNAL MN: to edit, delete entry and load new 'masternode.conf'") mnRowLayout.addWidget(self.btn_edit[name]) - ##--- Remove button + # --- Remove button self.btn_remove[name] = QPushButton() self.btn_remove[name].setToolTip('Delete masternode "%s"' % name) self.btn_remove[name].setIcon(self.removeMN_icon) self.btn_remove[name].alias = name mnRowLayout.addWidget(self.btn_remove[name]) - ##--- Three Dots + # --- Three Dots threeDots = QLabel() threeDots.setPixmap(self.threeDots_icon.scaledToHeight(20, Qt.SmoothTransformation)) mnRowLayout.addWidget(threeDots) - ##--- Set Row Layout + # --- Set Row Layout mnRow.setLayout(mnRowLayout) - ##--- Append Row + # --- Append Row self.current_mn[name] = QListWidgetItem() - #self.current_mn[name].setFlags(Qt.ItemIsSelectable) + # self.current_mn[name].setFlags(Qt.ItemIsSelectable) self.current_mn[name].setSizeHint(mnRow.sizeHint()) if row is not None: self.myList.insertItem(row, self.current_mn[name]) diff --git a/src/qt/gui_tabRewards.py b/src/qt/gui_tabRewards.py index 8ea0e49..b2e544b 100644 --- a/src/qt/gui_tabRewards.py +++ b/src/qt/gui_tabRewards.py @@ -34,7 +34,7 @@ def initRewardsForm(self): layout.setContentsMargins(10, 10, 10, 10) layout.setSpacing(13) layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) - ##--- ROW 1 + # --- ROW 1 hBox = QHBoxLayout() self.mnSelect = QComboBox() self.mnSelect.setToolTip("Select Masternode") @@ -55,7 +55,7 @@ def initRewardsForm(self): self.btn_toggleCollateral = QPushButton("Show Collateral") hBox.addWidget(self.btn_toggleCollateral) layout.addRow(QLabel("Masternode"), hBox) - ## --- ROW 2: REWARDS + # --- ROW 2: REWARDS self.rewardsList = QVBoxLayout() self.rewardsList.statusLabel = QLabel() self.rewardsList.statusLabel.setMinimumWidth(116) @@ -63,7 +63,7 @@ def initRewardsForm(self): self.rewardsList.addWidget(self.rewardsList.statusLabel) self.rewardsList.box = QTableWidget() self.rewardsList.box.setMinimumHeight(140) - #self.rewardsList.box.setMaximumHeight(140) + # self.rewardsList.box.setMaximumHeight(140) self.rewardsList.box.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.rewardsList.box.setSelectionMode(QAbstractItemView.MultiSelection) self.rewardsList.box.setSelectionBehavior(QAbstractItemView.SelectRows) @@ -91,7 +91,7 @@ def initRewardsForm(self): item = QTableWidgetItem() self.rewardsList.addWidget(self.rewardsList.box) layout.addRow(self.rewardsList) - ##--- ROW 3 + # --- ROW 3 hBox2 = QHBoxLayout() self.btn_selectAllRewards = QPushButton("Select All") self.btn_selectAllRewards.setToolTip("Select all available UTXOs") @@ -107,7 +107,7 @@ def initRewardsForm(self): hBox2.addWidget(self.selectedRewardsLine) hBox2.addStretch(1) layout.addRow(hBox2) - ##--- ROW 4 + # --- ROW 4 hBox3 = QHBoxLayout() self.destinationLine = QLineEdit() self.destinationLine.setToolTip("PIVX address to transfer rewards to") @@ -123,7 +123,7 @@ def initRewardsForm(self): self.btn_sendRewards = QPushButton("Send") hBox3.addWidget(self.btn_sendRewards) layout.addRow(QLabel("Destination Address"), hBox3) - ##--- ROW 5 + # --- ROW 5 hBox4 = QHBoxLayout() hBox4.addStretch(1) self.loadingLine = QLabel("Preparing TX. Completed: ") @@ -136,9 +136,9 @@ def initRewardsForm(self): self.loadingLine.hide() self.loadingLinePercent.hide() layout.addRow(hBox4) - #--- Set Layout + # --- Set Layout self.rewardsForm.setLayout(layout) - #--- ROW 5 + # --- ROW 5 self.btn_Cancel = QPushButton("Clear/Reload") def resetStatusLabel(self, message=None): diff --git a/src/tabGovernance.py b/src/tabGovernance.py index 08da8d6..21dc9e4 100644 --- a/src/tabGovernance.py +++ b/src/tabGovernance.py @@ -32,7 +32,7 @@ def __init__(self, caller): self.successVotes = 0 self.failedVotes = 0 - ##--- Initialize GUI + # Initialize GUI self.ui = TabGovernance_gui(caller) self.updateSelectedMNlabel() self.caller.tabGovernance = self.ui diff --git a/src/tabRewards.py b/src/tabRewards.py index a01b49c..4928afe 100644 --- a/src/tabRewards.py +++ b/src/tabRewards.py @@ -26,16 +26,16 @@ class TabRewards(): def __init__(self, caller): self.caller = caller - ##--- Lock for loading UTXO thread + # --- Lock for loading UTXO thread self.runInThread = ThreadFuns.runInThread self.Lock = threading.Lock() - ##--- Initialize Selection + # --- Initialize Selection self.selectedRewards = None self.feePerKb = MINIMUM_FEE self.suggestedFee = MINIMUM_FEE - ##--- Initialize GUI + # --- Initialize GUI self.ui = TabRewards_gui(caller.imgDir) self.caller.tabRewards = self.ui diff --git a/src/tests/testHwDeviceMethods.py b/src/tests/testHwDeviceMethods.py index 1075a6d..12612fb 100644 --- a/src/tests/testHwDeviceMethods.py +++ b/src/tests/testHwDeviceMethods.py @@ -115,7 +115,7 @@ def test_signature(self): print("sig = %s\naddress=%s" % (signature, pivx_address)) self.assertTrue(result) -## ----------------------------------------------------------------------------------- + # ----------------------------------------------------------------------------------- # from: # -- hwdevice.signMess # -- hwdevice.signMessSign From 0a22da23a507553edccbbae7d8bdd98e2a0bf278 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:20:04 -0800 Subject: [PATCH 03/16] Clean up white spacing per PEP8 --- spmt.py | 2 +- src/constants.py | 8 +-- src/database.py | 8 +-- src/ledgerClient.py | 2 +- src/mainWindow.py | 25 +++++----- src/masternode.py | 8 +-- src/misc.py | 36 +++++++------- src/pivx_b58.py | 4 +- src/pivx_hashlib.py | 2 +- src/proposals.py | 4 +- src/qt/dlg_budgetProjection.py | 4 +- src/qt/dlg_configureRPCservers.py | 22 ++++----- src/qt/dlg_findCollTx.py | 5 +- src/qt/dlg_pinMatrix.py | 4 +- src/qt/dlg_proposalDetails.py | 2 +- src/qt/dlg_selectMNs.py | 2 +- src/qt/dlg_signmessage.py | 4 +- src/qt/dlg_sweepAll.py | 6 +-- src/qt/gui_tabGovernance.py | 4 +- src/qt/gui_tabMNConf.py | 12 ++--- src/qt/gui_tabRewards.py | 2 +- src/spmtApp.py | 2 +- src/tabGovernance.py | 16 +++--- src/tabMNConf.py | 4 +- src/tabMain.py | 21 +++++--- src/tabRewards.py | 20 ++++---- src/tests/testHwDeviceMethods.py | 28 +++++------ src/tests/testMasternodeMethods.py | 8 +-- src/tests/testPivx_b58Methods.py | 2 +- src/threads.py | 79 +++++++++++++++--------------- src/trezorClient.py | 4 +- src/utils.py | 12 ++--- src/watchdogThreads.py | 6 +-- 33 files changed, 187 insertions(+), 181 deletions(-) diff --git a/spmt.py b/spmt.py index c845ccd..ecf5cf5 100644 --- a/spmt.py +++ b/spmt.py @@ -46,7 +46,7 @@ from PyQt5.Qt import Qt, QPixmap, QSplashScreen, QProgressBar, QColor, QPalette, QLabel from misc import updateSplash - from spmtApp import App + from spmtApp import App # Create App app = QApplication(sys.argv) diff --git a/src/constants.py b/src/constants.py index 6754374..091b8bf 100644 --- a/src/constants.py +++ b/src/constants.py @@ -12,14 +12,14 @@ MPATH_LEDGER = "44'/77'/" MPATH_TREZOR = "44'/119'/" MPATH_TESTNET = "44'/1'/" -WIF_PREFIX = 212 # 212 = d4 +WIF_PREFIX = 212 # 212 = d4 MAGIC_BYTE = 30 STAKE_MAGIC_BYTE = 63 TESTNET_WIF_PREFIX = 239 TESTNET_MAGIC_BYTE = 139 TESTNET_STAKE_MAGIC_BYTE = 73 DEFAULT_PROTOCOL_VERSION = 70915 -MINIMUM_FEE = 0.0001 # minimum PIV/kB +MINIMUM_FEE = 0.0001 # minimum PIV/kB starting_width = 933 starting_height = 666 APPDATA_DIRNAME = ".SecurePivxMasternodeTool" @@ -48,7 +48,7 @@ def NewSigsActive(nHeight, fTestnet=False): "isHardware": True, "hwAcc": 0, "collateral": {} - } +} DefaultCache = { "lastAddress": "", @@ -66,7 +66,7 @@ def NewSigsActive(nHeight, fTestnet=False): "selectedRPC_index": 0, "MN_count": 1, "isTestnetRPC": False - } +} trusted_RPC_Servers = [ ["https", "amsterdam.randomzebra.party:8080", "spmtUser_ams", "WUss6sr8956S5Paex254"], diff --git a/src/database.py b/src/database.py index 7720467..084e1b8 100644 --- a/src/database.py +++ b/src/database.py @@ -186,7 +186,7 @@ def initTable_RPC(self, cursor): General methods ''' - def clearTable(self, table_name): + def clearTable(self, table_name): printDbg("DB: Clearing table %s..." % table_name) cleared_RPC = False try: @@ -558,7 +558,7 @@ def deleteRawTx(self, tx_hash): logging.debug("DB: Deleting rawtx for %s" % tx_hash) try: cursor = self.getCursor() - cursor.execute("DELETE FROM RAWTXES WHERE tx_hash = ?", (tx_hash, )) + cursor.execute("DELETE FROM RAWTXES WHERE tx_hash = ?", (tx_hash,)) except Exception as e: err_msg = 'error deleting rawtx from DB' @@ -572,7 +572,7 @@ def getRawTx(self, tx_hash): cursor = self.getCursor() cursor.execute("SELECT * FROM RAWTXES" - " WHERE tx_hash = ?", (tx_hash, )) + " WHERE tx_hash = ?", (tx_hash,)) rows = cursor.fetchall() except Exception as e: @@ -593,7 +593,7 @@ def clearRawTxes(self, minTime): printDbg("Pruning table RAWTXES") try: cursor = self.getCursor() - cursor.execute("DELETE FROM RAWTXES WHERE lastfetch < ?", (minTime, )) + cursor.execute("DELETE FROM RAWTXES WHERE lastfetch < ?", (minTime,)) except Exception as e: err_msg = 'error deleting rawtx from DB' diff --git a/src/ledgerClient.py b/src/ledgerClient.py index 81703a5..b0951c3 100644 --- a/src/ledgerClient.py +++ b/src/ledgerClient.py @@ -269,7 +269,7 @@ def signMess(self, caller, hwpath, message, isTestnet=False): printOK('Signing Message') self.mBox = QMessageBox(caller) messageText = "Check display of your hardware device\n\n- message hash:\n\n%s\n\n-path:\t%s\n" % ( - message_sha, path) + message_sha, path) self.mBox.setText(messageText) self.mBox.setIconPixmap(caller.tabMain.ledgerImg.scaledToHeight(200, Qt.SmoothTransformation)) self.mBox.setWindowTitle("CHECK YOUR LEDGER") diff --git a/src/mainWindow.py b/src/mainWindow.py index c2b55fb..8eb3224 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -125,8 +125,8 @@ def __init__(self, parent, masternode_list, imgDir): self.splitter = QSplitter(Qt.Vertical) self.splitter.addWidget(self.tabs) self.splitter.addWidget(self.console) - self.splitter.setStretchFactor(0,0) - self.splitter.setStretchFactor(1,1) + self.splitter.setStretchFactor(0, 0) + self.splitter.setStretchFactor(1, 1) self.layout.addWidget(self.splitter) # -- Set Layout @@ -188,7 +188,7 @@ def connButtons(self): def getRPCserver(self): itemData = self.header.rpcClientsBox.itemData(self.header.rpcClientsBox.currentIndex()) - rpc_index = self.header.rpcClientsBox.currentIndex() + rpc_index = self.header.rpcClientsBox.currentIndex() rpc_protocol = itemData["protocol"] rpc_host = itemData["host"] rpc_user = itemData["user"] @@ -286,7 +286,7 @@ def loadMNConf(self, fileName): final_message = "%d External Masternodes " % new_nodes final_message += "added to the list." if new_nodes > 0: - final_message += "
" + str([x['name'] for x in new_masternodes]) + ". " + final_message += "
" + str([x['name'] for x in new_masternodes]) + ". " printOK(final_message) if len(skip_masternodes) > 0: final_message = "Following entries skipped due to duplicate names:
" @@ -299,7 +299,7 @@ def onCheckHw(self): self.showHWstatus() def onCheckRpc(self): - self.runInThread(self.updateRPCstatus, (True,),) + self.runInThread(self.updateRPCstatus, (True,), ) def onCheckVersion(self): printDbg("Checking SPMT version...") @@ -312,8 +312,9 @@ def checkVersion(self, ctrl): remote_version = self.gitVersion.split('.') if (remote_version[0] > local_version[0]) or \ - (remote_version[0] == local_version[0] and remote_version[1] > local_version[1]) or \ - (remote_version[0] == local_version[0] and remote_version[1] == local_version[1] and remote_version[2] > local_version[2]): + (remote_version[0] == local_version[0] and remote_version[1] > local_version[1]) or \ + (remote_version[0] == local_version[0] and remote_version[1] == local_version[1] and remote_version[2] > + local_version[2]): self.versionMess = 'New Version Available: %s ' % (self.gitVersion) self.versionMess += '(download)' else: @@ -329,13 +330,13 @@ def onChangeSelectedHW(self, i): self.clearHWstatus() # Persist setting - self.parent.cache['selectedHW_index'] = persistCacheSetting('cache_HWindex',i) + self.parent.cache['selectedHW_index'] = persistCacheSetting('cache_HWindex', i) def onChangeSelectedRPC(self, i): # Don't update when we are clearing the box if not self.updatingRPCbox: # persist setting - self.parent.cache['selectedRPC_index'] = persistCacheSetting('cache_RPCindex',i) + self.parent.cache['selectedRPC_index'] = persistCacheSetting('cache_RPCindex', i) self.runInThread(self.updateRPCstatus, (True,), ) def onCleanConsole(self): @@ -345,7 +346,7 @@ def onSaveConsole(self): timestamp = strftime('%Y-%m-%d_%H-%M-%S', gmtime(now())) options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog - fileName, _ = QFileDialog.getSaveFileName(self,"Save Logs to file","SPMT_Logs_%s.txt" % timestamp,"All Files (*);; Text Files (*.txt)", options=options) + fileName, _ = QFileDialog.getSaveFileName(self, "Save Logs to file", "SPMT_Logs_%s.txt" % timestamp, "All Files (*);; Text Files (*.txt)", options=options) try: if fileName: printOK("Saving logs to %s" % fileName) @@ -522,8 +523,8 @@ def updateRPCstatus(self, ctrl, fDebug=False): return rpcResponseTime = None - if r_time1 is not None and r_time2 !=0: - rpcResponseTime = round((r_time1+r_time2)/2, 3) + if r_time1 is not None and r_time2 != 0: + rpcResponseTime = round((r_time1 + r_time2) / 2, 3) # Do not update status if the user has selected a different server since the start of updateRPCStatus() if rpc_index != self.header.rpcClientsBox.currentIndex(): diff --git a/src/masternode.py b/src/masternode.py index 02d2bc8..137e644 100644 --- a/src/masternode.py +++ b/src/masternode.py @@ -28,7 +28,7 @@ class Masternode(QObject): # signal: sig (thread) is done - emitted by finalizeStartMessage sigdone = pyqtSignal(str) - def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral = {}, isTestnet=False, *args, **kwargs): + def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral={}, isTestnet=False, *args, **kwargs): QObject.__init__(self, *args, **kwargs) self.tab_main = tab_main self.name = name @@ -107,7 +107,7 @@ def signature2(self, block_hash): mnping = self.getPingMessage(fNewSigs, block_hash) if fNewSigs: printDbg("mnping: %s" % mnping.hex()) - sig2 = ecdsa_sign_bin(mnping, self.mnWIF) # local + sig2 = ecdsa_sign_bin(mnping, self.mnWIF) # local else: printDbg("mnping: %s" % mnping) sig2 = ecdsa_sign(mnping, self.mnWIF) @@ -143,8 +143,8 @@ def finalizeStartMessage(self, text): vinsig = num_to_varint(len(scriptSig) / 2).hex() + bytes.fromhex(scriptSig)[::-1].hex() vinseq = sequence.to_bytes(4, byteorder='big')[::-1].hex() ipv6map = ipmap(self.ip, self.port) - collateral_in = num_to_varint(len(self.collateral['pubKey'])/2).hex() + self.collateral['pubKey'] - delegate_in = num_to_varint(len(self.mnPubKey)/2).hex() + self.mnPubKey + collateral_in = num_to_varint(len(self.collateral['pubKey']) / 2).hex() + self.collateral['pubKey'] + delegate_in = num_to_varint(len(self.mnPubKey) / 2).hex() + self.mnPubKey except Exception as e: err_msg = "error in startMessage" diff --git a/src/misc.py b/src/misc.py index f62132c..cdd608e 100644 --- a/src/misc.py +++ b/src/misc.py @@ -22,7 +22,7 @@ "warn": QMessageBox.Warning, "crit": QMessageBox.Critical, "quest": QMessageBox.Question - } +} def add_defaultKeys_to_dict(dictObj, defaultObj): @@ -73,10 +73,10 @@ def checkRPCstring(urlstring, action_msg="Malformed credentials"): if o.netloc is None or o.netloc == '': raise Exception("Malformed host network location part.") if o.port is None or o.port == '': - raise Exception("Wrong IP port number") + raise Exception("Wrong IP port number") if o.username is None: raise Exception("Malformed username") - if o.password is None: + if o.password is None: raise Exception("Malformed password") return True @@ -163,7 +163,7 @@ def clean_v4_migration(wnd): def clean_for_html(text): if text is None: return "" - return text.replace("<", "{").replace(">","}") + return text.replace("<", "{").replace(">", "}") def clear_screen(): @@ -474,17 +474,17 @@ def saveCacheSettings(cache): def sec_to_time(seconds): - days = seconds//86400 - seconds -= days*86400 - hrs = seconds//3600 - seconds -= hrs*3600 - mins = seconds//60 - seconds -= mins*60 + days = seconds // 86400 + seconds -= days * 86400 + hrs = seconds // 3600 + seconds -= hrs * 3600 + mins = seconds // 60 + seconds -= mins * 60 return "{} days, {} hrs, {} mins, {} secs".format(days, hrs, mins, seconds) def splitString(text, n): - arr = [text[i:i+n] for i in range(0, len(text), n)] + arr = [text[i:i + n] for i in range(0, len(text), n)] return '\n'.join(arr) @@ -493,28 +493,28 @@ def timeThis(function, *args): start = time.clock() val = function(*args) end = time.clock() - return val, (end-start) + return val, (end - start) except Exception: return None, None def updateSplash(label, i): - if i==10: + if i == 10: progressText = "Loading configuration data..." label.setText(progressText) - elif i==40: + elif i == 40: progressText = "Opening database..." label.setText(progressText) - elif i==50: + elif i == 50: progressText = "Creating user interface..." label.setText(progressText) - elif i==70: + elif i == 70: progressText = "Releasing the watchdogs..." label.setText(progressText) - elif i==90: + elif i == 90: progressText = "SPMT ready" label.setText(progressText) - elif i==99: + elif i == 99: time.sleep(0.1) diff --git a/src/pivx_b58.py b/src/pivx_b58.py index ebc9522..5f11311 100644 --- a/src/pivx_b58.py +++ b/src/pivx_b58.py @@ -21,7 +21,7 @@ def b58encode(v): """ long_value = 0 for (i, c) in enumerate(v[::-1]): - long_value += (256**i) * _bord(c) + long_value += (256 ** i) * _bord(c) result = '' while long_value >= __b58base: @@ -47,7 +47,7 @@ def b58decode(v, length=None): """ long_value = 0 for (i, c) in enumerate(v[::-1]): - long_value += __b58chars.find(c) * (__b58base**i) + long_value += __b58chars.find(c) * (__b58base ** i) result = bytes() while long_value >= 256: diff --git a/src/pivx_hashlib.py b/src/pivx_hashlib.py index 7d49592..efd1db4 100644 --- a/src/pivx_hashlib.py +++ b/src/pivx_hashlib.py @@ -67,7 +67,7 @@ def wif_to_privkey(string): check = double_sha256(vs)[0:4] if (wifversion == WIF_PREFIX.to_bytes(1, byteorder='big').hex() and checksum == check.hex()) \ - or (wifversion == TESTNET_WIF_PREFIX.to_bytes(1, byteorder='big').hex() and checksum == check.hex()): + or (wifversion == TESTNET_WIF_PREFIX.to_bytes(1, byteorder='big').hex() and checksum == check.hex()): if wif_compressed: privkey = pvkeyencoded[2:-10] diff --git a/src/proposals.py b/src/proposals.py index a4a44aa..ebd9ea0 100644 --- a/src/proposals.py +++ b/src/proposals.py @@ -8,7 +8,7 @@ "YES": 1, "ABSTAIN": 0, "NO": -1 - } +} vote_type = { "1": "YES", @@ -21,7 +21,7 @@ class Proposal(): def __init__(self, name, URL, Hash, FeeHash, BlockStart, BlockEnd, TotalPayCount, RemainingPayCount, PayMentAddress, Yeas, Nays, Abstains, TotalPayment, MonthlyPayment): self.name = name - self.URL = URL if URL.startswith('http') or URL.startswith('https') else 'http://'+URL + self.URL = URL if URL.startswith('http') or URL.startswith('https') else 'http://' + URL self.Hash = Hash self.FeeHash = FeeHash self.BlockStart = int(BlockStart) diff --git a/src/qt/dlg_budgetProjection.py b/src/qt/dlg_budgetProjection.py index 17ada1f..e6b537a 100644 --- a/src/qt/dlg_budgetProjection.py +++ b/src/qt/dlg_budgetProjection.py @@ -36,12 +36,12 @@ def displayBudgetProjection(self): blocks_to_SB = self.next_superBlock - self.main_wnd.caller.rpcLastBlock self.ui.nextSuperBlock_label.setText("%s" % str(self.next_superBlock)) - timeToNextSB = "%s" % sec_to_time(60*blocks_to_SB) + timeToNextSB = "%s" % sec_to_time(60 * blocks_to_SB) self.ui.timeToNextSB_label.setText(timeToNextSB) total = self.projection[-1].get('Total_Allotted') total_label = "%s PIV" % str(total) self.ui.allottedBudget_label.setText(total_label) - self.ui.remainingBudget_label.setText("%s PIV" % str(round(43200.0-total,8))) + self.ui.remainingBudget_label.setText("%s PIV" % str(round(43200.0 - total, 8))) self.ui.passingProposals_label.setText("%s" % str(len(self.projection))) def item(value): diff --git a/src/qt/dlg_configureRPCservers.py b/src/qt/dlg_configureRPCservers.py index d17c72e..4fd0f50 100644 --- a/src/qt/dlg_configureRPCservers.py +++ b/src/qt/dlg_configureRPCservers.py @@ -4,8 +4,8 @@ # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. -from PyQt5.QtWidgets import QDialog, QHBoxLayout, QVBoxLayout, QLabel,\ - QListWidget, QFrame, QFormLayout, QComboBox, QLineEdit, QListWidgetItem,\ +from PyQt5.QtWidgets import QDialog, QHBoxLayout, QVBoxLayout, QLabel, \ + QListWidget, QFrame, QFormLayout, QComboBox, QLineEdit, QListWidgetItem, \ QWidget, QPushButton, QMessageBox from misc import myPopUp, checkRPCstring @@ -85,7 +85,7 @@ def loadEditFrame(self, index): server = self.main_wnd.mainWindow.rpcServersList[index] self.ui.user_edt.setText(server['user']) self.ui.passwd_edt.setText(server['password']) - if server['protocol'] == 'https': + if server['protocol'] == 'https': self.ui.protocol_select.setCurrentIndex(1) else: self.ui.protocol_select.setCurrentIndex(0) @@ -138,7 +138,7 @@ def onSave(self): passwd = self.ui.passwd_edt.text() # Check malformed URL url_string = "%s://%s:%s@%s" % (protocol, user, passwd, host) - if checkRPCstring(url_string): + if checkRPCstring(url_string): if self.changing_index is None: # Save new entry in DB. self.main_wnd.db.addRPCServer(protocol, host, user, passwd) @@ -150,8 +150,8 @@ def onSave(self): clients = self.main_wnd.mainWindow.header.rpcClientsBox data = clients.itemData(clients.currentIndex()) if data.get('id') == id and data.get('isCustom'): - ThreadFuns.runInThread(self.main_wnd.mainWindow.updateRPCstatus, (True,),) - + ThreadFuns.runInThread(self.main_wnd.mainWindow.updateRPCstatus, (True,), ) + # call onCancel self.onCancel() @@ -159,19 +159,19 @@ def onSave(self): class Ui_ConfigureRPCserversDlg(object): def setupUi(self, ConfigureRPCserversDlg): ConfigureRPCserversDlg.setModal(True) - ## -- Layout - self.layout = QVBoxLayout(ConfigureRPCserversDlg) + # -- Layout + self.layout = QVBoxLayout(ConfigureRPCserversDlg) self.layout.setSpacing(10) # -- Servers List self.serversBox = QListWidget() self.layout.addWidget(self.serversBox) - ## -- 'Add Server' button - self.addServer_btn = QPushButton("Add RPC Server") + # -- 'Add Server' button + self.addServer_btn = QPushButton("Add RPC Server") self.layout.addWidget(self.addServer_btn) # -- 'Close' button hBox = QHBoxLayout() hBox.addStretch(1) - self.close_btn = QPushButton("Close") + self.close_btn = QPushButton("Close") hBox.addWidget(self.close_btn) self.layout.addLayout(hBox) # -- Edit section diff --git a/src/qt/dlg_findCollTx.py b/src/qt/dlg_findCollTx.py index efaee34..1ffea6b 100644 --- a/src/qt/dlg_findCollTx.py +++ b/src/qt/dlg_findCollTx.py @@ -44,7 +44,7 @@ def item(value): self.tableW.setRowCount(len(self.utxos)) for row, utxo in enumerate(self.utxos): - pivxAmount = round(int(utxo.get('satoshis', 0))/1e8, 8) + pivxAmount = round(int(utxo.get('satoshis', 0)) / 1e8, 8) self.tableW.setItem(row, 0, item(str(pivxAmount))) self.tableW.setItem(row, 1, item(str(utxo['confirmations']))) self.tableW.setItem(row, 2, item(utxo.get('txid', None))) @@ -67,7 +67,8 @@ def load_utxos_thread(self, ctrl): try: self.blockCount = self.mainTab.caller.rpcClient.getBlockCount() utxos = self.mainTab.caller.apiClient.getAddressUtxos(self.pivx_addr) - self.utxos = [utxo for utxo in utxos if round(int(utxo.get('satoshis', 0))/1e8, 8) == 10000.00000000] + self.utxos = [utxo for utxo in utxos if + round(int(utxo.get('satoshis', 0)) / 1e8, 8) == 10000.00000000] except Exception as e: errorMsg = 'Error occurred while calling getaddressutxos method: ' + str(e) diff --git a/src/qt/dlg_pinMatrix.py b/src/qt/dlg_pinMatrix.py index e62caba..68621fe 100644 --- a/src/qt/dlg_pinMatrix.py +++ b/src/qt/dlg_pinMatrix.py @@ -50,7 +50,7 @@ def setupUI(self): Ui_pinMatrixDlg.setupUi(self, self) # Connect buttons matrix for i in range(9): - self.btn[i].clicked.connect(lambda _, b=i+1: self.btn_clicked(str(b))) + self.btn[i].clicked.connect(lambda _, b=i + 1: self.btn_clicked(str(b))) # Connect del/ok/cancel self.btn_del.clicked.connect(self.onDel) self.btn_ok.clicked.connect(self.onOK) @@ -85,7 +85,7 @@ def setupUi(self, PinMatrixDlg): """ self.btn = [] for i in range(9): - btn_lab = '\u2022' if PinMatrixDlg.hideBtns else str(i+1) + btn_lab = '\u2022' if PinMatrixDlg.hideBtns else str(i + 1) btn = QPushButton(btn_lab) self.btn.append(btn) diff --git a/src/qt/dlg_proposalDetails.py b/src/qt/dlg_proposalDetails.py index 4ba3620..dee41d1 100644 --- a/src/qt/dlg_proposalDetails.py +++ b/src/qt/dlg_proposalDetails.py @@ -7,7 +7,7 @@ from time import strftime, gmtime from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QDialog, QFormLayout, QVBoxLayout, QLabel, QLineEdit,\ +from PyQt5.QtWidgets import QDialog, QFormLayout, QVBoxLayout, QLabel, QLineEdit, \ QScrollArea, QFrame, QPushButton diff --git a/src/qt/dlg_selectMNs.py b/src/qt/dlg_selectMNs.py index 1592a04..b38387e 100644 --- a/src/qt/dlg_selectMNs.py +++ b/src/qt/dlg_selectMNs.py @@ -5,7 +5,7 @@ # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QDialog, QTableWidget, QVBoxLayout, QAbstractItemView, QHeaderView,\ +from PyQt5.QtWidgets import QDialog, QTableWidget, QVBoxLayout, QAbstractItemView, QHeaderView, \ QTableWidgetItem, QLabel, QHBoxLayout, QPushButton from misc import persistCacheSetting diff --git a/src/qt/dlg_signmessage.py b/src/qt/dlg_signmessage.py index 9f39496..c2411e0 100644 --- a/src/qt/dlg_signmessage.py +++ b/src/qt/dlg_signmessage.py @@ -271,8 +271,8 @@ def setSignEnabled(self, enabled): self.ui.hiddenLine.setVisible(not enabled) tooltip = "" if not enabled: - tooltip = "You need to find the address PK in your hardware device first.\n"\ - "Insert the account number (usually 0) and either a PIVX address\n"\ + tooltip = "You need to find the address PK in your hardware device first.\n" \ + "Insert the account number (usually 0) and either a PIVX address\n" \ "or the spath_id (address number) and click 'Search HW'." self.ui.addressLabel.setText("") self.ui.signBtn.setToolTip(tooltip) diff --git a/src/qt/dlg_sweepAll.py b/src/qt/dlg_sweepAll.py index c2cf9d9..dc24d83 100644 --- a/src/qt/dlg_sweepAll.py +++ b/src/qt/dlg_sweepAll.py @@ -74,7 +74,7 @@ def display_utxos(self): if r['mn_name'] == x['name'] # this mn's UTXOs and r['txid'] != mn['collateral'].get('txid') # except the collateral and not (r['coinstake'] and r['confirmations'] < required_confs)] # and immature rewards - x['total_rewards'] = round(sum([reward['satoshis'] for reward in x['utxos']])/1e8, 8) + x['total_rewards'] = round(sum([reward['satoshis'] for reward in x['utxos']]) / 1e8, 8) self.rewardsArray.append(x) # update fee per Kb @@ -111,11 +111,11 @@ def item(value): self.ui.tableW.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) total = sum([float(mnode['total_rewards']) for mnode in self.rewardsArray]) - self.ui.totalLine.setText("%s PIV" % str(round(total,8))) + self.ui.totalLine.setText("%s PIV" % str(round(total, 8))) self.ui.noOfUtxosLine.setText("%s" % str(numOfInputs)) # update fee - estimatedTxSize = (44+numOfInputs*148)*1.0 / 1000 # kB + estimatedTxSize = (44 + numOfInputs * 148) * 1.0 / 1000 # kB self.suggestedFee = round(self.feePerKb * estimatedTxSize, 8) self.updateFee() diff --git a/src/qt/gui_tabGovernance.py b/src/qt/gui_tabGovernance.py index e0bd43e..23f846d 100644 --- a/src/qt/gui_tabGovernance.py +++ b/src/qt/gui_tabGovernance.py @@ -8,8 +8,8 @@ from PyQt5.Qt import QPixmap, QIcon from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QWidget, QVBoxLayout, QAbstractItemView, QHeaderView,\ - QTableWidget, QTableWidgetItem, QHBoxLayout, QPushButton, QCheckBox, QLabel, QProgressBar,\ +from PyQt5.QtWidgets import QWidget, QVBoxLayout, QAbstractItemView, QHeaderView, \ + QTableWidget, QTableWidgetItem, QHBoxLayout, QPushButton, QCheckBox, QLabel, QProgressBar, \ QSpinBox, QScrollArea, QDialog diff --git a/src/qt/gui_tabMNConf.py b/src/qt/gui_tabMNConf.py index eff0efb..c9f9e49 100644 --- a/src/qt/gui_tabMNConf.py +++ b/src/qt/gui_tabMNConf.py @@ -5,7 +5,7 @@ # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. from PyQt5.Qt import QLabel, QFormLayout, QSpinBox -from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, QCheckBox,\ +from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, QCheckBox, \ QFrame, QLineEdit @@ -16,12 +16,12 @@ def __init__(self, masternode_alias=None, *args, **kwargs): # -- Compose tab2 layout mainVertical2 = QVBoxLayout() mainVertical2.setSpacing(10) - mainVertical2.addWidget(self.configForm) + mainVertical2.addWidget(self.configForm) vBox = QVBoxLayout() vBox.addStretch(1) mainVertical2.addLayout(vBox) mainVertical2.addLayout(self.footer) - self.setLayout(mainVertical2) + self.setLayout(mainVertical2) def clearConfigForm(self): self.testnetCheck.setChecked(False) @@ -52,7 +52,7 @@ def fillConfigForm(self, masternode): self.edt_pubKey.setText(masternode['collateral'].get('pubKey')) self.edt_txid.setText(masternode['collateral'].get('txid')) self.edt_txidn.setValue(masternode['collateral'].get('txidn')) - self.configForm.setTitle("Edit Masternode") + self.configForm.setTitle("Edit Masternode") def initConfigForm(self, masternode_alias=None): self.configForm = QGroupBox() @@ -103,7 +103,7 @@ def initConfigForm(self, masternode_alias=None): self.edt_hwAccount = QSpinBox() self.edt_hwAccount.setFixedWidth(50) self.edt_hwAccount.setToolTip("account number of the hardware wallet.\nIf unsure put 0") - self.edt_hwAccount.setValue(0) + self.edt_hwAccount.setValue(0) hBox3.addWidget(self.edt_hwAccount) hBox3.addWidget(QLabel("PIVX Address")) self.edt_address = QLineEdit() @@ -136,7 +136,7 @@ def initConfigForm(self, masternode_alias=None): self.btn_editTxid = QPushButton("Edit") self.btn_editTxid.setToolTip("edit txid and txidn manually") hBox5.addWidget(self.btn_editTxid) - hBox5.addWidget(QLabel("txid")) + hBox5.addWidget(QLabel("txid")) self.edt_txid = QLineEdit() self.edt_txid.setToolTip("txid for the collateral") self.edt_txid.setEnabled(False) diff --git a/src/qt/gui_tabRewards.py b/src/qt/gui_tabRewards.py index b2e544b..1445a1b 100644 --- a/src/qt/gui_tabRewards.py +++ b/src/qt/gui_tabRewards.py @@ -7,7 +7,7 @@ import os from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout,\ +from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, \ QProgressBar, QLineEdit, QComboBox, QLabel, QFormLayout, QDoubleSpinBox, QTableWidget, \ QTableWidgetItem, QAbstractItemView, QHeaderView, QCheckBox from PyQt5.Qt import QIcon diff --git a/src/spmtApp.py b/src/spmtApp.py index dba07e0..9c8f900 100644 --- a/src/spmtApp.py +++ b/src/spmtApp.py @@ -102,7 +102,7 @@ def initUI(self, masternode_list, imgDir): # Sort masternode list (by alias if no previous order set) if self.cache.get('mnList_order') != {} and ( - len(self.cache.get('mnList_order')) == len(masternode_list)): + len(self.cache.get('mnList_order')) == len(masternode_list)): try: masternode_list.sort(key=self.extract_order) except Exception as e: diff --git a/src/tabGovernance.py b/src/tabGovernance.py index 21dc9e4..7b09712 100644 --- a/src/tabGovernance.py +++ b/src/tabGovernance.py @@ -41,8 +41,8 @@ def __init__(self, caller): self.vote_codes = ["abstains", "yes", "no"] self.ui.refreshProposals_btn.clicked.connect(lambda: self.onRefreshProposals()) self.ui.toggleExpiring_btn.clicked.connect(lambda: self.onToggleExpiring()) - self.ui.selectMN_btn.clicked.connect(lambda: SelectMNs_dlg(self).exec_()) - self.ui.budgetProjection_btn.clicked.connect(lambda: BudgetProjection_dlg(self).exec_()) + self.ui.selectMN_btn.clicked.connect(lambda: SelectMNs_dlg(self).exec_()) + self.ui.budgetProjection_btn.clicked.connect(lambda: BudgetProjection_dlg(self).exec_()) self.ui.proposalBox.itemClicked.connect(lambda: self.updateSelection()) self.ui.voteYes_btn.clicked.connect(lambda: self.onVote(1)) self.ui.voteAbstain_btn.clicked.connect(lambda: self.onVote(0)) @@ -209,18 +209,18 @@ def getSelection(self): row = items[i].row() rows.add(row) rowsList = list(rows) - hashesList = [self.ui.proposalBox.item(row,1).text() for row in rowsList] + hashesList = [self.ui.proposalBox.item(row, 1).text() for row in rowsList] return [p for p in proposals if p.Hash in hashesList] def onRefreshProposals(self): self.ui.resetStatusLabel() - ThreadFuns.runInThread(self.loadProposals_thread, (),) + ThreadFuns.runInThread(self.loadProposals_thread, (), ) def onToggleExpiring(self): if self.ui.toggleExpiring_btn.text() == "Hide Expiring": # Hide expiring proposals for row in range(0, self.ui.proposalBox.rowCount()): - if self.ui.proposalBox.item(row,5).background() == Qt.yellow: + if self.ui.proposalBox.item(row, 5).background() == Qt.yellow: self.ui.proposalBox.hideRow(row) # Update button self.ui.toggleExpiring_btn.setToolTip("Show expiring proposals (yellow background) in list") @@ -229,7 +229,7 @@ def onToggleExpiring(self): else: # Show expiring proposals for row in range(0, self.ui.proposalBox.rowCount()): - if self.ui.proposalBox.item(row,5).background() == Qt.yellow: + if self.ui.proposalBox.item(row, 5).background() == Qt.yellow: self.ui.proposalBox.showRow(row) # Update button self.ui.toggleExpiring_btn.setToolTip("Hide expiring proposals (yellow background) from list") @@ -327,7 +327,7 @@ def vote_thread(self, ctrl, vote_code): try: # Get mnPrivKey - currNode = next(x for x in self.caller.masternode_list if x['name']==mn[1]) + currNode = next(x for x in self.caller.masternode_list if x['name'] == mn[1]) if currNode is None: printDbg("currNode not found for current voting masternode %s" % mn[1]) self.clear() @@ -340,7 +340,7 @@ def vote_thread(self, ctrl, vote_code): minuns_max = int(self.ui.randomDelayNeg_edt.value()) plus_max = int(self.ui.randomDelayPos_edt.value()) delay_secs = random.randint(-minuns_max, plus_max) - sig_time += delay_secs + sig_time += delay_secs # Print Debug line to console mess = "Processing '%s' vote on behalf of masternode [%s]" % (self.vote_codes[vote_code], mn[1]) diff --git a/src/tabMNConf.py b/src/tabMNConf.py index 4129067..b1aed42 100644 --- a/src/tabMNConf.py +++ b/src/tabMNConf.py @@ -70,7 +70,7 @@ def findSpath_done(self): self.findPubKey() else: - mess = "Scanned addresses %d to %d of HW account %d.
" % (starting_spath, starting_spath+spath_count-1, currHwAcc) + mess = "Scanned addresses %d to %d of HW account %d.
" % (starting_spath, starting_spath + spath_count - 1, currHwAcc) mess += "Unable to find the address %s.
Maybe it's on a different account.

" % currAddr mess += "Do you want to scan %d more addresses of account n.%d ?" % (spath_count, currHwAcc) ans = myPopUp(self.caller, "crit", 'SPMT - spath search', mess) @@ -178,7 +178,7 @@ def onGenerateMNkey(self): if self.ui.edt_mnPrivKey.text() != "": reply = myPopUp(self.caller, "warn", "GENERATE PRIV KEY", - "Are you sure?\nThis will overwrite current private key", QMessageBox.No) + "Are you sure?\nThis will overwrite current private key", QMessageBox.No) if reply == QMessageBox.No: return diff --git a/src/tabMain.py b/src/tabMain.py index e38ca01..d196175 100644 --- a/src/tabMain.py +++ b/src/tabMain.py @@ -84,7 +84,7 @@ def displayMNStatus(self, currMN): display_text += '%d/%d' % (position, total_count) self.ui.mnStatusProgress[masternode_alias].setRange(0, total_count) - self.ui.mnStatusProgress[masternode_alias].setValue(total_count-position) + self.ui.mnStatusProgress[masternode_alias].setValue(total_count - position) self.ui.mnStatusProgress[masternode_alias].show() else: self.ui.mnLed[masternode_alias].setPixmap(self.caller.ledRedV_icon) @@ -97,11 +97,13 @@ def displayMNStatus(self, currMN): def onCheckAllMN(self): if not self.caller.rpcConnected: - myPopUp_sb(self.caller, "crit", 'SPMT - hw device check', "RPC server must be connected to perform this action.") + myPopUp_sb(self.caller, "crit", 'SPMT - hw device check', + "RPC server must be connected to perform this action.") printDbg("Unable to connect: %s" % self.caller.rpcStatusMess) return if self.caller.masternode_list is None or self.caller.masternode_list == []: - myPopUp_sb(self.caller, "crit", 'SPMT - Check-All masternodes', "No masternode in list. Add masternodes first.") + myPopUp_sb(self.caller, "crit", 'SPMT - Check-All masternodes', + "No masternode in list. Add masternodes first.") return try: printDbg("Check-All pressed") @@ -144,7 +146,7 @@ def onRemoveMN(self, data=None): masternode_alias = target.alias reply = myPopUp(self.caller, "warn", 'Confirm REMOVE', - "Are you sure you want to remove\nmasternoode:'%s'" % masternode_alias, QMessageBox.No) + "Are you sure you want to remove\nmasternoode:'%s'" % masternode_alias, QMessageBox.No) if reply == QMessageBox.No: return @@ -173,12 +175,13 @@ def onStartAllMN(self): try: reply = myPopUp(self.caller, "quest", 'Confirm START', - "Are you sure you want to start ALL masternodes?", QMessageBox.Yes) + "Are you sure you want to start ALL masternodes?", QMessageBox.Yes) if reply == QMessageBox.Yes: mnList = [x for x in self.caller.masternode_list if x['isHardware']] for mn_conf in mnList: self.masternodeToStart = Masternode(self, mn_conf['name'], mn_conf['ip'], mn_conf['port'], - mn_conf['mnPrivKey'], mn_conf['hwAcc'], mn_conf['collateral'], mn_conf['isTestnet']) + mn_conf['mnPrivKey'], mn_conf['hwAcc'], mn_conf['collateral'], + mn_conf['isTestnet']) # connect signal self.masternodeToStart.sigdone.connect(self.sendBroadcast) self.mnToStartList.append(self.masternodeToStart) @@ -203,10 +206,12 @@ def onStartMN(self, data=None): for mn_conf in self.caller.masternode_list: if mn_conf['name'] == masternode_alias: reply = myPopUp(self.caller, QMessageBox.Question, 'Confirm START', - "Are you sure you want to start masternoode:\n'%s'?" % mn_conf['name'], QMessageBox.Yes) + "Are you sure you want to start masternoode:\n'%s'?" % mn_conf['name'], + QMessageBox.Yes) if reply == QMessageBox.Yes: self.masternodeToStart = Masternode(self, mn_conf['name'], mn_conf['ip'], mn_conf['port'], - mn_conf['mnPrivKey'], mn_conf['hwAcc'], mn_conf['collateral'], mn_conf['isTestnet']) + mn_conf['mnPrivKey'], mn_conf['hwAcc'], + mn_conf['collateral'], mn_conf['isTestnet']) # connect signal self.masternodeToStart.sigdone.connect(self.sendBroadcast) self.mnToStartList.append(self.masternodeToStart) diff --git a/src/tabRewards.py b/src/tabRewards.py index 4928afe..3840641 100644 --- a/src/tabRewards.py +++ b/src/tabRewards.py @@ -43,7 +43,7 @@ def __init__(self, caller): self.ui.destinationLine.setText(self.caller.parent.cache.get("lastAddress")) # init first selected MN - self.loadMnSelect(True) # loads masternodes list in MnSelect and display utxos + self.loadMnSelect(True) # loads masternodes list in MnSelect and display utxos self.updateFee() # Connect GUI buttons @@ -88,7 +88,7 @@ def item(value): # Insert items for row, utxo in enumerate(rewards): txId = utxo.get('txid', None) - pivxAmount = round(int(utxo.get('satoshis', 0))/1e8, 8) + pivxAmount = round(int(utxo.get('satoshis', 0)) / 1e8, 8) self.ui.rewardsList.box.setItem(row, 0, item(str(pivxAmount))) self.ui.rewardsList.box.setItem(row, 1, item(str(utxo.get('confirmations', None)))) self.ui.rewardsList.box.setItem(row, 2, item(txId)) @@ -101,7 +101,7 @@ def item(value): # MARK COLLATERAL UTXO if txId == self.curr_txid: - for i in range(0,4): + for i in range(0, 4): self.ui.rewardsList.box.item(row, i).setFont(QFont("Arial", 9, QFont.Bold)) self.ui.rewardsList.box.collateralRow = row @@ -109,7 +109,7 @@ def item(value): if utxo['coinstake']: required = 16 if self.caller.isTestnetRPC else 101 if utxo['confirmations'] < required: - for i in range(0,4): + for i in range(0, 4): self.ui.rewardsList.box.item(row, i).setFlags(Qt.NoItemFlags) ttip = self.ui.rewardsList.box.item(row, i).toolTip() self.ui.rewardsList.box.item(row, i).setToolTip( @@ -118,7 +118,7 @@ def item(value): self.ui.rewardsList.box.resizeColumnsToContents() if self.ui.rewardsList.box.collateralRow is not None: - self.ui.rewardsList.box.hideRow(self.ui.rewardsList.box.collateralRow) + self.ui.rewardsList.box.hideRow(self.ui.rewardsList.box.collateralRow) if len(rewards) > 1: # (collateral is a reward) self.ui.rewardsList.statusLabel.setVisible(False) @@ -276,7 +276,7 @@ def onSendRewards(self): # Check spending collateral if (not self.ui.collateralHidden and self.ui.rewardsList.box.collateralRow is not None and - self.ui.rewardsList.box.item(self.ui.rewardsList.box.collateralRow, 0).isSelected() ): + self.ui.rewardsList.box.item(self.ui.rewardsList.box.collateralRow, 0).isSelected()): warning1 = "Are you sure you want to transfer the collateral?" warning2 = "Really?" warning3 = "Take a deep breath. Do you REALLY want to transfer your collateral?" @@ -440,7 +440,7 @@ def FinishSend_int(self, serialized_tx, amount_to_send): amount = decodedTx.get("vout")[0].get("value") message = '

Broadcast signed transaction?

Destination address:
%s

' % destination message += '

Amount: %s PIV
' % str(round(amount / 1e8, 8)) - message += 'Fees: %s PIV
Size: %d Bytes

' % (str(round(self.currFee / 1e8, 8) ), len(tx_hex)/2) + message += 'Fees: %s PIV
Size: %d Bytes

' % (str(round(self.currFee / 1e8, 8)), len(tx_hex) / 2) except Exception as e: printException(getCallerName(), getFunctionName(), "decoding exception", str(e)) message = '

Unable to decode TX- Broadcast anyway?

' @@ -498,12 +498,12 @@ def updateSelection(self, clicked_item=None): total += int(self.selectedRewards[i].get('satoshis')) # update suggested fee and selected rewards - estimatedTxSize = (44+numOfInputs*148)*1.0 / 1000 # kB + estimatedTxSize = (44 + numOfInputs * 148) * 1.0 / 1000 # kB self.suggestedFee = round(self.feePerKb * estimatedTxSize, 8) printDbg("estimatedTxSize is %s kB" % str(estimatedTxSize)) printDbg("suggested fee is %s PIV (%s PIV/kB)" % (str(self.suggestedFee), str(self.feePerKb))) - self.ui.selectedRewardsLine.setText(str(round(total/1e8, 8))) + self.ui.selectedRewardsLine.setText(str(round(total / 1e8, 8))) else: self.ui.selectedRewardsLine.setText("") @@ -522,5 +522,5 @@ def updateTotalBalance(self, rewards): for utxo in rewards: nAmount = nAmount + utxo['satoshis'] - totalBalance = str(round(nAmount/1e8, 8)) + totalBalance = str(round(nAmount / 1e8, 8)) self.ui.addrAvailLine.setText("%s PIVs" % totalBalance) diff --git a/src/tests/testHwDeviceMethods.py b/src/tests/testHwDeviceMethods.py index 12612fb..4125926 100644 --- a/src/tests/testHwDeviceMethods.py +++ b/src/tests/testHwDeviceMethods.py @@ -47,13 +47,13 @@ def test_transaction(self): print("=================================") print(" Press 'OK' on Ledger device ") print("---------------------------------") - txraw, amount = self.signTx(self.device, path, utxos, pivx_address_to, fee, rawtransactions) - + txraw, amount = self.signTx(self.device, path, utxos, pivx_address_to, fee, rawtransactions) + # Check total amount total = sum([int(utxo['value']) for utxo in utxos], 0) - amount = round(float(amount)*1e8) - self.assertEqual(total-fee, amount) - + amount = round(float(amount) * 1e8) + self.assertEqual(total - fee, amount) + # Decode Raw Tx to inspect and check inputs inputs = [utxo["tx_hash"] for utxo in utxos] decodedTx = self.rpcClient.decodeRawTx(txraw.hex()) @@ -64,7 +64,7 @@ def test_transaction(self): decoded_inputs.remove(input_tx) def test_scanForBip32(self): - # Get accounts obtained from seed outside ledger + # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) with open('accounts.data.txt') as datafile: # datafile has 4 lines of header (lines_offset) @@ -76,10 +76,10 @@ def test_scanForBip32(self): result, _ = self.device.scanForBip32(account_n, address, starting_spath=address_n, spath_count=1) # Address found in account_n with index. - self.assertTrue(result) + self.assertTrue(result) def test_scanForPubKey(self): - # Get accounts obtained from seed outside ledger + # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) with open('accounts.data.txt') as datafile: # datafile has 4 lines of header (lines_offset) @@ -122,7 +122,7 @@ def test_signature(self): # -- hwdevice.signMessFinish # without gui def signMess(self, path, message): - from utils import b64encode + from utils import b64encode # Ledger doesn't accept characters other that ascii printable: # https://ledgerhq.github.io/btchip-doc/bitcoin-technical.html#_sign_message message = message.encode('ascii', 'ignore') @@ -131,10 +131,10 @@ def signMess(self, path, message): if signature != None: if len(signature) > 4: rLength = signature[3] - r = signature[4 : 4 + rLength] - if len(signature) > 4 + rLength + 1: + r = signature[4: 4 + rLength] + if len(signature) > 4 + rLength + 1: sLength = signature[4 + rLength + 1] - if len(signature) > 4 + rLength + 2: + if len(signature) > 4 + rLength + 2: s = signature[4 + rLength + 2:] if rLength == 33: r = r[1:] @@ -164,7 +164,7 @@ def signMess(self, path, message): # -- hwdevice.signTxSign # -- hwdevice.signTxFinish # without gui - def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawtransactions): + def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawtransactions): # For each UTXO create a Ledger 'trusted input' self.trusted_inputs = [] # https://klmoney.wordpress.com/bitcoin-dissecting-transactions-part-2-building-a-transaction-by-hand) @@ -211,7 +211,7 @@ def signTx(self, device, bip32_path, utxos_to_spend, dest_address, tx_fee, rawt self.amount -= int(tx_fee) self.amount = int(self.amount) - arg_outputs = [{'address': dest_address, 'valueSat': self.amount}] # there will be multiple outputs soon + arg_outputs = [{'address': dest_address, 'valueSat': self.amount}] # there will be multiple outputs soon self.new_transaction = bitcoinTransaction() # new transaction object to be used for serialization at the last stage self.new_transaction.version = bytearray([0x01, 0x00, 0x00, 0x00]) try: diff --git a/src/tests/testMasternodeMethods.py b/src/tests/testMasternodeMethods.py index b55b7d3..780dcb3 100644 --- a/src/tests/testMasternodeMethods.py +++ b/src/tests/testMasternodeMethods.py @@ -23,7 +23,7 @@ def setUp(self): if not rpcStatus: self.skipTest("RPC not connected") - # read masternode data from file + # read masternode data from file with open('test_masternode.data.json') as data_file: input_data_list = json.load(data_file) @@ -55,8 +55,8 @@ def test_finalizeStartMessage(self): mnode.finalizeStartMessage(mnode.sig1) sleep(3) - # Activated by signal from masternode - @pyqtSlot(str) + # Activated by signal from masternode + @pyqtSlot(str) def finalizeStartMessage_end(self, text): # decode message ret = self.caller.rpcClient.decodemasternodebroadcast(text) @@ -82,4 +82,4 @@ def finalizeStartMessage_end(self, text): self.assertEqual(ret['vchSig'], node_sig) if __name__ == '__main__': - unittest.main(verbosity=2) \ No newline at end of file + unittest.main(verbosity=2) diff --git a/src/tests/testPivx_b58Methods.py b/src/tests/testPivx_b58Methods.py index 823d437..a3968bf 100644 --- a/src/tests/testPivx_b58Methods.py +++ b/src/tests/testPivx_b58Methods.py @@ -29,7 +29,7 @@ def test_decodeEncode(self): decoded_text = b58decode(text) print("\nDecoded Text: %s\n" % decoded_text) # verify - self.assertEqual(b58encode(decoded_text), text) + self.assertEqual(b58encode(decoded_text), text) def randomBytesString(self, length): randomString = bytes() diff --git a/src/threads.py b/src/threads.py index f1b6797..3a22896 100644 --- a/src/threads.py +++ b/src/threads.py @@ -17,44 +17,43 @@ class ThreadFuns: @staticmethod def runInThread(worker_fun, worker_fun_args, on_thread_finish=None, on_thread_exception=None, - skip_raise_exception=False): - """ - Run a function inside a thread. - :param worker_fun: reference to function to be executed inside a thread - :param worker_fun_args: arguments passed to a thread function - :param on_thread_finish: function to be called after thread finishes its execution - :param skip_raise_exception: Exception raised inside the 'worker_fun' will be passed to the calling thread if: - - on_thread_exception is a valid function (it's exception handler) - - skip_raise_exception is False - :return: reference to a thread object - """ - - def on_thread_finished_int(thread_arg, on_thread_finish_arg, skip_raise_exception_arg, on_thread_exception_arg): - if thread_arg.worker_exception: - if on_thread_exception_arg: - on_thread_exception_arg(thread_arg.worker_exception) - else: - if not skip_raise_exception_arg: - raise thread_arg.worker_exception + skip_raise_exception=False): + """ + Run a function inside a thread. + :param worker_fun: reference to function to be executed inside a thread + :param worker_fun_args: arguments passed to a thread function + :param on_thread_finish: function to be called after thread finishes its execution + :param skip_raise_exception: Exception raised inside the 'worker_fun' will be passed to the calling thread if: + - on_thread_exception is a valid function (it's exception handler) + - skip_raise_exception is False + :return: reference to a thread object + """ + + def on_thread_finished_int(thread_arg, on_thread_finish_arg, skip_raise_exception_arg, on_thread_exception_arg): + if thread_arg.worker_exception: + if on_thread_exception_arg: + on_thread_exception_arg(thread_arg.worker_exception) else: - if on_thread_finish_arg: - on_thread_finish_arg() - - if threading.current_thread() != threading.main_thread(): - # starting thread from another thread causes an issue of not passing arguments' - # values to on_thread_finished_int function, so on_thread_finish is not called - st = traceback.format_stack() - print('Running thread from inside another thread. Stack: \n' + ''.join(st)) - - thread = WorkerThread(worker_fun=worker_fun, worker_fun_args=worker_fun_args) - - # in Python 3.5 local variables sometimes are removed before calling on_thread_finished_int - # so we have to bind that variables with the function ref - bound_on_thread_finished = partial(on_thread_finished_int, thread, on_thread_finish, skip_raise_exception, - on_thread_exception) - - thread.finished.connect(bound_on_thread_finished) - thread.daemon = True - thread.start() - return thread - \ No newline at end of file + if not skip_raise_exception_arg: + raise thread_arg.worker_exception + else: + if on_thread_finish_arg: + on_thread_finish_arg() + + if threading.current_thread() != threading.main_thread(): + # starting thread from another thread causes an issue of not passing arguments' + # values to on_thread_finished_int function, so on_thread_finish is not called + st = traceback.format_stack() + print('Running thread from inside another thread. Stack: \n' + ''.join(st)) + + thread = WorkerThread(worker_fun=worker_fun, worker_fun_args=worker_fun_args) + + # in Python 3.5 local variables sometimes are removed before calling on_thread_finished_int + # so we have to bind that variables with the function ref + bound_on_thread_finished = partial(on_thread_finished_int, thread, on_thread_finish, skip_raise_exception, + on_thread_exception) + + thread.finished.connect(bound_on_thread_finished) + thread.daemon = True + thread.start() + return thread diff --git a/src/trezorClient.py b/src/trezorClient.py index 25efa9b..0bded6a 100644 --- a/src/trezorClient.py +++ b/src/trezorClient.py @@ -26,7 +26,7 @@ from qt.dlg_pinMatrix import PinMatrix_dlg -def process_trezor_exceptions(func): +def process_trezor_exceptions(func): def process_trezor_exceptions_int(*args, **kwargs): hwDevice = args[0] try: @@ -453,7 +453,7 @@ def copy_tx_meta(tx): elif res.request_type == R.TXEXTRADATA: o, l = res.details.extra_data_offset, res.details.extra_data_len msg = trezor_proto.TransactionType() - msg.extra_data = current_tx.extra_data[o : o + l] + msg.extra_data = current_tx.extra_data[o: o + l] res = client.call(trezor_proto.TxAck(tx=msg)) if isinstance(res, trezor_proto.Failure): diff --git a/src/utils.py b/src/utils.py index d6c833e..95eebc9 100644 --- a/src/utils.py +++ b/src/utils.py @@ -60,7 +60,7 @@ def compose_tx_locking_script(dest_address, isTestnet): :param dest_address: destination address in Base58Check format :return: sequence of opcodes and its arguments, defining logic of the locking script """ - pubkey_hash = bytearray.fromhex(b58check_to_hex(dest_address)) # convert address to a public key hash + pubkey_hash = bytearray.fromhex(b58check_to_hex(dest_address)) # convert address to a public key hash if len(pubkey_hash) != 20: raise Exception('Invalid length of the public key hash: ' + str(len(pubkey_hash))) @@ -74,7 +74,7 @@ def compose_tx_locking_script(dest_address, isTestnet): OP_EQUALVERIFY + \ OP_CHECKSIG elif (((not isTestnet) and (dest_address[0] in P2SH_PREFIXES)) - or (isTestnet and (dest_address[0] in P2SH_PREFIXES_TNET))): + or (isTestnet and (dest_address[0] in P2SH_PREFIXES_TNET))): # sequence of opcodes/arguments for p2sh (pay-to-script-hash) scr = OP_HASH160 + \ int.to_bytes(len(pubkey_hash), 1, byteorder='little') + \ @@ -177,9 +177,9 @@ def ipmap(ip, port): ipv6map = '' if len(ip) > 6 and ip.endswith('.onion'): - pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) + pchOnionCat = bytearray([0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43]) vchAddr = base64.b32decode(ip[0:-6], True) - if len(vchAddr) != 16-len(pchOnionCat): + if len(vchAddr) != 16 - len(pchOnionCat): raise Exception('Invalid onion %s' % str(ip)) return pchOnionCat.hex() + vchAddr.hex() + int(port).to_bytes(2, byteorder='big').hex() @@ -205,8 +205,8 @@ def ipmap(ip, port): return ipv6map except Exception as e: - err_msg = "error in ipmap" - printException(getCallerName(), getFunctionName(), err_msg, e.args) + err_msg = "error in ipmap" + printException(getCallerName(), getFunctionName(), err_msg, e.args) def num_to_varint(a): diff --git a/src/watchdogThreads.py b/src/watchdogThreads.py index bab745c..bb5da04 100644 --- a/src/watchdogThreads.py +++ b/src/watchdogThreads.py @@ -21,11 +21,11 @@ class CtrlObject(object): class RpcWatchdog(QObject): def __init__(self, control_tab, timer_off=10, timer_on=120, *args, **kwargs): QObject.__init__(self, *args, **kwargs) - self.firstLoop = True + self.firstLoop = True self.shutdown_flag = Event() self.control_tab = control_tab - self.timer_off = timer_off #delay when not connected - self.timer_on = timer_on #delay when connected + self.timer_off = timer_off # delay when not connected + self.timer_on = timer_on # delay when connected self.ctrl_obj = CtrlObject() self.ctrl_obj.finish = False From fe340df6daf4baef317a552b15013c9bdb8b3b2f Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:33:25 -0800 Subject: [PATCH 04/16] Cleanup includes --- spmt.py | 2 +- src/mainWindow.py | 4 ++-- src/misc.py | 9 +++++---- src/qt/dlg_budgetProjection.py | 2 +- src/qt/dlg_pinMatrix.py | 2 +- src/qt/dlg_sweepAll.py | 14 ++++---------- src/qt/gui_tabRewards.py | 2 +- src/rpcClient.py | 6 ++---- 8 files changed, 17 insertions(+), 24 deletions(-) diff --git a/spmt.py b/spmt.py index ecf5cf5..b8803de 100644 --- a/spmt.py +++ b/spmt.py @@ -43,7 +43,7 @@ imgDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img') from PyQt5.QtWidgets import QApplication - from PyQt5.Qt import Qt, QPixmap, QSplashScreen, QProgressBar, QColor, QPalette, QLabel + from PyQt5.Qt import Qt, QPixmap, QSplashScreen, QProgressBar, QLabel from misc import updateSplash from spmtApp import App diff --git a/src/mainWindow.py b/src/mainWindow.py index 8eb3224..a7eb2d1 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -18,8 +18,8 @@ from constants import starting_height, DefaultCache, wqueue from hwdevice import HWdevice from misc import printDbg, printException, printOK, getCallerName, getFunctionName, \ - WriteStream, WriteStreamReceiver, now, getRemoteSPMTversion, loadMNConfFile, \ - persistCacheSetting, appendMasternode, myPopUp_sb + WriteStreamReceiver, now, getRemoteSPMTversion, loadMNConfFile, \ + persistCacheSetting, appendMasternode, myPopUp_sb from tabGovernance import TabGovernance from tabMain import TabMain from tabMNConf import TabMNConf diff --git a/src/misc.py b/src/misc.py index cdd608e..d67b371 100644 --- a/src/misc.py +++ b/src/misc.py @@ -4,14 +4,15 @@ # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. -import os, sys -from contextlib import redirect_stdout -from ipaddress import ip_address import logging -import simplejson as json +import os +import sys import time +from contextlib import redirect_stdout +from ipaddress import ip_address from urllib.parse import urlparse +import simplejson as json from PyQt5.QtCore import QObject, pyqtSignal, QSettings from PyQt5.QtWidgets import QMessageBox diff --git a/src/qt/dlg_budgetProjection.py b/src/qt/dlg_budgetProjection.py index e6b537a..c840af6 100644 --- a/src/qt/dlg_budgetProjection.py +++ b/src/qt/dlg_budgetProjection.py @@ -8,7 +8,7 @@ from PyQt5.QtWidgets import QDialog, QVBoxLayout, QTableWidget, QAbstractItemView, QHeaderView, \ QTableWidgetItem, QPushButton, QLabel, QGroupBox, QHBoxLayout, QFormLayout -from misc import printException, sec_to_time +from misc import printException, sec_to_time, getCallerName, getFunctionName from threads import ThreadFuns diff --git a/src/qt/dlg_pinMatrix.py b/src/qt/dlg_pinMatrix.py index 68621fe..6c3f498 100644 --- a/src/qt/dlg_pinMatrix.py +++ b/src/qt/dlg_pinMatrix.py @@ -6,7 +6,7 @@ from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QGridLayout, \ - QLineEdit, QHBoxLayout, QWidget + QHBoxLayout, QWidget from misc import myPopUp_sb diff --git a/src/qt/dlg_sweepAll.py b/src/qt/dlg_sweepAll.py index dc24d83..1d061d8 100644 --- a/src/qt/dlg_sweepAll.py +++ b/src/qt/dlg_sweepAll.py @@ -4,20 +4,14 @@ # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. -import simplejson as json - from PyQt5.QtCore import Qt -from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem,\ - QAbstractScrollArea, QHeaderView, QLabel, QLineEdit, QFormLayout, QDoubleSpinBox, QMessageBox,\ - QApplication, QProgressBar, QCheckBox +from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem, \ + QAbstractScrollArea, QHeaderView, QLabel, QLineEdit, QFormLayout, QDoubleSpinBox, QMessageBox, \ + QApplication, QProgressBar from constants import MINIMUM_FEE -from misc import printDbg, getCallerName, getFunctionName, printException, persistCacheSetting, \ - myPopUp_sb, DisconnectedException, myPopUp -from pivx_parser import ParseTx +from misc import myPopUp from threads import ThreadFuns -from txCache import TxCache -from utils import checkPivxAddr class SweepAll_dlg(QDialog): diff --git a/src/qt/gui_tabRewards.py b/src/qt/gui_tabRewards.py index 1445a1b..6c3242e 100644 --- a/src/qt/gui_tabRewards.py +++ b/src/qt/gui_tabRewards.py @@ -9,7 +9,7 @@ from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, \ QProgressBar, QLineEdit, QComboBox, QLabel, QFormLayout, QDoubleSpinBox, QTableWidget, \ - QTableWidgetItem, QAbstractItemView, QHeaderView, QCheckBox + QTableWidgetItem, QAbstractItemView, QHeaderView from PyQt5.Qt import QIcon diff --git a/src/rpcClient.py b/src/rpcClient.py index 6f12f42..c2327cc 100644 --- a/src/rpcClient.py +++ b/src/rpcClient.py @@ -5,10 +5,8 @@ # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. from bitcoinrpc.authproxy import AuthServiceProxy -try: - import http.client as httplib -except ImportError: - import httplib + +import http.client as httplib import ssl import threading From b02695bd233794c31b24f26ed8de429529ac9eb5 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:40:34 -0800 Subject: [PATCH 05/16] Remove un-necessary trailing semi-colons --- src/ledgerClient.py | 4 ++-- src/tabMNConf.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ledgerClient.py b/src/ledgerClient.py index b0951c3..de09a04 100644 --- a/src/ledgerClient.py +++ b/src/ledgerClient.py @@ -241,7 +241,7 @@ def signMess(self, caller, hwpath, message, isTestnet=False): # Ledger doesn't accept characters other that ascii printable: # https://ledgerhq.github.io/btchip-doc/bitcoin-technical.html#_sign_message message = message.encode('ascii', 'ignore') - message_sha = splitString(single_sha256(message).hex(), 32); + message_sha = splitString(single_sha256(message).hex(), 32) # Connection pop-up mBox = QMessageBox(caller) @@ -250,7 +250,7 @@ def signMess(self, caller, hwpath, message, isTestnet=False): warningText += "click the Retry button.\nTo cancel, click the Abort button" mBox.setText(warningText) mBox.setWindowTitle("WARNING") - mBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Abort); + mBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Abort) # Ask confirmation with self.lock: diff --git a/src/tabMNConf.py b/src/tabMNConf.py index b1aed42..a9f717b 100644 --- a/src/tabMNConf.py +++ b/src/tabMNConf.py @@ -95,7 +95,7 @@ def findPubKey(self): warningText += "might have taken over the USB communication with the device.

" warningText += "To continue click the Retry button.\nTo cancel, click the Abort button." mBox = QMessageBox(QMessageBox.Critical, "WARNING", warningText, QMessageBox.Retry) - mBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Abort); + mBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Abort) while result is None: ans = mBox.exec_() From 1019467784c208c682f484e8ae3dfe04a2e6f80e Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:42:01 -0800 Subject: [PATCH 06/16] Remove unused local variables in exceptions --- src/qt/dlg_findCollTx.py | 2 +- src/tabRewards.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/qt/dlg_findCollTx.py b/src/qt/dlg_findCollTx.py index 1ffea6b..3f0b5f2 100644 --- a/src/qt/dlg_findCollTx.py +++ b/src/qt/dlg_findCollTx.py @@ -74,7 +74,7 @@ def load_utxos_thread(self, ctrl): errorMsg = 'Error occurred while calling getaddressutxos method: ' + str(e) printError(getCallerName(), getFunctionName(), errorMsg) - except Exception as e: + except Exception: pass def getSelection(self): diff --git a/src/tabRewards.py b/src/tabRewards.py index 3840641..56d1acb 100644 --- a/src/tabRewards.py +++ b/src/tabRewards.py @@ -372,7 +372,7 @@ def SendRewards(self, inputs=None, gui=None): self.currFee, self.caller.isTestnetRPC) - except DisconnectedException as e: + except DisconnectedException: self.caller.hwStatus = 0 self.caller.updateHWleds() From 3f3ca1490f58a17ae059ab7ac987d9b16649eb48 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:43:00 -0800 Subject: [PATCH 07/16] Remove unused local variable and import from trezorClient.py --- src/trezorClient.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/trezorClient.py b/src/trezorClient.py index 0bded6a..5b08c86 100644 --- a/src/trezorClient.py +++ b/src/trezorClient.py @@ -10,7 +10,7 @@ from PyQt5.QtCore import Qt, QObject, pyqtSignal from PyQt5.QtWidgets import QMessageBox, QApplication -from trezorlib import btc, exceptions, messages as trezor_proto, coins +from trezorlib import btc, exceptions, messages as trezor_proto from trezorlib.client import TrezorClient, MINIMUM_FIRMWARE_VERSION from trezorlib.tools import parse_path from trezorlib.transport import enumerate_devices @@ -201,7 +201,6 @@ def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, i c_name = "PIVX" if isTestnet: c_name += " Testnet" - coin = coins.by_name[c_name] with self.lock: self.amount = 0 From 48b8e11c9689d3d26499265d3f8624d7dc9e4567 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:43:55 -0800 Subject: [PATCH 08/16] Remove redundant parenthesis in class definitions --- src/tabMNConf.py | 2 +- src/tabMain.py | 2 +- src/tabRewards.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tabMNConf.py b/src/tabMNConf.py index a9f717b..fc4bfca 100644 --- a/src/tabMNConf.py +++ b/src/tabMNConf.py @@ -15,7 +15,7 @@ from threads import ThreadFuns -class TabMNConf(): +class TabMNConf: def __init__(self, caller, masternode_alias=None): self.caller = caller self.ui = TabMNConf_gui(masternode_alias) diff --git a/src/tabMain.py b/src/tabMain.py index d196175..fc8ae29 100644 --- a/src/tabMain.py +++ b/src/tabMain.py @@ -20,7 +20,7 @@ from threads import ThreadFuns -class TabMain(): +class TabMain: def __init__(self, caller): self.caller = caller self.all_masternodes = {} diff --git a/src/tabRewards.py b/src/tabRewards.py index 56d1acb..80005dd 100644 --- a/src/tabRewards.py +++ b/src/tabRewards.py @@ -22,7 +22,7 @@ from utils import checkPivxAddr -class TabRewards(): +class TabRewards: def __init__(self, caller): self.caller = caller From cd5c97da29d5601dab60d1bce6c7f1ec57f63a7a Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:45:30 -0800 Subject: [PATCH 09/16] Use PEP8 compliant conditional test notation --- src/database.py | 2 +- src/ledgerClient.py | 2 +- src/mainWindow.py | 2 +- src/misc.py | 2 +- src/tabMNConf.py | 2 +- src/tests/testHwDeviceMethods.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/database.py b/src/database.py index 084e1b8..0fc94d8 100644 --- a/src/database.py +++ b/src/database.py @@ -388,7 +388,7 @@ def addNewMasternode(self, mn): def addMasternode(self, mn, old_mn=None): add_defaultKeys_to_dict(mn, DEFAULT_MN_CONF) - if not old_mn is None: + if old_mn is not None: printDbg("DB: Editing masternode %s" % old_mn) try: cursor = self.getCursor() diff --git a/src/ledgerClient.py b/src/ledgerClient.py index de09a04..25719c9 100644 --- a/src/ledgerClient.py +++ b/src/ledgerClient.py @@ -291,7 +291,7 @@ def signMessageSign(self, ctrl): def signMessageFinish(self): with self.lock: self.mBox.accept() - if self.signature != None: + if self.signature is not None: if len(self.signature) > 4: rLength = self.signature[3] r = self.signature[4: 4 + rLength] diff --git a/src/mainWindow.py b/src/mainWindow.py index a7eb2d1..62325a9 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -259,7 +259,7 @@ def loadIcons(self): def loadMNConf(self, fileName): hot_masternodes = loadMNConfFile(fileName) - if hot_masternodes == None: + if hot_masternodes is None: messText = "Unable to load data from file '%s'" % fileName myPopUp_sb(self, "warn", "SPMT - Load MN Conf", messText) else: diff --git a/src/misc.py b/src/misc.py index d67b371..0a40b8d 100644 --- a/src/misc.py +++ b/src/misc.py @@ -36,7 +36,7 @@ def appendMasternode(mainWnd, mn): printDbg("saving MN configuration for %s" % mn['name']) # If we are changing a MN, remove previous entry: - if not mainWnd.mnode_to_change is None: + if mainWnd.mnode_to_change is not None: # remove from cache and QListWidget only removeMNfromList(mainWnd, mainWnd.mnode_to_change, removeFromDB=False) diff --git a/src/tabMNConf.py b/src/tabMNConf.py index fc4bfca..28f1092 100644 --- a/src/tabMNConf.py +++ b/src/tabMNConf.py @@ -207,7 +207,7 @@ def onSaveMNConf(self): mn_alias = self.ui.edt_name.text().strip() # if we are changing a masternode check for duplicate only if name is changed old_alias = None - if not self.caller.mnode_to_change is None: + if self.caller.mnode_to_change is not None: old_alias = self.caller.mnode_to_change['name'] if self.caller.isMasternodeInList(mn_alias) and old_alias != mn_alias: mess_text = 'Attention! The name %s is already in use for another masternode.
' % mn_alias diff --git a/src/tests/testHwDeviceMethods.py b/src/tests/testHwDeviceMethods.py index 4125926..e4371bd 100644 --- a/src/tests/testHwDeviceMethods.py +++ b/src/tests/testHwDeviceMethods.py @@ -128,7 +128,7 @@ def signMess(self, path, message): message = message.encode('ascii', 'ignore') self.device.chip.signMessagePrepare(path, message) signature = self.device.chip.signMessageSign(None) - if signature != None: + if signature is not None: if len(signature) > 4: rLength = signature[3] r = signature[4: 4 + rLength] From 102502343be6beb0c6d6ba3a2ae870687a3e3e6b Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:45:55 -0800 Subject: [PATCH 10/16] Add explicit type identifier to wqueue to satisfy mypy static analysis --- src/constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/constants.py b/src/constants.py index 091b8bf..7d0a374 100644 --- a/src/constants.py +++ b/src/constants.py @@ -7,7 +7,7 @@ import os from queue import Queue -wqueue = Queue() +wqueue = Queue() # type: Queue[int] MPATH_LEDGER = "44'/77'/" MPATH_TREZOR = "44'/119'/" From ada0a4369678ddea6ac886a37b1dad67b8b6dc1d Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:50:18 -0800 Subject: [PATCH 11/16] Rename DB's open function to openDB --- src/database.py | 2 +- src/spmtApp.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/database.py b/src/database.py index 0fc94d8..48e2baf 100644 --- a/src/database.py +++ b/src/database.py @@ -27,7 +27,7 @@ def __init__(self, app): self.conn = None printDbg("DB: Initialized") - def open(self): + def openDB(self): printDbg("DB: Opening...") if self.isOpen: raise Exception("Database already open") diff --git a/src/spmtApp.py b/src/spmtApp.py index 9c8f900..8d0d692 100644 --- a/src/spmtApp.py +++ b/src/spmtApp.py @@ -58,7 +58,7 @@ def __init__(self, imgDir, app, start_args): # Open database self.db = Database(self) - self.db.open() + self.db.openDB() # Clean v4 migration (read data from old files and delete them) clean_v4_migration(self) @@ -180,7 +180,7 @@ def closeEvent(self, *args, **kwargs): # Clear Rewards and Governance DB try: - self.db.open() + self.db.openDB() except Exception: pass self.db.removeTable('REWARDS') From 9b654ce9c98b7fdf75c067673a329d8c41e6454a Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 22:54:51 -0800 Subject: [PATCH 12/16] Ensure text files are always opened with UTF-8 encoding --- src/mainWindow.py | 2 +- src/misc.py | 8 ++++---- src/qt/dlg_signmessage.py | 2 +- src/tests/testHwDeviceMethods.py | 8 ++++---- src/tests/testMasternodeMethods.py | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/mainWindow.py b/src/mainWindow.py index 62325a9..b8d25cc 100644 --- a/src/mainWindow.py +++ b/src/mainWindow.py @@ -350,7 +350,7 @@ def onSaveConsole(self): try: if fileName: printOK("Saving logs to %s" % fileName) - log_file = open(fileName, 'w+') + log_file = open(fileName, 'w+', encoding="utf-8") log_text = self.consoleArea.toPlainText() log_file.write(log_text) log_file.close() diff --git a/src/misc.py b/src/misc.py index 0a40b8d..4fa8523 100644 --- a/src/misc.py +++ b/src/misc.py @@ -117,7 +117,7 @@ def clean_v4_migration(wnd): if os.path.exists(rpc_file): # If RPC file exists try: - with open(rpc_file) as data_file: + with open(rpc_file, encoding="utf-8") as data_file: rpc_config = json.load(data_file) # copy to database rpc_host = "%s:%d" % (rpc_config['rpc_ip'], rpc_config['rpc_port']) @@ -142,7 +142,7 @@ def clean_v4_migration(wnd): if os.path.exists(mn_file): # If mn file exists try: - with open(mn_file) as data_file: + with open(mn_file, encoding="utf-8") as data_file: mnList = json.load(data_file) # add to database for mn in mnList: @@ -207,7 +207,7 @@ def getRemoteSPMTversion(): def getSPMTVersion(): version_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'version.txt') - with open(version_file) as data_file: + with open(version_file, encoding="utf-8") as data_file: data = json.load(data_file) return data @@ -258,7 +258,7 @@ def is_hex(s): def loadMNConfFile(fileName): hot_masternodes = [] try: - with open(fileName) as f: + with open(fileName, encoding="utf-8") as f: for line in f: confline = line.strip() diff --git a/src/qt/dlg_signmessage.py b/src/qt/dlg_signmessage.py index c2411e0..89ebb36 100644 --- a/src/qt/dlg_signmessage.py +++ b/src/qt/dlg_signmessage.py @@ -185,7 +185,7 @@ def onSave(self): "All Files (*);; Text Files (*.txt)", options=options) try: if fileName: - save_file = open(fileName, 'w') + save_file = open(fileName, 'w', encoding="utf-8") save_file.write(self.ui.signatureTextEdt.toPlainText()) save_file.close() myPopUp_sb(self.main_wnd, QMessageBox.Information, 'SPMT - saved', "Signature saved to file") diff --git a/src/tests/testHwDeviceMethods.py b/src/tests/testHwDeviceMethods.py index e4371bd..356ef06 100644 --- a/src/tests/testHwDeviceMethods.py +++ b/src/tests/testHwDeviceMethods.py @@ -34,7 +34,7 @@ def tearDown(self): def test_transaction(self): # Read input data from file import simplejson as json - with open('test_transaction.data.json') as data_file: + with open('test_transaction.data.json', encoding="utf-8") as data_file: input_data = json.load(data_file) data_file.close() @@ -66,7 +66,7 @@ def test_transaction(self): def test_scanForBip32(self): # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) - with open('accounts.data.txt') as datafile: + with open('accounts.data.txt', encoding="utf-8") as datafile: # datafile has 4 lines of header (lines_offset) for _ in range(4): datafile.readline() @@ -81,7 +81,7 @@ def test_scanForBip32(self): def test_scanForPubKey(self): # Get accounts obtained from seed outside ledger # (5 accounts. 5 addresses per account) - with open('accounts.data.txt') as datafile: + with open('accounts.data.txt', encoding="utf-8") as datafile: # datafile has 4 lines of header (lines_offset) for _ in range(4): datafile.readline() @@ -96,7 +96,7 @@ def test_scanForPubKey(self): def test_signature(self): # Get message and path from datafile import simplejson as json - with open('test_signature.data.json') as data_file: + with open('test_signature.data.json', encoding="utf-8") as data_file: input_data = json.load(data_file) # Rename input data diff --git a/src/tests/testMasternodeMethods.py b/src/tests/testMasternodeMethods.py index 780dcb3..d00cafd 100644 --- a/src/tests/testMasternodeMethods.py +++ b/src/tests/testMasternodeMethods.py @@ -24,7 +24,7 @@ def setUp(self): self.skipTest("RPC not connected") # read masternode data from file - with open('test_masternode.data.json') as data_file: + with open('test_masternode.data.json', encoding="utf-8") as data_file: input_data_list = json.load(data_file) self.mnode_list = [] From d34f2d5337216725a29ba97001cfaaafb3abf063 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 23:03:29 -0800 Subject: [PATCH 13/16] Avoid initializing with a mutable dict default --- src/masternode.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/masternode.py b/src/masternode.py index 137e644..5f096e1 100644 --- a/src/masternode.py +++ b/src/masternode.py @@ -28,8 +28,10 @@ class Masternode(QObject): # signal: sig (thread) is done - emitted by finalizeStartMessage sigdone = pyqtSignal(str) - def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral={}, isTestnet=False, *args, **kwargs): + def __init__(self, tab_main, name, ip, port, mnPrivKey, hwAcc, collateral=None, isTestnet=False, *args, **kwargs): QObject.__init__(self, *args, **kwargs) + if collateral is None: + collateral = {} self.tab_main = tab_main self.name = name self.ip = ip From 63f3a4ee55703d3f02d08c2146620683729374b2 Mon Sep 17 00:00:00 2001 From: Fuzzbawls Date: Thu, 18 Feb 2021 23:07:06 -0800 Subject: [PATCH 14/16] [GA] Add Github Actions script --- .github/workflows/main.yaml | 85 ++++++++++++++ .../lint-python-mutable-default-parameters.sh | 49 ++++++++ lint/lint-python-utf8-encoding.sh | 28 +++++ lint/lint-python.sh | 109 ++++++++++++++++++ 4 files changed, 271 insertions(+) create mode 100644 .github/workflows/main.yaml create mode 100755 lint/lint-python-mutable-default-parameters.sh create mode 100755 lint/lint-python-utf8-encoding.sh create mode 100755 lint/lint-python.sh diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 0000000..7990e9a --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,85 @@ +name: CI Actions for SPMT + +on: [push, pull_request] +jobs: + lint: + name: Lint + runs-on: ubuntu-16.04 + defaults: + run: + shell: bash + steps: + - name: Checkout Repo + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Initialize Python + uses: actions/setup-python@v2 + with: + python-version: 3.7 + + - name: Install Dependencies + run: | + python -m pip install --upgrade pip setuptools wheel + pip install -r requirements.txt + pip install flake8==3.8.4 + pip install mypy==0.781 + pip install vulture==2.3 + + - name: Lint + run: | + lint/lint-python.sh + lint/lint-python-mutable-default-parameters.sh + lint/lint-python-utf8-encoding.sh + + build: + name: Build-${{ matrix.config.name }} + runs-on: ${{ matrix.config.os }} + needs: lint + defaults: + run: + shell: bash + strategy: + fail-fast: false + matrix: + config: + - name: Linux + os: ubuntu-16.04 + cachepath: ~/.cache/pip + packages: libusb-1.0-0-dev libudev-dev + + - name: macOS + os: macos-10.15 + cachepath: ~/Library/Caches/pip + + - name: Windows + os: windows-2019 + cachepath: ~\AppData\Local\pip\Cache + + steps: + - name: Get Source + uses: actions/checkout@v2 + - name: Setup Python 3.7 + uses: actions/setup-python@v2 + with: + python-version: 3.7 + - name: Setup pip cache + uses: actions/cache@v2 + with: + path: ${{ matrix.config.cachepath }} + key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} + restore-keys: | + ${{ runner.os }}-pip- + - name: Install dependencies + run: | + if [[ ${{ matrix.config.os }} = ubuntu* ]]; then + sudo apt-get update + sudo apt-get install --no-install-recommends --no-upgrade -qq ${{ matrix.config.packages }} + fi + python -m pip install --upgrade pip setuptools wheel + pip install -r requirements.txt + pip install pyinstaller + - name: Build + run: | + pyinstaller SecurePivxMasternodeTool.spec diff --git a/lint/lint-python-mutable-default-parameters.sh b/lint/lint-python-mutable-default-parameters.sh new file mode 100755 index 0000000..d7be7ca --- /dev/null +++ b/lint/lint-python-mutable-default-parameters.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2019 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# +# Detect when a mutable list or dict is used as a default parameter value in a Python function. + +export LC_ALL=C +EXIT_CODE=0 +OUTPUT=$(git grep -E '^\s*def [a-zA-Z0-9_]+\(.*=\s*(\[|\{)' -- "*.py") +if [[ ${OUTPUT} != "" ]]; then + echo "A mutable list or dict seems to be used as default parameter value:" + echo + echo "${OUTPUT}" + echo + cat << EXAMPLE +This is how mutable list and dict default parameter values behave: +>>> def f(i, j=[], k={}): +... j.append(i) +... k[i] = True +... return j, k +... +>>> f(1) +([1], {1: True}) +>>> f(1) +([1, 1], {1: True}) +>>> f(2) +([1, 1, 2], {1: True, 2: True}) +The intended behaviour was likely: +>>> def f(i, j=None, k=None): +... if j is None: +... j = [] +... if k is None: +... k = {} +... j.append(i) +... k[i] = True +... return j, k +... +>>> f(1) +([1], {1: True}) +>>> f(1) +([1], {1: True}) +>>> f(2) +([2], {2: True}) +EXAMPLE + EXIT_CODE=1 +fi +exit ${EXIT_CODE} diff --git a/lint/lint-python-utf8-encoding.sh b/lint/lint-python-utf8-encoding.sh new file mode 100755 index 0000000..19d018b --- /dev/null +++ b/lint/lint-python-utf8-encoding.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2018-2020 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# +# Make sure we explicitly open all text files using UTF-8 (or ASCII) encoding to +# avoid potential issues on the BSDs where the locale is not always set. + +export LC_ALL=C +EXIT_CODE=0 +OUTPUT=$(git grep " open(" -- "*.py" | grep -vE "encoding=.(ascii|utf8|utf-8)." | grep -vE "open\([^,]*, ['\"][^'\"]*b[^'\"]*['\"]") +if [[ ${OUTPUT} != "" ]]; then + echo "Python's open(...) seems to be used to open text files without explicitly" + echo "specifying encoding=\"utf8\":" + echo + echo "${OUTPUT}" + EXIT_CODE=1 +fi +OUTPUT=$(git grep "check_output(" -- "*.py" | grep "universal_newlines=True" | grep -vE "encoding=.(ascii|utf8|utf-8).") +if [[ ${OUTPUT} != "" ]]; then + echo "Python's check_output(...) seems to be used to get program outputs without explicitly" + echo "specifying encoding=\"utf8\":" + echo + echo "${OUTPUT}" + EXIT_CODE=1 +fi +exit ${EXIT_CODE} diff --git a/lint/lint-python.sh b/lint/lint-python.sh new file mode 100755 index 0000000..285a1a9 --- /dev/null +++ b/lint/lint-python.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2017-2020 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +# +# Check for specified flake8 warnings in python files. + +export LC_ALL=C +export MYPY_CACHE_DIR="${BASE_ROOT_DIR}/test/.mypy_cache" + +enabled=( + E101 # indentation contains mixed spaces and tabs + E112 # expected an indented block + E113 # unexpected indentation + E115 # expected an indented block (comment) + E116 # unexpected indentation (comment) + E125 # continuation line with same indent as next logical line + E129 # visually indented line with same indent as next logical line + E131 # continuation line unaligned for hanging indent + E133 # closing bracket is missing indentation + E223 # tab before operator + E224 # tab after operator + E242 # tab after ',' + E266 # too many leading '#' for block comment + E271 # multiple spaces after keyword + E272 # multiple spaces before keyword + E273 # tab after keyword + E274 # tab before keyword + E275 # missing whitespace after keyword + E304 # blank lines found after function decorator + E306 # expected 1 blank line before a nested definition + E401 # multiple imports on one line + E402 # module level import not at top of file + E502 # the backslash is redundant between brackets + E701 # multiple statements on one line (colon) + E702 # multiple statements on one line (semicolon) + E703 # statement ends with a semicolon + E711 # comparison to None should be 'if cond is None:' + E714 # test for object identity should be "is not" + E721 # do not compare types, use "isinstance()" + E742 # do not define classes named "l", "O", or "I" + E743 # do not define functions named "l", "O", or "I" + E901 # SyntaxError: invalid syntax + E902 # TokenError: EOF in multi-line string + F401 # module imported but unused + F402 # import module from line N shadowed by loop variable + F403 # 'from foo_module import *' used; unable to detect undefined names + F404 # future import(s) name after other statements + F405 # foo_function may be undefined, or defined from star imports: bar_module + F406 # "from module import *" only allowed at module level + F407 # an undefined __future__ feature name was imported + F601 # dictionary key name repeated with different values + F602 # dictionary key variable name repeated with different values + F621 # too many expressions in an assignment with star-unpacking + F622 # two or more starred expressions in an assignment (a, *b, *c = d) + F631 # assertion test is a tuple, which are always True + F632 # use ==/!= to compare str, bytes, and int literals + F701 # a break statement outside of a while or for loop + F702 # a continue statement outside of a while or for loop + F703 # a continue statement in a finally block in a loop + F704 # a yield or yield from statement outside of a function + F705 # a return statement with arguments inside a generator + F706 # a return statement outside of a function/method + F707 # an except: block as not the last exception handler + F811 # redefinition of unused name from line N + F812 # list comprehension redefines 'foo' from line N + F821 # undefined name 'Foo' + F822 # undefined name name in __all__ + F823 # local variable name … referenced before assignment + F831 # duplicate argument name in function definition + F841 # local variable 'foo' is assigned to but never used + W191 # indentation contains tabs + W291 # trailing whitespace + W292 # no newline at end of file + W293 # blank line contains whitespace + W601 # .has_key() is deprecated, use "in" + W602 # deprecated form of raising exception + W603 # "<>" is deprecated, use "!=" + W604 # backticks are deprecated, use "repr()" + W605 # invalid escape sequence "x" + W606 # 'async' and 'await' are reserved keywords starting with Python 3.7 +) + +if ! command -v flake8 > /dev/null; then + echo "Skipping Python linting since flake8 is not installed." + exit 0 +elif PYTHONWARNINGS="ignore" flake8 --version | grep -q "Python 2"; then + echo "Skipping Python linting since flake8 is running under Python 2. Install the Python 3 version of flake8." + exit 0 +fi + +EXIT_CODE=0 + +if ! PYTHONWARNINGS="ignore" flake8 --ignore=B,C,E,F,I,N,W --select=$(IFS=","; echo "${enabled[*]}") $( + if [[ $# == 0 ]]; then + git ls-files "*.py" + else + echo "$@" + fi +); then + EXIT_CODE=1 +fi + +if ! mypy --ignore-missing-imports $(git ls-files "src/*.py"); then + EXIT_CODE=1 +fi + +exit $EXIT_CODE \ No newline at end of file From 35486e298169be776c74638a4a14e1a4e4da661e Mon Sep 17 00:00:00 2001 From: random-zebra Date: Mon, 22 Feb 2021 14:37:03 +0100 Subject: [PATCH 15/16] [Cleanup] Remove unused variable c_name --- src/trezorClient.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/trezorClient.py b/src/trezorClient.py index 5b08c86..f3232ae 100644 --- a/src/trezorClient.py +++ b/src/trezorClient.py @@ -198,9 +198,6 @@ def json_to_bin_output(self, output): def prepare_transfer_tx_bulk(self, caller, rewardsArray, dest_address, tx_fee, isTestnet=False): inputs = [] outputs = [] - c_name = "PIVX" - if isTestnet: - c_name += " Testnet" with self.lock: self.amount = 0 From 2ca62283e08f92fdd6d5d011adbaef6aa62fb8ec Mon Sep 17 00:00:00 2001 From: random-zebra Date: Mon, 22 Feb 2021 14:38:48 +0100 Subject: [PATCH 16/16] [Cleanup] Fix Queue arg in annotation --- src/constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/constants.py b/src/constants.py index 7d0a374..3d42ef3 100644 --- a/src/constants.py +++ b/src/constants.py @@ -7,7 +7,7 @@ import os from queue import Queue -wqueue = Queue() # type: Queue[int] +wqueue = Queue() # type: Queue[str] MPATH_LEDGER = "44'/77'/" MPATH_TREZOR = "44'/119'/"