def mouseReleaseEvent(self, event):
        dialog = QDialog(self)
        dialog.setWindowTitle(_('Electrum update'))
        dialog.setModal(1)

        main_layout = QGridLayout()
        main_layout.addWidget(QLabel(_("A new version of Electrum is available:")+" " + self.latest_version), 0,0,1,3)

        ignore_version = QPushButton(_("Ignore this version"))
        ignore_version.clicked.connect(self.ignore_this_version)

        ignore_all_versions = QPushButton(_("Ignore all versions"))
        ignore_all_versions.clicked.connect(self.ignore_all_version)

        open_website = QPushButton(_("Goto download page"))
        open_website.clicked.connect(self.open_website)

        main_layout.addWidget(ignore_version, 1, 0)
        main_layout.addWidget(ignore_all_versions, 1, 1)
        main_layout.addWidget(open_website, 1, 2)

        dialog.setLayout(main_layout)

        self.dialog = dialog

        if not dialog.exec_(): return
    def context_menu(self):
        view_menu = QMenu()
        themes_menu = view_menu.addMenu(_("&Themes"))
        selected_theme = self.actuator.selected_theme()
        theme_group = QActionGroup(self)
        for theme_name in self.actuator.theme_names():
            theme_action = themes_menu.addAction(theme_name)
            theme_action.setCheckable(True)
            if selected_theme == theme_name:
                theme_action.setChecked(True)
            class SelectThemeFunctor:
                def __init__(self, theme_name, toggle_theme):
                    self.theme_name = theme_name
                    self.toggle_theme = toggle_theme
                def __call__(self, checked):
                    if checked:
                        self.toggle_theme(self.theme_name)
            delegate = SelectThemeFunctor(theme_name, self.toggle_theme)
            theme_action.toggled.connect(delegate)
            theme_group.addAction(theme_action)
        view_menu.addSeparator()

        show_receiving = view_menu.addAction(_("Show Receiving addresses"))
        show_receiving.setCheckable(True)
        show_receiving.toggled.connect(self.toggle_receiving_layout)
        show_receiving.setChecked(self.config.get("gui_show_receiving",False))

        show_history = view_menu.addAction(_("Show History"))
        show_history.setCheckable(True)
        show_history.toggled.connect(self.show_history)
        show_history.setChecked(self.config.get("gui_show_history",False))

        return view_menu
    def __init__(self, transaction_id, parent):
        super(TransactionWindow, self).__init__()

        self.tx_id = str(transaction_id)
        self.parent = parent

        self.setModal(True)
        self.resize(200,100)
        self.setWindowTitle(_("Transaction successfully sent"))

        self.layout = QGridLayout(self)
        history_label = "%s\n%s" % (_("Your transaction has been sent."), _("Please enter a label for this transaction for future reference."))
        self.layout.addWidget(QLabel(history_label))

        self.label_edit = QLineEdit()
        self.label_edit.setPlaceholderText(_("Transaction label"))
        self.label_edit.setObjectName("label_input")
        self.label_edit.setAttribute(Qt.WA_MacShowFocusRect, 0)
        self.label_edit.setFocusPolicy(Qt.ClickFocus)
        self.layout.addWidget(self.label_edit)

        self.save_button = QPushButton(_("Save"))
        self.layout.addWidget(self.save_button)
        self.save_button.clicked.connect(self.set_label)

        self.exec_()
예제 #4
0
 def build_tray_menu(self):
     m = QMenu()
     m.addAction(_("Show/Hide"), self.show_or_hide)
     m.addAction(_("Dark/Light"), self.toggle_tray_icon)
     m.addSeparator()
     m.addAction(_("Exit Electrum-BOLI"), self.close)
     self.tray.setContextMenu(m)
    def __init__(self, address, parent):
        self.address = address
        self.parent = parent
        self.config = parent.config
        self.wallet = parent.wallet
        self.app = parent.app
        self.saved = True

        QDialog.__init__(self)
        self.setMinimumWidth(700)
        self.setWindowTitle(_("Address"))
        self.setModal(1)
        vbox = QVBoxLayout()
        self.setLayout(vbox)

        vbox.addWidget(QLabel(_("Address:")))
        self.addr_e = ButtonsLineEdit(self.address)
        self.addr_e.addCopyButton(self.app)
        self.addr_e.addButton(":icons/qrcode.png", self.show_qr, _("Show QR Code"))
        self.addr_e.setReadOnly(True)
        vbox.addWidget(self.addr_e)

        vbox.addWidget(QLabel(_("History")))
        self.hw = HistoryWidget(self.parent)
        vbox.addWidget(self.hw)

        vbox.addStretch(1)
        vbox.addLayout(Buttons(CloseButton(self)))
        self.format_amount = self.parent.format_amount

        h = self.wallet.get_history([self.address])
        self.hw.update(h)
 def qr_input(self):
     from electrum_boli import qrscanner, get_config
     try:
         data = qrscanner.scan_qr(get_config())
     except BaseException, e:
         QMessageBox.warning(self, _('Error'), _(e), _('OK'))
         return ""
    def multi_mpk_dialog(self, xpub_hot, n):
        vbox = QVBoxLayout()
        scroll = QScrollArea()
        scroll.setEnabled(True)
        scroll.setWidgetResizable(True)
        vbox.addWidget(scroll)

        w = QWidget()
        scroll.setWidget(w)

        innerVbox = QVBoxLayout()
        w.setLayout(innerVbox)

        vbox0 = seed_dialog.show_seed_box(MSG_SHOW_MPK, xpub_hot, 'hot')
        innerVbox.addLayout(vbox0)
        entries = []
        for i in range(n):
            msg = _("Please enter the master public key of cosigner") + ' %d'%(i+1)
            vbox2, seed_e2 = seed_dialog.enter_seed_box(msg, self, 'cold')
            innerVbox.addLayout(vbox2)
            entries.append(seed_e2)
        vbox.addStretch(1)
        button = OkButton(self, _('Next'))
        vbox.addLayout(Buttons(CancelButton(self), button))
        button.setEnabled(False)
        f = lambda: button.setEnabled( map(lambda e: Wallet.is_xpub(self.get_seed_text(e)), entries) == [True]*len(entries))
        for e in entries:
            e.textChanged.connect(f)
        self.set_layout(vbox)
        if not self.exec_():
            return
        return map(lambda e: self.get_seed_text(e), entries)
 def on_change_hist(checked):
     if checked:
         self.config.set_key('history_rates', 'checked')
         self.request_history_rates()
     else:
         self.config.set_key('history_rates', 'unchecked')
         self.win.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
         self.win.history_list.setColumnCount(5)
 def save(self):
     name = 'signed_%s.txn' % (self.tx.hash()[0:8]) if self.tx.is_complete() else 'unsigned.txn'
     fileName = self.parent.getSaveFileName(_("Select where to save your signed transaction"), name, "*.txn")
     if fileName:
         with open(fileName, "w+") as f:
             f.write(json.dumps(self.tx.as_dict(), indent=4) + '\n')
         self.show_message(_("Transaction saved successfully"))
         self.saved = True
 def verify_seed(self, seed, sid, func=None):
     r = self.enter_seed_dialog(MSG_VERIFY_SEED, sid, func)
     if not r:
         return
     if prepare_seed(r) != prepare_seed(seed):
         QMessageBox.warning(None, _('Error'), _('Incorrect seed'), _('OK'))
         return False
     else:
         return True
    def add_io(self, vbox):

        if self.tx.locktime > 0:
            vbox.addWidget(QLabel("LockTime: %d\n" % self.tx.locktime))

        vbox.addWidget(QLabel(_("Inputs")))

        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(QColor("lightgreen")))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(QColor("yellow")))
        chg.setToolTip(_("Wallet change address"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            return ext

        i_text = QTextEdit()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        i_text.setMaximumHeight(100)
        cursor = i_text.textCursor()
        for x in self.tx.inputs:
            if x.get('is_coinbase'):
                cursor.insertText('coinbase')
            else:
                prevout_hash = x.get('prevout_hash')
                prevout_n = x.get('prevout_n')
                cursor.insertText(prevout_hash[0:8] + '...', ext)
                cursor.insertText(prevout_hash[-8:] + ":%-4d " % prevout_n, ext)
                addr = x.get('address')
                if addr == "(pubkey)":
                    _addr = self.wallet.find_pay_to_pubkey_address(prevout_hash, prevout_n)
                    if _addr:
                        addr = _addr
                if addr is None:
                    addr = _('unknown')
                cursor.insertText(addr, text_format(addr))
            cursor.insertBlock()

        vbox.addWidget(i_text)
        vbox.addWidget(QLabel(_("Outputs")))
        o_text = QTextEdit()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        o_text.setMaximumHeight(100)
        cursor = o_text.textCursor()
        for addr, v in self.tx.get_outputs():
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(self.parent.format_amount(v, whitespaces = True), ext)
            cursor.insertBlock()
        vbox.addWidget(o_text)
 def give_error(self, message, clear_client = False):
     print_error(message)
     if not self.signing:
         QMessageBox.warning(QDialog(), _('Warning'), _(message), _('OK'))
     else:
         self.signing = False
     if clear_client and self.client is not None:
         self.client.bad = True
         self.device_checked = False
     raise Exception(message)
 def installwizard_restore(self, wizard, storage):
     if storage.get('wallet_type') != 'btchip':
         return
     wallet = BTChipWallet(storage)
     try:
         wallet.create_main_account(None)
     except BaseException as e:
         QMessageBox.information(None, _('Error'), str(e), _('OK'))
         return
     return wallet
def ok_cancel_buttons(dialog):
    row_layout = QHBoxLayout()
    row_layout.addStretch(1)
    ok_button = QPushButton(_("OK"))
    row_layout.addWidget(ok_button)
    ok_button.clicked.connect(dialog.accept)
    cancel_button = QPushButton(_("Cancel"))
    row_layout.addWidget(cancel_button)
    cancel_button.clicked.connect(dialog.reject)
    return row_layout
 def __init__(self, parent, seed, imported_keys):
     QDialog.__init__(self, parent)
     self.setModal(1)
     self.setMinimumWidth(400)
     self.setWindowTitle('Electrum-BOLI' + ' - ' + _('Seed'))
     vbox = show_seed_box_msg(seed)
     if imported_keys:
         vbox.addWidget(QLabel("<b>"+_("WARNING")+":</b> " + _("Your wallet contains imported keys. These keys cannot be recovered from seed.") + "</b><p>"))
     vbox.addLayout(Buttons(CloseButton(self)))
     self.setLayout(vbox)
 def closeEvent(self, event):
     if (self.prompt_if_unsaved and not self.saved and not self.broadcast
         and QMessageBox.question(
             self, _('Warning'),
             _('This transaction is not saved. Close anyway?'),
             QMessageBox.Yes | QMessageBox.No) == QMessageBox.No):
         event.ignore()
     else:
         event.accept()
         dialogs.remove(self)
    def history_tab_update(self):
        if self.config.get('history_rates') != "checked":
            return
        if not self.resp_hist:
            return
        if not self.wallet:
            return

        self.win.is_edit = True
        self.win.history_list.setColumnCount(6)
        self.win.history_list.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance'), _('Fiat Amount')] )
        root = self.win.history_list.invisibleRootItem()
        childcount = root.childCount()
        for i in range(childcount):
            item = root.child(i)
            try:
                tx_info = self.tx_list[str(item.data(0, Qt.UserRole).toPyObject())]
            except Exception:
                newtx = self.wallet.get_history()
                v = newtx[[x[0] for x in newtx].index(str(item.data(0, Qt.UserRole).toPyObject()))][2]
                tx_info = {'timestamp':int(time.time()), 'value': v}
                pass
            tx_time = int(tx_info['timestamp'])
            tx_value = Decimal(str(tx_info['value'])) / COIN
            if self.cur_exchange == "CoinDesk":
                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
                try:
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(self.resp_hist['bpi'][tx_time_str]), "USD")
                except KeyError:
                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(str(tx_info['value']))/COIN , "USD")
            elif self.cur_exchange == "Winkdex":
                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
                try:
                    tx_rate = self.resp_hist[[x['timestamp'] for x in self.resp_hist].index(tx_time_str)]['price']
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(tx_rate)/Decimal("100.0"), "USD")
                except ValueError:
                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(tx_info['value'])/COIN , "USD")
                except KeyError:
                    tx_fiat_val = _("No data")
            elif self.cur_exchange == "BitcoinVenezuela":
                tx_time_str = datetime.datetime.fromtimestamp(tx_time).strftime('%Y-%m-%d')
                try:
                    num = self.resp_hist[tx_time_str].replace(',','')
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(num), self.fiat_unit())
                except KeyError:
                    tx_fiat_val = _("No data")

            tx_fiat_val = " "*(12-len(tx_fiat_val)) + tx_fiat_val
            item.setText(5, tx_fiat_val)
            item.setFont(5, QFont(MONOSPACE_FONT))
            if Decimal(str(tx_info['value'])) < 0:
                item.setForeground(5, QBrush(QColor("#BC1E1E")))

        self.win.history_list.setColumnWidth(5, 120)
        self.win.is_edit = False
 def append(self, address, amount, date):
     if address is None:
         address = _("Unknown")
     if amount is None:
         amount = _("Unknown")
     if date is None:
         date = _("Unknown")
     item = QTreeWidgetItem([amount, address, date])
     if amount.find("-") != -1:
         item.setForeground(0, QBrush(QColor("#BC1E1E")))
     self.insertTopLevelItem(0, item)
    def __init__(self, owner=None):
        self.owner = owner
        self.editing = False

        QTreeWidget.__init__(self, owner)
        self.setColumnCount(3)
        self.setHeaderLabels([_("Address"), _("Label"), _("Used")])
        self.setIndentation(0)

        self.hide_used = True
        self.setColumnHidden(2, True)
예제 #20
0
    def close(self):
        self.d.accept()
        if self.error:
            QMessageBox.warning(self.parent, _('Error'), self.error, _('OK'))
        else:
            if self.on_success:
                if type(self.result) is not tuple:
                    self.result = (self.result,)
                self.on_success(*self.result)

        if self.on_complete:
            self.on_complete()
    def restore_or_create(self):
        vbox = QVBoxLayout()
        main_label = QLabel(_("Electrum-BOLI could not find an existing wallet."))
        vbox.addWidget(main_label)
        grid = QGridLayout()
        grid.setSpacing(5)
        gb1 = QGroupBox(_("What do you want to do?"))
        vbox.addWidget(gb1)
        b1 = QRadioButton(gb1)
        b1.setText(_("Create new wallet"))
        b1.setChecked(True)
        b2 = QRadioButton(gb1)
        b2.setText(_("Restore a wallet or import keys"))
        group1 = QButtonGroup()
        group1.addButton(b1)
        group1.addButton(b2)
        vbox.addWidget(b1)
        vbox.addWidget(b2)

        gb2 = QGroupBox(_("Wallet type:"))
        vbox.addWidget(gb2)
        group2 = QButtonGroup()

        self.wallet_types = [
            ('standard',  _("Standard wallet")),
            ('twofactor', _("Wallet with two-factor authentication")),
            ('multisig',  _("Multi-signature wallet")),
            ('hardware',  _("Hardware wallet")),
        ]

        for i, (wtype,name) in enumerate(self.wallet_types):
            if not filter(lambda x:x[0]==wtype, electrum_boli.wallet.wallet_types):
                continue
            button = QRadioButton(gb2)
            button.setText(name)
            vbox.addWidget(button)
            group2.addButton(button)
            group2.setId(button, i)
            if i==0:
                button.setChecked(True)

        vbox.addStretch(1)
        self.set_layout(vbox)
        vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
        self.show()
        self.raise_()

        if not self.exec_():
            return None, None

        action = 'create' if b1.isChecked() else 'restore'
        wallet_type = self.wallet_types[group2.checkedId()][0]
        return action, wallet_type
def show_seed_box_msg(seedphrase, sid=None):
    msg =  _("Your wallet generation seed is") + ":"
    vbox = show_seed_box(msg, seedphrase, sid)
    save_msg = _("Please save these %d words on paper (order is important).")%len(seedphrase.split()) + " "
    msg2 = save_msg + " " \
           + _("This seed will allow you to recover your wallet in case of computer failure.") + "<br/>" \
           + "<b>"+_("WARNING")+":</b> " + _("Never disclose your seed. Never type it on a website.") + "</b><p>"
    label2 = QLabel(msg2)
    label2.setWordWrap(True)
    vbox.addWidget(label2)
    vbox.addStretch(1)
    return vbox
 def load_wallet(self, wallet, window):
     self.wallet = wallet
     self.wallet.plugin = self
     self.window = window
     if self.handler is None:
         self.handler = BTChipQTHandler(self.window.app)
     if self.btchip_is_connected():
         if not self.wallet.check_proper_device():
             QMessageBox.information(self.window, _('Error'), _("This wallet does not match your BTChip device"), _('OK'))
             self.wallet.force_watching_only = True
     else:
         QMessageBox.information(self.window, _('Error'), _("BTChip device not detected.\nContinuing in watching-only mode."), _('OK'))
         self.wallet.force_watching_only = True
 def question(self, msg, yes_label=_('OK'), no_label=_('Cancel'), icon=None):
     vbox = QVBoxLayout()
     self.set_layout(vbox)
     if icon:
         logo = QLabel()
         logo.setPixmap(icon)
         vbox.addWidget(logo)
     label = QLabel(msg)
     label.setWordWrap(True)
     vbox.addWidget(label)
     vbox.addStretch(1)
     vbox.addLayout(Buttons(CancelButton(self, no_label), OkButton(self, yes_label)))
     if not self.exec_():
         return None
     return True
예제 #25
0
    def passphrase_dialog(self):
        from electrum_boli_gui.qt.password_dialog import make_password_dialog, run_password_dialog

        d = QDialog()
        d.setModal(1)
        d.setLayout(make_password_dialog(d, None, self.message, False))
        confirmed, p, passphrase = run_password_dialog(d, None, None)
        if not confirmed:
            QMessageBox.critical(None, _("Error"), _("Password request canceled"), _("OK"))
            self.passphrase = None
        else:
            if passphrase is None:
                passphrase = ""  # Even blank string is valid Trezor passphrase
            self.passphrase = unicodedata.normalize("NFKD", unicode(passphrase))
        self.done.set()
    def setup(self, address):
        label = QLabel(_("Copied your Dash address to the clipboard!"))
        address_display = QLineEdit(address)
        address_display.setReadOnly(True)
        resize_line_edit_width(address_display, address)

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(label)
        main_layout.addWidget(address_display)

        self.setMouseTracking(True)
        self.setWindowTitle("Electrum-BOLI - " + _("Receive Dash payment"))
        self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|
                            Qt.MSWindowsFixedSizeDialogHint)
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
예제 #27
0
    def __init__(self, win):
        QWidget.__init__(self)
        self.win = win
        self.setWindowTitle('Electrum-BOLI - '+_('Payment Request'))
        self.setMinimumSize(800, 250)
        self.address = ''
        self.label = ''
        self.amount = 0
        self.setFocusPolicy(QtCore.Qt.NoFocus)

        main_box = QHBoxLayout()

        self.qrw = QRCodeWidget()
        main_box.addWidget(self.qrw, 1)

        vbox = QVBoxLayout()
        main_box.addLayout(vbox)

        self.address_label = QLabel("")
        #self.address_label.setFont(QFont(MONOSPACE_FONT))
        vbox.addWidget(self.address_label)

        self.label_label = QLabel("")
        vbox.addWidget(self.label_label)

        self.amount_label = QLabel("")
        vbox.addWidget(self.amount_label)

        vbox.addStretch(1)
        self.setLayout(main_box)
 def __init__(self, change_quote_currency, parent=None):
     super(QLabel, self).__init__(_("Connecting..."), parent)
     self.change_quote_currency = change_quote_currency
     self.state = self.SHOW_CONNECTING
     self.balance_text = ""
     self.amount_text = ""
     self.parent = parent
    def on_receive(self):
        if self.wallet.use_encryption:
            password = self.win.password_dialog('An encrypted transaction was retrieved from cosigning pool.\nPlease enter your password to decrypt it.')
            if not password:
                return
        else:
            password = None
            if not self.win.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")):
                return

        message = self.listener.message
        key = self.listener.keyname
        xprv = self.wallet.get_master_private_key(key, password)
        if not xprv:
            return
        try:
            k = bitcoin.deserialize_xkey(xprv)[-1].encode('hex')
            EC = bitcoin.EC_KEY(k.decode('hex'))
            message = EC.decrypt_message(message)
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
            self.win.show_message(str(e))
            return

        self.listener.clear()
        tx = transaction.Transaction(message)
        show_transaction(tx, self.win, prompt_if_unsaved=True)
 def auth_dialog(self ):
     d = QDialog(self.window)
     d.setModal(1)
     vbox = QVBoxLayout(d)
     pw = AmountEdit(None, is_int = True)
     msg = _('Please enter your Google Authenticator code')
     vbox.addWidget(QLabel(msg))
     grid = QGridLayout()
     grid.setSpacing(8)
     grid.addWidget(QLabel(_('Code')), 1, 0)
     grid.addWidget(pw, 1, 1)
     vbox.addLayout(grid)
     vbox.addLayout(Buttons(CancelButton(d), OkButton(d)))
     if not d.exec_():
         return
     return pw.get_amount()
예제 #31
0
 def on_error(self):
     QMessageBox.information(None, _("Error"), self.error)
     self.setEnabled(True)
예제 #32
0
 def receive_list_menu(self, menu, addr):
     menu.addAction(_("Send via e-mail"), lambda: self.send(addr))
예제 #33
0
 def __init__(self, dialog):
     QPushButton.__init__(self, _("Close"))
     self.clicked.connect(dialog.close)
     self.setDefault(True)
예제 #34
0
 def __init__(self, dialog, label=None):
     QPushButton.__init__(self, label or _("Cancel"))
     self.clicked.connect(dialog.reject)
    def history_tab_update(self):
        if self.config.get('history_rates') != "checked":
            return
        if not self.resp_hist:
            return
        if not self.wallet:
            return

        self.win.is_edit = True
        self.win.history_list.setColumnCount(6)
        self.win.history_list.setHeaderLabels([
            '',
            _('Date'),
            _('Description'),
            _('Amount'),
            _('Balance'),
            _('Fiat Amount')
        ])
        root = self.win.history_list.invisibleRootItem()
        childcount = root.childCount()
        for i in range(childcount):
            item = root.child(i)
            try:
                tx_info = self.tx_list[str(
                    item.data(0, Qt.UserRole).toPyObject())]
            except Exception:
                newtx = self.wallet.get_history()
                v = newtx[[x[0] for x in newtx].index(
                    str(item.data(0, Qt.UserRole).toPyObject()))][2]
                tx_info = {'timestamp': int(time.time()), 'value': v}
                pass
            tx_time = int(tx_info['timestamp'])
            tx_value = Decimal(str(tx_info['value'])) / COIN
            if self.cur_exchange == "CoinDesk":
                tx_time_str = datetime.datetime.fromtimestamp(
                    tx_time).strftime('%Y-%m-%d')
                try:
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(
                        self.resp_hist['bpi'][tx_time_str]), "USD")
                except KeyError:
                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(
                        str(tx_info['value'])) / COIN, "USD")
            elif self.cur_exchange == "Winkdex":
                tx_time_str = datetime.datetime.fromtimestamp(
                    tx_time).strftime('%Y-%m-%d') + "T16:00:00-04:00"
                try:
                    tx_rate = self.resp_hist[[
                        x['timestamp'] for x in self.resp_hist
                    ].index(tx_time_str)]['price']
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(tx_rate) /
                                               Decimal("100.0"), "USD")
                except ValueError:
                    tx_fiat_val = "%.2f %s" % (self.btc_rate * Decimal(
                        tx_info['value']) / COIN, "USD")
                except KeyError:
                    tx_fiat_val = _("No data")
            elif self.cur_exchange == "BitcoinVenezuela":
                tx_time_str = datetime.datetime.fromtimestamp(
                    tx_time).strftime('%Y-%m-%d')
                try:
                    num = self.resp_hist[tx_time_str].replace(',', '')
                    tx_fiat_val = "%.2f %s" % (tx_value * Decimal(num),
                                               self.fiat_unit())
                except KeyError:
                    tx_fiat_val = _("No data")

            tx_fiat_val = " " * (12 - len(tx_fiat_val)) + tx_fiat_val
            item.setText(5, tx_fiat_val)
            item.setFont(5, QFont(MONOSPACE_FONT))
            if Decimal(str(tx_info['value'])) < 0:
                item.setForeground(5, QBrush(QColor("#BC1E1E")))

        self.win.history_list.setColumnWidth(5, 120)
        self.win.is_edit = False
class Plugin(BasePlugin):

    button_label = _("Verify GA instant")

    @hook
    def init_qt(self, gui):
        self.win = gui.main_window

    @hook
    def transaction_dialog(self, d):
        self.wallet = d.wallet
        self.verify_button = b = QPushButton(self.button_label)
        b.clicked.connect(lambda: self.do_verify(d.tx))
        d.buttons.insert(0, b)
        self.transaction_dialog_update(d)

    def get_my_addr(self, tx):
        """Returns the address for given tx which can be used to request
        instant confirmation verification from GreenAddress"""

        for addr, _ in tx.get_outputs():
            if self.wallet.is_mine(addr):
                return addr
        return None

    @hook
    def transaction_dialog_update(self, d):
        if d.tx.is_complete() and self.get_my_addr(d.tx):
            self.verify_button.show()
        else:
            self.verify_button.hide()

    def do_verify(self, tx):
        # 1. get the password and sign the verification request
        password = None
        if self.wallet.use_encryption:
            msg = _(
                'GreenAddress requires your signature to verify that transaction is instant.\n'
                'Please enter your password to sign a verification request.')
            password = self.win.password_dialog(msg)
            if not password:
                return
        try:
            self.verify_button.setText(_('Verifying...'))
            QApplication.processEvents()  # update the button label

            addr = self.get_my_addr(tx)
            message = "Please verify if %s is GreenAddress instant confirmed" % tx.hash(
            )
            sig = self.wallet.sign_message(addr, message, password)
            sig = base64.b64encode(sig)

            # 2. send the request
            response = requests.request(
                "GET",
                ("https://greenaddress.it/verify/?signature=%s&txhash=%s" %
                 (urllib.quote(sig), tx.hash())),
                headers={'User-Agent': 'Electrum'})
            response = response.json()

            # 3. display the result
            if response.get('verified'):
                QMessageBox.information(
                    None, _('Verification successful!'),
                    _('%s is covered by GreenAddress instant confirmation') %
                    (tx.hash()), _('OK'))
            else:
                QMessageBox.critical(
                    None, _('Verification failed!'),
                    _('%s is not covered by GreenAddress instant confirmation')
                    % (tx.hash()), _('OK'))
        except BaseException as e:
            import traceback
            traceback.print_exc(file=sys.stdout)
            QMessageBox.information(None, _('Error'), str(e), _('OK'))
        finally:
            self.verify_button.setText(self.button_label)
예제 #37
0
 def contextMenuEvent(self, e):
     m = self.createStandardContextMenu()
     m.addAction(_("Read QR code"), self.qr_input)
     m.exec_(e.globalPos())
예제 #38
0
 def __init__(self, dialog, label=None):
     QPushButton.__init__(self, label or _("OK"))
     self.clicked.connect(dialog.accept)
     self.setDefault(True)
예제 #39
0
 def __init__(self, text=""):
     ButtonsTextEdit.__init__(self, text)
     self.setReadOnly(0)
     self.addButton(":icons/file.png", self.file_input, _("Read file"))
     self.addButton(":icons/qrcode.png", self.qr_input, _("Read QR code"))
     run_hook('scan_text_edit', self)
예제 #40
0
 def contextMenuEvent(self, e):
     m = self.createStandardContextMenu()
     m.addAction(_("Show as QR code"), self.qr_show)
     m.exec_(e.globalPos())
예제 #41
0
 def addCopyButton(self, app):
     self.app = app
     f = lambda: self.app.clipboard().setText(str(self.text()))
     self.addButton(":icons/copy.png", f, _("Copy to Clipboard"))
예제 #42
0
    def __init__(self, text=None):
        QLineEdit.__init__(self, text)
        self.buttons = []

    def resizeEvent(self, e):
        o = QLineEdit.resizeEvent(self, e)
        self.resizeButtons()
        return o


class ButtonsTextEdit(QPlainTextEdit, ButtonsWidget):
    def __init__(self, text=None):
        QPlainTextEdit.__init__(self, text)
        self.setText = self.setPlainText
        self.text = self.toPlainText
        self.buttons = []

    def resizeEvent(self, e):
        o = QPlainTextEdit.resizeEvent(self, e)
        self.resizeButtons()
        return o


if __name__ == "__main__":
    app = QApplication([])
    t = WaitingDialog(
        None, 'testing ...', lambda: [time.sleep(1)],
        lambda x: QMessageBox.information(None, 'done', "done", _('OK')))
    t.start()
    app.exec_()
예제 #43
0
 def __init__(self, text_getter, app, dialog):
     QPushButton.__init__(self, _("Copy and Close"))
     self.clicked.connect(lambda: app.clipboard().setText(text_getter()))
     self.clicked.connect(dialog.close)
     self.setDefault(True)
    def __init__(self, network, config, parent):

        QDialog.__init__(self, parent)
        self.setModal(1)
        self.setWindowTitle(_('Network'))
        self.setMinimumSize(375, 20)

        self.network = network
        self.config = config
        self.protocol = None

        self.servers = network.get_servers()
        host, port, protocol, proxy_config, auto_connect = network.get_parameters(
        )
        if not proxy_config:
            proxy_config = {
                "mode": "none",
                "host": "localhost",
                "port": "9050"
            }

        if parent:
            n = len(network.get_interfaces())
            if n:
                status = _("Blockchain") + ": " + "%d " % (
                    network.get_local_height()) + _("blocks") + ".\n" + _(
                        "Getting block headers from %d nodes.") % n
            else:
                status = _("Not connected")
            if network.is_connected():
                status += "\n" + _("Server") + ": %s" % (host)
            else:
                status += "\n" + _("Disconnected from server")
        else:
            status = _("Please choose a server.") + "\n" + _(
                "Select 'Cancel' if you are offline.")

        vbox = QVBoxLayout()
        vbox.setSpacing(30)
        hbox = QHBoxLayout()
        l = QLabel()
        l.setPixmap(QPixmap(":icons/network.png"))
        hbox.addStretch(10)
        hbox.addWidget(l)
        hbox.addWidget(QLabel(status))
        hbox.addStretch(50)
        msg = _("Electrum-BOLI sends your wallet addresses to a single server, in order to receive your transaction history.") + "\n\n" \
            + _("In addition, Electrum-BOLI connects to several nodes in order to download block headers and find out the longest blockchain.") + " " \
            + _("This blockchain is used to verify the transactions sent by the address server.")
        hbox.addWidget(HelpButton(msg))
        vbox.addLayout(hbox)

        # grid layout
        grid = QGridLayout()
        grid.setSpacing(8)
        vbox.addLayout(grid)

        # server
        self.server_host = QLineEdit()
        self.server_host.setFixedWidth(200)
        self.server_port = QLineEdit()
        self.server_port.setFixedWidth(60)
        grid.addWidget(QLabel(_('Server') + ':'), 0, 0)

        # use SSL
        self.ssl_cb = QCheckBox(_('Use SSL'))
        self.ssl_cb.setChecked(auto_connect)
        grid.addWidget(self.ssl_cb, 3, 1)
        self.ssl_cb.stateChanged.connect(self.change_protocol)

        # auto connect
        self.autoconnect_cb = QCheckBox(_('Auto-connect'))
        self.autoconnect_cb.setChecked(auto_connect)
        grid.addWidget(self.autoconnect_cb, 0, 1)
        self.autoconnect_cb.setEnabled(
            self.config.is_modifiable('auto_connect'))
        msg = _("If auto-connect is enabled, Electrum-BOLI will always use a server that is on the longest blockchain.") + " " \
            + _("If it is disabled, Electrum-BOLI will warn you if your server is lagging.")
        grid.addWidget(HelpButton(msg), 0, 4)
        grid.addWidget(self.server_host, 0, 2, 1, 2)
        grid.addWidget(self.server_port, 0, 3)

        label = _('Active Servers') if network.is_connected() else _(
            'Default Servers')
        self.servers_list_widget = QTreeWidget(parent)
        self.servers_list_widget.setHeaderLabels([label, _('Limit')])
        self.servers_list_widget.setMaximumHeight(150)
        self.servers_list_widget.setColumnWidth(0, 240)

        self.change_server(host, protocol)
        self.set_protocol(protocol)

        self.servers_list_widget.connect(
            self.servers_list_widget,
            SIGNAL('currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            lambda x, y: self.server_changed(x))
        grid.addWidget(self.servers_list_widget, 1, 1, 1, 3)

        def enable_set_server():
            if config.is_modifiable('server'):
                enabled = not self.autoconnect_cb.isChecked()
                self.server_host.setEnabled(enabled)
                self.server_port.setEnabled(enabled)
                self.servers_list_widget.setEnabled(enabled)
            else:
                for w in [
                        self.autoconnect_cb, self.server_host,
                        self.server_port, self.ssl_cb, self.servers_list_widget
                ]:
                    w.setEnabled(False)

        self.autoconnect_cb.clicked.connect(enable_set_server)
        enable_set_server()

        # proxy setting
        self.proxy_mode = QComboBox()
        self.proxy_host = QLineEdit()
        self.proxy_host.setFixedWidth(200)
        self.proxy_port = QLineEdit()
        self.proxy_port.setFixedWidth(60)
        self.proxy_mode.addItems(['NONE', 'SOCKS4', 'SOCKS5', 'HTTP'])

        def check_for_disable(index=False):
            if self.config.is_modifiable('proxy'):
                if self.proxy_mode.currentText() != 'NONE':
                    self.proxy_host.setEnabled(True)
                    self.proxy_port.setEnabled(True)
                else:
                    self.proxy_host.setEnabled(False)
                    self.proxy_port.setEnabled(False)
            else:
                for w in [self.proxy_host, self.proxy_port, self.proxy_mode]:
                    w.setEnabled(False)

        check_for_disable()
        self.proxy_mode.connect(self.proxy_mode,
                                SIGNAL('currentIndexChanged(int)'),
                                check_for_disable)
        self.proxy_mode.setCurrentIndex(
            self.proxy_mode.findText(str(proxy_config.get("mode").upper())))
        self.proxy_host.setText(proxy_config.get("host"))
        self.proxy_port.setText(proxy_config.get("port"))

        grid.addWidget(QLabel(_('Proxy') + ':'), 4, 0)
        grid.addWidget(self.proxy_mode, 4, 1)
        grid.addWidget(self.proxy_host, 4, 2)
        grid.addWidget(self.proxy_port, 4, 3)

        # buttons
        vbox.addLayout(Buttons(CancelButton(self), OkButton(self)))
        self.setLayout(vbox)
예제 #45
0
 def done_processing(self):
     QMessageBox.information(None, _("Labels synchronised"), _("Your labels have been synchronised."))
예제 #46
0
 def __init__(self, parent=None):
     MyTreeWidget.__init__(self, parent, self.create_menu, [ '', _('Date'), _('Description') , _('Amount'), _('Balance')], 2)
     self.config = self.parent.config
     self.setSortingEnabled(False)
 def copy_to_clipboard():
     bmp.save_qrcode(qrw.qr, filename)
     QApplication.clipboard().setImage(QImage(filename))
     QMessageBox.information(None, _('Message'), _("QR code saved to clipboard"), _('OK'))
예제 #48
0
 def __init__(self, text_getter, app):
     QPushButton.__init__(self, _("Copy"))
     self.clicked.connect(lambda: app.clipboard().setText(text_getter()))
예제 #49
0
 def settings_widget(self, window):
     return EnterButton(_('Settings'), self.settings_dialog)
    def settings_dialog(self):
        d = QDialog()
        d.setWindowTitle("Settings")
        layout = QGridLayout(d)
        layout.addWidget(QLabel(_('Exchange rate API: ')), 0, 0)
        layout.addWidget(QLabel(_('Currency: ')), 1, 0)
        layout.addWidget(QLabel(_('History Rates: ')), 2, 0)
        combo = QComboBox()
        combo_ex = QComboBox()
        hist_checkbox = QCheckBox()
        hist_checkbox.setEnabled(False)
        hist_checkbox.setChecked(
            self.config.get('history_rates', 'unchecked') != 'unchecked')
        ok_button = QPushButton(_("OK"))

        def on_change(x):
            try:
                cur_request = str(self.currencies[x])
            except Exception:
                return
            if cur_request != self.fiat_unit():
                self.config.set_key('currency', cur_request, True)
                cur_exchange = self.config.get('use_exchange', "Blockchain")
                if (cur_exchange, cur_request) in EXCH_SUPPORT_HIST:
                    hist_checkbox.setEnabled(True)
                else:
                    disable_check()
                self.win.update_status()
                try:
                    self.fiat_button
                except:
                    pass
                else:
                    self.fiat_button.setText(cur_request)

        def disable_check():
            hist_checkbox.setChecked(False)
            hist_checkbox.setEnabled(False)

        def on_change_ex(x):
            cur_request = str(self.exchanges[x])
            if cur_request != self.config.get('use_exchange', "Blockchain"):
                self.config.set_key('use_exchange', cur_request, True)
                self.currencies = []
                combo.clear()
                self.exchanger.query_rates.set()
                cur_currency = self.fiat_unit()
                if (cur_request, cur_currency) in EXCH_SUPPORT_HIST:
                    hist_checkbox.setEnabled(True)
                else:
                    disable_check()
                set_currencies(combo)
                self.win.update_status()

        def on_change_hist(checked):
            if checked:
                self.config.set_key('history_rates', 'checked')
                self.request_history_rates()
            else:
                self.config.set_key('history_rates', 'unchecked')
                self.win.history_list.setHeaderLabels([
                    '',
                    _('Date'),
                    _('Description'),
                    _('Amount'),
                    _('Balance')
                ])
                self.win.history_list.setColumnCount(5)

        def set_hist_check(hist_checkbox):
            cur_exchange = self.config.get('use_exchange', "Blockchain")
            hist_checkbox.setEnabled(
                cur_exchange in ["CoinDesk", "Winkdex", "BitcoinVenezuela"])

        def set_currencies(combo):
            try:
                combo.blockSignals(True)
                current_currency = self.fiat_unit()
                combo.clear()
            except Exception:
                return
            combo.addItems(self.currencies)
            try:
                index = self.currencies.index(current_currency)
            except Exception:
                index = 0
            combo.blockSignals(False)
            combo.setCurrentIndex(index)

        def set_exchanges(combo_ex):
            try:
                combo_ex.clear()
            except Exception:
                return
            combo_ex.addItems(self.exchanges)
            try:
                index = self.exchanges.index(
                    self.config.get('use_exchange', "Blockchain"))
            except Exception:
                index = 0
            combo_ex.setCurrentIndex(index)

        def ok_clicked():
            if self.config.get('use_exchange',
                               "Blockchain") in ["CoinDesk", "itBit"]:
                self.exchanger.query_rates.set()
            d.accept()

        set_exchanges(combo_ex)
        set_currencies(combo)
        set_hist_check(hist_checkbox)
        combo.currentIndexChanged.connect(on_change)
        combo_ex.currentIndexChanged.connect(on_change_ex)
        hist_checkbox.stateChanged.connect(on_change_hist)
        combo.connect(self.win, SIGNAL('refresh_currencies_combo()'),
                      lambda: set_currencies(combo))
        combo_ex.connect(d, SIGNAL('refresh_exchanges_combo()'),
                         lambda: set_exchanges(combo_ex))
        ok_button.clicked.connect(lambda: ok_clicked())
        layout.addWidget(combo, 1, 1)
        layout.addWidget(combo_ex, 0, 1)
        layout.addWidget(hist_checkbox, 2, 1)
        layout.addWidget(ok_button, 3, 1)

        if d.exec_():
            return True
        else:
            return False
예제 #51
0
def question(msg):
    return QMessageBox.question(None, _('Message'), msg,
                                QMessageBox.Yes | QMessageBox.No,
                                QMessageBox.No) == QMessageBox.Yes
예제 #52
0
 def description(self):
     return _("Send and receive payment requests via email")
 def print_qr():
     bmp.save_qrcode(qrw.qr, filename)
     QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))