def getBudgetVotes(self, proposal): try: self.lock.acquire() votes = self.conn.getbudgetvotes(proposal) except Exception as e: err_msg = 'remote or local PIVX-cli running?' printException(getCallerName(), getFunctionName(), err_msg, e.args) votes = {} finally: self.lock.release() return votes
def getAddressUtxos(self, addresses): try: self.lock.acquire() res = self.conn.getaddressutxos({'addresses': addresses}) except Exception as e: err_msg = "error in getAddressUtxos" printException(getCallerName(), getFunctionName(), err_msg, e.args) res = None finally: self.lock.release() return res
def relaymasternodebroadcast(self, work): try: self.lock.acquire() res = self.conn.relaymasternodebroadcast(work.strip()) except Exception as e: err_msg = "error in relaymasternodebroadcast" printException(getCallerName(), getFunctionName(), err_msg, e.args) res = "" finally: self.lock.release() return res
def verifyMessage(self, pivxaddress, signature, message): try: self.lock.acquire() res = self.conn.verifymessage(pivxaddress, signature, message) except Exception as e: err_msg = "error in verifyMessage" printException(getCallerName(), getFunctionName(), err_msg, e.args) res = False finally: self.lock.release() return res
def decodeRawTransaction(self, rawTx): try: self.lock.acquire() res = self.conn.decoderawtransaction(rawTx) except Exception as e: err_msg = 'error in decodeRawTransaction' printException(getCallerName(), getFunctionName(), err_msg, e.args) res = None finally: self.lock.release() return res
def getRawTransaction(self, txid): try: self.lock.acquire() res = self.conn.getrawtransaction(txid) except Exception as e: err_msg = "is Blockchain synced?" printException(getCallerName(), getFunctionName(), err_msg, e.args) res = None finally: self.lock.release() return res
def getMasternodeCount(self): try: self.lock.acquire() ans = self.conn.getmasternodecount() except Exception as e: err_msg = "error in getMasternodeCount" printException(getCallerName(), getFunctionName(), err_msg, e.args) ans = None finally: self.lock.release() return ans
def deleteReward(self, txid, txidn): try: cursor = self.getCursor() cursor.execute( "DELETE FROM REWARDS WHERE tx_hash = ? AND tx_ouput_n = ?", (txid, txidn)) except Exception as e: err_msg = 'error deleting UTXO from DB' printException(getCallerName(), getFunctionName(), err_msg, e.args) finally: self.releaseCursor(vacuum=True)
def getBlockHash(self, blockNum): try: self.lock.acquire() h = self.conn.getblockhash(blockNum) except Exception as e: err_msg = 'remote or local PIVX-cli running?' printException(getCallerName(), getFunctionName(), err_msg, e.args) h = None finally: self.lock.release() return h
def getBlockCount(self): try: self.parameters = {} self.parameters['q'] = 'getblockcount' return self.checkResponse(self.parameters) except Exception as e: err_msg = "error in getBlockCount" printException(getCallerName(), getFunctionName(), err_msg, e.args) try: self.client.close() self.client = requests.session() except Exception: pass
def process_ledger_exceptions_int(*args, **kwargs): hwDevice = args[0] try: return func(*args, **kwargs) except BTChipException as e: printDbg('Error while communicating with Ledger hardware wallet.') e.message = 'Error while communicating with Ledger hardware wallet.' if (e.sw in (0x6f01, 0x6d00, 0x6700, 0x6faa)): e.message = 'Make sure the PIVX app is open on your Ledger device.' e.message += '<br>If there is a program (such as Ledger Bitcoin Wallet) interfering with the USB communication, close it first.' elif (e.sw == 0x6982): e.message = 'Enter the PIN on your Ledger device.' printException(getCallerName(True), getFunctionName(True), e.message, e.args) raise DisconnectedException(e.message, hwDevice) except Exception as e: e.message = "Ledger - generic exception" if str(e.args[0]) == 'read error': e.message = 'Read Error. Click "Connect" to reconnect HW device' printException(getCallerName(True), getFunctionName(True), e.message, str(e)) raise DisconnectedException(e.message, hwDevice)
def signature1(self, device): self.sig_time = int(time.time()) serializedData = ipport(self.ip, self.port) serializedData += str(self.sig_time) serializedData += binascii.unhexlify( bitcoin.hash160(bytes.fromhex( self.collateral['pubKey'])))[::-1].hex() serializedData += binascii.unhexlify( bitcoin.hash160(bytes.fromhex(self.mnPubKey)))[::-1].hex() serializedData += str(self.protocol_version) printDbg("Masternode PubKey: %s" % self.mnPubKey) printDbg("SerializedData: MY_IP:%s" % serializedData.split(':')[1]) try: device.signMess(self.caller, self.nodePath, serializedData) #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) except KeyboardInterrupt: err_msg = "Keyboard Interrupt" printException(getCallerName(), getFunctionName(), err_msg, e.args) return None
def process_RPC_exceptions_int(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: message = "Exception in RPC client" printException(getCallerName(True), getFunctionName(True), message, e) try: args[0].httpConnection.close() except Exception as e: printDbg(e) pass
def scanForPubKey(self, account, spath): printOK("Scanning for Address of path_id %s on account n° %s" % (str(spath), str(account))) curr_path = MPATH + "%d'/0/%d" % (account, spath) try: nodeData = self.chip.getWalletPublicKey(curr_path) except Exception as e: err_msg = 'error in scanForPubKey' printException(getCallerName(), getFunctionName(), err_msg, e.args) return None return compress_public_key(nodeData.get('publicKey')).hex()
def sendRawTransaction(self, tx_hex, use_swiftx): try: self.lock.acquire() tx_id = self.conn.sendrawtransaction(tx_hex, True, bool(use_swiftx)) except Exception as e: err_msg = 'error in rpcClient.sendRawTransaction' printException(getCallerName(), getFunctionName(), err_msg, e.args) tx_id = None finally: self.lock.release() return tx_id
def getProtocolVersion(self): try: self.lock.acquire() prot_version = self.conn.getinfo().get('protocolversion') res = int(prot_version) except Exception as e: err_msg = 'error in getProtocolVersion' printException(getCallerName(), getFunctionName(), err_msg, e.args) res = DEFAULT_PROTOCOL_VERSION finally: self.lock.release() return res
def removeTable(self, table_name): printDbg("DB: Dropping table %s..." % table_name) try: cursor = self.getCursor() cursor.execute("DROP TABLE IF EXISTS %s" % table_name) printDbg("DB: Table %s removed" % table_name) except Exception as e: err_msg = 'error removing table %s from database' % table_name printException(getCallerName(), getFunctionName(), err_msg, e.args) finally: self.releaseCursor(vacuum=True)
def initTables(self): try: cursor = self.conn.cursor() # Tables for RPC Servers cursor.execute("CREATE TABLE IF NOT EXISTS PUBLIC_RPC_SERVERS(" " id INTEGER PRIMARY KEY, protocol TEXT, host TEXT," " user TEXT, pass TEXT)") cursor.execute("CREATE TABLE IF NOT EXISTS CUSTOM_RPC_SERVERS(" " id INTEGER PRIMARY KEY, protocol TEXT, host TEXT," " user TEXT, pass TEXT)") self.initTable_RPC(cursor) # Tables for Masternodes cursor.execute( "CREATE TABLE IF NOT EXISTS MASTERNODES(" " name TEXT PRIMARY KEY, ip TEXT, port INTEGER, mnPrivKey TEXT," " hwAcc INTEGER, isTestnet INTEGER, isHardware INTEGER," " address TEXT, spath INTEGER, pubkey TEXT, txid TEXT, txidn INTEGER)" ) # Tables for Rewards cursor.execute( "CREATE TABLE IF NOT EXISTS REWARDS(" " tx_hash TEXT, tx_ouput_n INTEGER," " value INTEGER, confirmations INTEGER, script TEXT, raw_tx TEXT, mn_name TEXT," " PRIMARY KEY (tx_hash, tx_ouput_n))") # Tables for Governance Objects cursor.execute( "CREATE TABLE IF NOT EXISTS PROPOSALS(" " name TEXT, url TEXT, hash TEXT PRIMARY KEY, feeHash TEXT," " blockStart INTEGER, blockEnd INTEGER, totalPayCount INTEGER," " remainingPayCount INTEGER, paymentAddress TEXT," " yeas INTEGER, nays INTEGER, abstains INTEGER, " " totalPayment REAL, monthlyPayment REAL)") #cursor.execute("CREATE TABLE IF NOT EXISTS PROJECTED_PROPOSALS(" # " name TEXT, hash TEXT PRIMARY KEY, " # " allotted REAL, votes INTEGER, totaAllotted REAL)") cursor.execute( "CREATE TABLE IF NOT EXISTS MY_VOTES(" " mn_name TEXT, p_hash, vote INTEGER, timeslip INTEGER, " " PRIMARY KEY (mn_name, p_hash))") except Exception as e: err_msg = 'error initializing tables' printException(getCallerName(), getFunctionName(), err_msg, e.args)
def FinishSend(self, serialized_tx, amount_to_send): self.AbortSend() QApplication.processEvents() if not self.txFinished: try: self.txFinished = True self.close() tx_hex = serialized_tx.hex() printDbg("Raw signed transaction: " + tx_hex) printDbg("Amount to send :" + amount_to_send) if len(tx_hex) > 90000: mess = "Transaction's length exceeds 90000 bytes. Select less UTXOs and try again." self.main_tab.caller.myPopUp2(QMessageBox.Warning, 'transaction Warning', mess) else: decodedTx = self.main_tab.caller.rpcClient.decodeRawTransaction( tx_hex) destination = decodedTx.get("vout")[0].get( "scriptPubKey").get("addresses")[0] amount = decodedTx.get("vout")[0].get("value") message = '<p>Broadcast signed transaction?</p><p>Destination address:<br><b>%s</b></p>' % destination message += '<p>Amount: <b>%s</b> QMC<br>' % str(amount) message += 'Fees: <b>%s</b> QMC <br>Size: <b>%d</b> Bytes</p>' % ( str(round(self.currFee / 1e8, 8)), len(tx_hex) / 2) mess1 = QMessageBox(QMessageBox.Information, 'Send transaction', message) mess1.setDetailedText( json.dumps(decodedTx, indent=4, sort_keys=False)) mess1.setStandardButtons(QMessageBox.Yes | QMessageBox.No) reply = mess1.exec_() if reply == QMessageBox.Yes: txid = self.main_tab.caller.rpcClient.sendRawTransaction( tx_hex, self.useSwiftX()) mess2_text = "<p>Transaction successfully sent.</p><p>(Note that the selected rewards will remain displayed in the app until the transaction is confirmed.)</p>" mess2 = QMessageBox(QMessageBox.Information, 'transaction Sent', mess2_text) mess2.setDetailedText(txid) mess2.exec_() else: self.main_tab.caller.myPopUp2(QMessageBox.Information, 'Transaction NOT sent', "Transaction NOT sent") except Exception as e: err_msg = "Exception in FinishSend" printException(getCallerName(), getFunctionName(), err_msg, e.args)
def submit_torrent_thread(self, ctrl, name, uri, payee, cat): while not self.update: time.sleep(self.UPDATE_HALF_PERIOD) with requests.Session() as s: initial_block = self.current_block response = None try: response = s.post(self.server_uri, auth=self.auth_pair, data=self.prepare_budget_json( name, uri, payee, cat, self.next_super), headers={'Content-Type': 'text/plain'}) except Exception as e: printException(getCallerName(), getFunctionName(), 'Preparing the torrent failed', e.args + (name, uri, payee, cat)) response_object = json.loads(response.content) if response_object.get('error'): raise ValueError(response_object['error']['message']) while self.current_block < initial_block + self.BLOCK_DELAY: time.sleep(self.UPDATE_HALF_PERIOD) try: s.post(self.server_uri, auth=self.auth_pair, data=self.submit_budget_json(name, uri, payee, cat, self.next_super, response_object['result']), headers={'Content-Type': 'text/plain'}) except Exception as e: printException(getCallerName(), getFunctionName(), 'Submitting the torrent failed', e.args + (name, uri, payee, cat))
def getStatusCode(self): try: if self.initialized: if not self.checkApp(): statusCode = 1 else: statusCode = 2 else: statusCode = 0 except Exception as e: err_msg = 'error in getStatusCode' printException(getCallerName(), getFunctionName(), err_msg, e.args) statusCode = 0 return statusCode
def signTxSign(self, ctrl): self.lock.acquire() try: starting = True curr_input_signed = 0 # 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): self.chip.startUntrustedTransaction(starting, idx, self.trusted_inputs, new_input['locking_script']) self.chip.finalizeInputFull(self.all_outputs_raw) sig = self.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]) self.new_transaction.inputs.append(inputTx) starting = False # signature percent emitted curr_input_signed += 1 completion = int(100*curr_input_signed / len(self.arg_inputs)) self.sig_progress.emit(completion) self.new_transaction.lockTime = bytearray([0, 0, 0, 0]) self.tx_raw = bytearray(self.new_transaction.serialize()) self.sig_progress.emit(100) except TypeError as te: printDbg(str(te)) self.tx_raw = None except Exception as e: if e.sw != 0x6985: self.status = 0 printException(getCallerName(), getFunctionName(), e.message, e.args) self.tx_raw = None finally: self.lock.release() if self.status == 0: self.dongle.close() self.initDevice()
def append_inputs_to_TX(self, utxo, bip32_path, inputs): if utxo['staker'] != "": printException(getCallerName(), getFunctionName(), "Unable to sing P2CS on Trezor", "") return # Update amount self.amount += int(utxo['satoshis']) # Add input address_n = parse_path(bip32_path) prev_hash = binascii.unhexlify(utxo['txid']) it = trezor_proto.TxInputType(address_n=address_n, prev_hash=prev_hash, prev_index=int(utxo['vout'])) inputs.append(it)
def getBalance(self, address): try: self.parameters = {} self.parameters['q'] = 'getbalance' self.parameters['a'] = address return self.checkResponse(self.parameters) except Exception as e: err_msg = "error in getBalance" printException(getCallerName(), getFunctionName(), err_msg, e.args) try: self.client.close() self.client = requests.session() except Exception: pass
def startMN(self): if self.caller.hwStatus != 2: self.caller.myPopUp2(QMessageBox.Question, 'SPMT - hw device check', self.caller.hwStatusMess, QMessageBox.Ok) elif not self.caller.rpcConnected: self.caller.myPopUp2(QMessageBox.Question, 'SPMT - rpc device check', self.caller.rpcStatusMess, QMessageBox.Ok) else: try: self.masternodeToStart = self.mnToStartList.pop() printDbg("Starting...%s" % self.masternodeToStart.name) self.masternodeToStart.startMessage(self.caller.hwdevice, self.caller.rpcClient) # wait for signal when masternode.work is ready then ---> sendBroadcast except Exception as e: err_msg = "error in startMN" printException(getCallerName(), getFunctionName(), err_msg, e)
def getBlockHash(self, blockNum): try: self.parameters = {} self.parameters['q'] = 'getblockhash' self.parameters['height'] = str(blockNum) return self.checkResponse(self.parameters) except Exception as e: err_msg = "error in getBlockHash" printException(getCallerName(), getFunctionName(), err_msg, e.args) try: self.client.close() self.client = requests.session() except Exception: pass
def clearRawTxes(self, minTime): """ removes txes with lastfetch older than mintime """ printDbg("Pruning table RAWTXES") try: cursor = self.getCursor() cursor.execute("DELETE FROM RAWTXES WHERE lastfetch < ?", (minTime,)) except Exception as e: err_msg = 'error deleting rawtx from DB' printException(getCallerName(), getFunctionName(), err_msg, e.args) finally: self.releaseCursor(vacuum=True)
def getFeePerKb(self): try: self.lock.acquire() # get transaction data from last 200 blocks feePerKb = float(self.conn.getfeeinfo(200)['feeperkb']) res = (feePerKb if feePerKb > MINIMUM_FEE else MINIMUM_FEE) except Exception as e: err_msg = 'error in getFeePerKb' printException(getCallerName(), getFunctionName(), err_msg, e.args) res = MINIMUM_FEE finally: self.lock.release() return res
def getBlockCount(self): try: self.lock.acquire() n = self.conn.getblockcount() except Exception as e: err_msg = 'remote or local PIVX-cli running?' if str(e.args[0]) != "Request-sent": printException(getCallerName(), getFunctionName(), err_msg, e.args) n = 0 finally: self.lock.release() return n
def isBlockchainSynced(self): try: self.lock.acquire() res = self.conn.mnsync('status').get("IsBlockchainSynced") except Exception as e: if str(e.args[0]) != "Request-sent": err_msg = "error in isBlockchainSynced" printException(getCallerName(), getFunctionName(), err_msg, e.args) res = False finally: self.lock.release() return res