Exemple #1
0
    def test_is_valid_address(self):
        for priv_details in self.priv_pub_addr:
            addr = priv_details['address']
            self.assertFalse(is_address(priv_details['priv']))
            self.assertFalse(is_address(priv_details['pub']))
            self.assertTrue(is_address(addr))

            is_enc_b58 = priv_details['addr_encoding'] == 'base58'
            self.assertEqual(is_enc_b58, is_b58_address(addr))

            is_enc_bech32 = priv_details['addr_encoding'] == 'bech32'
            self.assertEqual(is_enc_bech32, is_segwit_address(addr))

        self.assertFalse(is_address("not an address"))
Exemple #2
0
 def do_send(self):
     if self.screen.is_pr:
         if self.payment_request.has_expired():
             self.app.show_error(_('Payment request has expired'))
             return
         outputs = self.payment_request.get_outputs()
     else:
         address = str(self.screen.address)
         if not address:
             self.app.show_error(_('Recipient not specified.') + ' ' + _('Please scan a Bitcoin address or a payment request'))
             return
         if not bitcoin.is_address(address):
             self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + address)
             return
         try:
             amount = self.app.get_amount(self.screen.amount)
         except:
             self.app.show_error(_('Invalid amount') + ':\n' + self.screen.amount)
             return
         outputs = [(bitcoin.TYPE_ADDRESS, address, amount)]
     message = unicode(self.screen.message)
     amount = sum(map(lambda x:x[2], outputs))
     if self.app.electrum_config.get('use_rbf'):
         from dialogs.question import Question
         d = Question(_('Should this transaction be replaceable?'), lambda b: self._do_send(amount, message, outputs, b))
         d.open()
     else:
         self._do_send(amount, message, outputs, False)
Exemple #3
0
    def do_send(self):
        app = App.get_running_app()
        screen_send = app.root.main_screen.ids.tabs.ids.screen_send
        scrn = screen_send.ids
        label = unicode(scrn.message_e.text)
        r = unicode(scrn.payto_e.text).strip()
        # label or alias, with address in brackets
        global re
        if not re:
            import re
        m = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", r)
        to_address = m.group(2) if m else r

        if not bitcoin.is_address(to_address):
            app.show_error(_("Invalid Bitcoin Address") + ":\n" + to_address)
            return

        amount = self.get_amount(scrn.amount_e.text)

        fee = scrn.fee_e.amt
        if not fee:
            app.show_error(_("Invalid Fee"))
            return

        # from pudb import set_trace; set_trace()
        # Unused
        # message = 'sending {} {} to {}'.format(app.base_unit, scrn.amount_e.text, r)

        # assume no password and fee is None
        password = None
        fee = None
        self.send_tx([("address", to_address, amount)], fee, label, password)
 def place_text_on_clipboard(self, text):
     if is_address(text):
         try:
             self.wallet.check_address(text)
         except InternalAddressCorruption as e:
             self.parent.show_error(str(e))
             raise
     self.parent.app.clipboard().setText(text)
Exemple #5
0
    def create_menu(self, position):
        from electrum.wallet import Multisig_Wallet
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selectedItems()
        multi_select = len(selected) > 1
        addrs = [unicode(item.text(0)) for item in selected]
        if not addrs:
            return
        if not multi_select:
            item = self.itemAt(position)
            col = self.currentColumn()
            if not item:
                return
            addr = addrs[0]
            if not is_address(addr):
                k = str(item.data(0,32).toString())
                if k:
                    self.create_account_menu(position, k, item)
                else:
                    item.setExpanded(not item.isExpanded())
                return

        menu = QMenu()
        if not multi_select:
            column_title = self.headerItem().text(col)
            menu.addAction(_("Copy %s")%column_title, lambda: self.parent.app.clipboard().setText(item.text(col)))
            if col in self.editable_columns:
                menu.addAction(_("Edit %s")%column_title, lambda: self.editItem(item, col))
            menu.addAction(_("Request payment"), lambda: self.parent.receive_at(addr))
            menu.addAction(_('History'), lambda: self.parent.show_address(addr))
            menu.addAction(_('Public Keys'), lambda: self.parent.show_public_keys(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"), lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"), lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"), lambda: self.parent.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"), lambda: self.parent.remove_address(addr))
            addr_URL = block_explorer_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"), lambda: webbrowser.open(addr_URL))

        if any(not self.wallet.is_frozen(addr) for addr in addrs):
            menu.addAction(_("Freeze"), lambda: self.parent.set_frozen_state(addrs, True))
        if any(self.wallet.is_frozen(addr) for addr in addrs):
            menu.addAction(_("Unfreeze"), lambda: self.parent.set_frozen_state(addrs, False))

        def can_send(addr):
            return not self.wallet.is_frozen(addr) and sum(self.wallet.get_addr_balance(addr)[:2])
        if any(can_send(addr) for addr in addrs):
            menu.addAction(_("Send From"), lambda: self.parent.send_from_addresses(addrs))

        run_hook('receive_menu', menu, addrs, self.wallet)
        menu.exec_(self.viewport().mapToGlobal(position))
Exemple #6
0
 def show_address_helper(self, wallet, address, keystore=None):
     if keystore is None:
         keystore = wallet.get_keystore()
     if not is_address(address):
         keystore.handler.show_error(_('Invalid Bitcoin Address'))
         return False
     if not wallet.is_mine(address):
         keystore.handler.show_error(_('Address not in wallet.'))
         return False
     if type(keystore) != self.keystore_class:
         return False
     return True
Exemple #7
0
    def do_send(self):
        if not is_address(self.str_recipient):
            print(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx(outputs=[
                PartialTxOutput.from_address_and_value(self.str_recipient,
                                                       amount)
            ],
                                  password=password,
                                  fee=fee)
        except Exception as e:
            print(repr(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        print(_("Please wait..."))
        try:
            self.network.run_from_another_thread(
                self.network.broadcast_transaction(tx))
        except TxBroadcastError as e:
            msg = e.get_message_for_gui()
            print(msg)
        except BestEffortRequestFailed as e:
            msg = repr(e)
            print(msg)
        else:
            print(_('Payment sent.'))
Exemple #8
0
 def show_address_helper(self, wallet, address, keystore=None):
     if keystore is None:
         keystore = wallet.get_keystore()
     if not is_address(address):
         keystore.handler.show_error(_('Invalid Bitcoin Address'))
         return False
     if not wallet.is_mine(address):
         keystore.handler.show_error(_('Address not in wallet.'))
         return False
     if type(keystore) != self.keystore_class:
         return False
     return True
Exemple #9
0
 def do_send(self):
     if self.screen.is_pr:
         if self.payment_request.has_expired():
             self.app.show_error(_('Payment request has expired'))
             return
         outputs = self.payment_request.get_outputs()
     else:
         address = str(self.screen.address)
         if not address:
             self.app.show_error(
                 _('Recipient not specified.') + ' ' +
                 _('Please scan a Bitcoin address or a payment request'))
             return
         if not bitcoin.is_address(address):
             self.app.show_error(
                 _('Invalid Bitcoin Address') + ':\n' + address)
             return
         try:
             amount = self.app.get_amount(self.screen.amount)
         except:
             self.app.show_error(
                 _('Invalid amount') + ':\n' + self.screen.amount)
             return
         outputs = [(bitcoin.TYPE_ADDRESS, address, amount)]
     message = unicode(self.screen.message)
     amount = sum(map(lambda x: x[2], outputs))
     # make unsigned transaction
     coins = self.app.wallet.get_spendable_coins()
     config = self.app.electrum_config
     try:
         tx = self.app.wallet.make_unsigned_transaction(
             coins, outputs, config, None)
     except NotEnoughFunds:
         self.app.show_error(_("Not enough funds"))
         return
     except Exception as e:
         traceback.print_exc(file=sys.stdout)
         self.app.show_error(str(e))
         return
     if self.app.electrum_config.get('use_rbf'):
         tx.set_sequence(0)
     fee = tx.get_fee()
     msg = [
         _("Amount to be sent") + ": " +
         self.app.format_amount_and_units(amount),
         _("Mining fee") + ": " + self.app.format_amount_and_units(fee),
     ]
     if fee >= config.get('confirm_fee', 100000):
         msg.append(
             _('Warning') + ': ' +
             _("The fee for this transaction seems unusually high."))
     msg.append(_("Enter your PIN code to proceed"))
     self.app.protected('\n'.join(msg), self.send_tx, (tx, message))
Exemple #10
0
    def create_menu(self, position):
        from electrum.wallet import Multisig_Wallet
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selectedItems()
        multi_select = len(selected) > 1
        addrs = [item.text(0) for item in selected]
        if not addrs:
            return
        if not multi_select:
            item = self.itemAt(position)
            col = self.currentColumn()
            if not item:
                return
            addr = addrs[0]
            if not is_address(addr):
                item.setExpanded(not item.isExpanded())
                return

        menu = QMenu()
        if not multi_select:
            column_title = self.headerItem().text(col)
            copy_text = item.text(col)
            menu.addAction(_("Copy %s") % column_title, lambda: self.parent.app.clipboard().setText(copy_text))
            menu.addAction(_('Details'), lambda: self.parent.show_address(addr))
            if col in self.editable_columns:
                menu.addAction(_("Edit %s") % column_title, lambda: self.editItem(item, col))
            menu.addAction(_("Request payment"), lambda: self.parent.receive_at(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"), lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"), lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"), lambda: self.parent.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"), lambda: self.parent.remove_address(addr))
            addr_URL = block_explorer_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"), lambda: webbrowser.open(addr_URL))

            if not self.wallet.is_frozen(addr):
                menu.addAction(_("Freeze"), lambda: self.parent.set_frozen_state([addr], True))
            else:
                menu.addAction(_("Unfreeze"), lambda: self.parent.set_frozen_state([addr], False))

        coins = self.wallet.get_utxos(addrs)
        if coins:
            menu.addAction(_("Spend from"), lambda: self.parent.spend_coins(coins))

        run_hook('receive_menu', menu, addrs, self.wallet)
        menu.exec_(self.viewport().mapToGlobal(position))
Exemple #11
0
 def do_send(self):
     address = str(self.screen.address)
     if not bitcoin.is_address(address):
         self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + address)
         return
     try:
         amount = self.app.get_amount(self.screen.amount)
     except:
         self.app.show_error(_('Invalid amount') + ':\n' + self.screen.amount)
         return
     message = unicode(self.screen.message)
     fee = None
     outputs = [('address', address, amount)]
     self.app.protected(self.send_tx, (outputs, fee, message))
Exemple #12
0
    def create_menu(self, position):
        from electrum.wallet import Multisig_Wallet
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selectedItems()
        multi_select = len(selected) > 1
        addrs = [item.text(1) for item in selected]
        if not addrs:
            return
        if not multi_select:
            item = self.itemAt(position)
            col = self.currentColumn()
            if not item:
                return
            addr = addrs[0]
            if not is_address(addr):
                item.setExpanded(not item.isExpanded())
                return

        menu = QMenu()
        if not multi_select:
            column_title = self.headerItem().text(col)
            copy_text = item.text(col)
            menu.addAction(_("Copy {}").format(column_title), lambda: self.parent.app.clipboard().setText(copy_text))
            menu.addAction(_('Details'), lambda: self.parent.show_address(addr))
            if col in self.editable_columns:
                menu.addAction(_("Edit {}").format(column_title), lambda: self.editItem(item, col))
            menu.addAction(_("Request payment"), lambda: self.parent.receive_at(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"), lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"), lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"), lambda: self.parent.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"), lambda: self.parent.remove_address(addr))
            addr_URL = block_explorer_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"), lambda: webbrowser.open(addr_URL))

            if not self.wallet.is_frozen(addr):
                menu.addAction(_("Freeze"), lambda: self.parent.set_frozen_state([addr], True))
            else:
                menu.addAction(_("Unfreeze"), lambda: self.parent.set_frozen_state([addr], False))

        coins = self.wallet.get_utxos(addrs)
        if coins:
            menu.addAction(_("Spend from"), lambda: self.parent.spend_coins(coins))

        run_hook('receive_menu', menu, addrs, self.wallet)
        menu.exec_(self.viewport().mapToGlobal(position))
Exemple #13
0
 def _resolve_openalias(self, text: str) -> Optional[dict]:
     key = text
     key = key.strip()  # strip whitespaces
     if not (('.' in key) and ('<' not in key) and (' ' not in key)):
         return None
     parts = key.split(sep=',')  # assuming single line
     if parts and len(parts) > 0 and bitcoin.is_address(parts[0]):
         return None
     try:
         data = self.win.contacts.resolve(key)
     except Exception as e:
         self.logger.info(f'error resolving address/alias: {repr(e)}')
         return None
     return data or None
Exemple #14
0
    def do_send(self):
        if not is_address(self.str_recipient):
            print(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx(
                [TxOutput(TYPE_ADDRESS, self.str_recipient, amount)], password,
                self.config, fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        print(_("Please wait..."))
        try:
            self.network.run_from_another_thread(
                self.network.broadcast_transaction(tx))
        except Exception as e:
            display_msg = _(
                'The server returned an error when broadcasting the transaction.'
            )
            display_msg += '\n' + repr(e)
            print(display_msg)
        else:
            print(_('Payment sent.'))
Exemple #15
0
    def test_is_address_bad_checksums(self):
        self.assertTrue(is_address('1819s5TxxbBtuRPr3qYskMVC8sb1pqapWx'))
        self.assertFalse(is_address('1819s5TxxbBtuRPr3qYskMVC8sb1pqapWw'))

        self.assertTrue(is_address('3LrjLVnngqnaJeo3BQwMBg34iqYsjZjQUe'))
        self.assertFalse(is_address('3LrjLVnngqnaJeo3BQwMBg34iqYsjZjQUd'))

        self.assertTrue(is_address('bc1qxq64lrwt02hm7tu25lr3hm9tgzh58snfe67yt6'))
        self.assertFalse(is_address('bc1qxq64lrwt02hm7tu25lr3hm9tgzh58snfe67yt5'))
Exemple #16
0
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(
                _('Invalid {name} address').format(name=constants.net.NAME))
            return
        try:
            amount = int(Decimal(self.str_amount) * constants.net.COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * constants.net.COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx(outputs=[
                PartialTxOutput.from_address_and_value(self.str_recipient,
                                                       amount)
            ],
                                  password=password,
                                  fee=fee)
        except Exception as e:
            self.show_message(repr(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        try:
            self.network.run_from_another_thread(
                self.network.broadcast_transaction(tx))
        except TxBroadcastError as e:
            msg = e.get_message_for_gui()
            self.show_message(msg)
        except BestEffortRequestFailed as e:
            msg = repr(e)
            self.show_message(msg)
        else:
            self.show_message(_('Payment sent.'))
            self.do_clear()
Exemple #17
0
    def do_send(self):
        if not is_address(self.str_recipient):
            print(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx(
                [TxOutput(TYPE_ADDRESS, self.str_recipient, amount)], password,
                self.config, fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        print(_("Please wait..."))
        status, msg = self.network.run_from_another_thread(
            self.network.broadcast_transaction(tx))

        if status:
            print(_('Payment sent.'))
            #self.do_clear()
            #self.update_contacts_tab()
        else:
            print(_('Error'))
Exemple #18
0
 def reader_didScanResult_(self, reader, result) -> None:
     utils.NSLog("Reader data = '%s'", str(result))
     result = cleanup_address_remove_colon(result)
     if not is_address(result):
         title = _("Invalid QR Code")
         message = _("The QR code does not appear to be a valid BTC address.\nPlease try again.")
         reader.stopScanning()
         gui.ElectrumGui.gui.show_error(
             title=title,
             message=message,
             onOk=lambda: reader.startScanning(),
             vc=self.qrvc
         )
     else:
         self.address.text = result
         self.readerDidCancel_(reader)
Exemple #19
0
    def read_send_tab(self, label, payToText, amountText):
        if self.payment_request and self.payment_request.has_expired():
            self.show_error(_('Payment request has expired'))
            return
        

        self.amount_e = BTCAmountEdit(self.get_decimal_point, text=amountText)
        self.payto_e = PayToEdit(self, payToText)
        
        if self.payment_request:
            outputs = self.payment_request.get_outputs()
        else:
            errors = self.payto_e.get_errors()
            if errors:
                self.show_warning(_("Invalid Lines found:") + "\n\n" + '\n'.join([ _("Line #") + str(x[0]+1) + ": " + x[1] for x in errors]))
                return
            outputs = self.payto_e.get_outputs(self.is_max)

            if self.payto_e.is_alias and self.payto_e.validated is False:
                print('Unimplemented')
                '''
                alias = self.payto_e.toPlainText()
                msg = _('WARNING: the alias "{}" could not be validated via an additional '
                        'security check, DNSSEC, and thus may not be correct.').format(alias) + '\n'
                msg += _('Do you wish to continue?')
                if not self.question(msg):
                '''
                return

        if not outputs:
            self.show_error(_('No outputs'))
            return

        for _type, addr, amount in outputs:
            if addr is None:
                self.show_error(_('Bitcoin Address is None'))
                return
            if _type == TYPE_ADDRESS and not bitcoin.is_address(addr):
                self.show_error(_('Invalid Bitcoin Address'))
                return
            if amount is None:
                self.show_error(_('Invalid Amount'))
                return

        fee_estimator = None#self.get_send_fee_estimator()
        coins = self.get_coins()
        return outputs, fee_estimator, label, coins
Exemple #20
0
    def test_is_address_bad_checksums(self):
        self.assertTrue(is_address('VHfNngL8fDdE9m9umCsBh8YGCBd3YKBfm1'))
        self.assertFalse(is_address('VHfNngL8fDdE9m9umCsBh8YGCBd3YKBfm0'))

        self.assertTrue(is_address('MT4sePCkdxe17A4wHHvh1KHU3Y9KjZbpsQ'))
        self.assertFalse(is_address('MT4sePCkdxe17A4wHHvh1KHU3Y9KjZbpsP'))

        self.assertTrue(
            is_address('vips1qxq64lrwt02hm7tu25lr3hm9tgzh58snf7cllvl'))
        self.assertFalse(
            is_address('vips1qxq64lrwt02hm7tu25lr3hm9tgzh58snf7cllvk'))
Exemple #21
0
def make_new_contact():
    code = droid.scanBarcode()
    r = code.result
    if r:
        data = str(r['extras']['SCAN_RESULT']).strip()
        if data:
            if re.match('^bitcoin:', data):
                address, _, _, _, _ = util.parse_URI(data)
            elif is_address(data):
                address = data
            else:
                address = None
            if address:
                if modal_question('Add to contacts?', address):
                    wallet.add_contact(address)
        else:
            modal_dialog('Invalid address', data)
Exemple #22
0
    def resolve(self):
        self.is_alias = False
        if self.hasFocus():
            return
        if self.is_multiline():  # only supports single line entries atm
            return
        if self.is_pr:
            return
        key = str(self.toPlainText())
        key = key.strip()  # strip whitespaces
        if key == self.previous_payto:
            return
        self.previous_payto = key
        if not (('.' in key) and (not '<' in key) and (not ' ' in key)):
            return
        parts = key.split(sep=',')  # assuming single line
        if parts and len(parts) > 0 and bitcoin.is_address(parts[0]):
            return
        try:
            data = self.win.contacts.resolve(key)
        except Exception as e:
            self.logger.info(f'error resolving address/alias: {repr(e)}')
            return
        if not data:
            return
        self.is_alias = True

        address = data.get('address')
        name = data.get('name')
        new_url = key + ' <' + address + '>'
        self.setText(new_url)
        self.previous_payto = new_url

        #if self.win.config.get('openalias_autoadd') == 'checked':
        self.win.contacts[key] = ('openalias', name)
        self.win.contact_list.update()

        self.setFrozen(True)
        if data.get('type') == 'openalias':
            self.validated = data.get('validated')
            if self.validated:
                self.setGreen()
            else:
                self.setExpired()
        else:
            self.validated = None
Exemple #23
0
    def resolve(self):
        self.is_alias = False
        if self.hasFocus():
            return
        if self.is_multiline():  # only supports single line entries atm
            return
        if self.is_pr:
            return
        key = str(self.toPlainText())
        key = key.strip()  # strip whitespaces
        if key == self.previous_payto:
            return
        self.previous_payto = key
        if not (('.' in key) and (not '<' in key) and (not ' ' in key)):
            return
        parts = key.split(sep=',')  # assuming single line
        if parts and len(parts) > 0 and bitcoin.is_address(parts[0]):
            return
        try:
            data = self.win.contacts.resolve(key)
        except Exception as e:
            self.print_error(f'error resolving address/alias: {repr(e)}')
            return
        if not data:
            return
        self.is_alias = True

        address = data.get('address')
        name = data.get('name')
        new_url = key + ' <' + address + '>'
        self.setText(new_url)
        self.previous_payto = new_url

        #if self.win.config.get('openalias_autoadd') == 'checked':
        self.win.contacts[key] = ('openalias', name)
        self.win.contact_list.update()

        self.setFrozen(True)
        if data.get('type') == 'openalias':
            self.validated = data.get('validated')
            if self.validated:
                self.setGreen()
            else:
                self.setExpired()
        else:
            self.validated = None
Exemple #24
0
    def do_send(self):
        if not is_address(self.str_recipient):
            print(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx([TxOutput(TYPE_ADDRESS, self.str_recipient, amount)],
                                  password, self.config, fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        print(_("Please wait..."))
        status, msg = self.network.broadcast_transaction(tx)

        if status:
            print(_('Payment sent.'))
            #self.do_clear()
            #self.update_contacts_tab()
        else:
            print(_('Error'))
Exemple #25
0
def make_new_contact():
    code = droid.scanBarcode()
    r = code.result
    if r:
        data = str(r['extras']['SCAN_RESULT']).strip()
        if data:
            if re.match('^bitcoin:', data):
                address, _, _, _, _ = util.parse_URI(data)
            elif is_address(data):
                address = data
            else:
                address = None
            if address:
                if modal_question('Add to contacts?', address):
                    wallet.add_contact(address)
        else:
            modal_dialog('Invalid address', data)
Exemple #26
0
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid VIPSTARCOIN address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx(
                [TxOutput(TYPE_ADDRESS, self.str_recipient, amount)], password,
                self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.hash()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        status, msg = self.network.broadcast_transaction(tx)

        if status:
            self.show_message(_('Payment sent.'))
            self.do_clear()
            #self.update_contacts_tab()
        else:
            display_msg = _(
                'The server returned an error when broadcasting the transaction.'
            )
            display_msg += '\n' + str(msg)
            self.show_message(display_msg)
Exemple #27
0
 def do_send(self):
     if self.screen.is_pr:
         if self.payment_request.has_expired():
             self.app.show_error(_('Payment request has expired'))
             return
         outputs = self.payment_request.get_outputs()
     else:
         address = str(self.screen.address)
         if not address:
             self.app.show_error(_('Recipient not specified.') + ' ' + _('Please scan a Bitcoin address or a payment request'))
             return
         if not bitcoin.is_address(address):
             self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + address)
             return
         try:
             amount = self.app.get_amount(self.screen.amount)
         except:
             self.app.show_error(_('Invalid amount') + ':\n' + self.screen.amount)
             return
         outputs = [(bitcoin.TYPE_ADDRESS, address, amount)]
     message = unicode(self.screen.message)
     amount = sum(map(lambda x:x[2], outputs))
     # make unsigned transaction
     coins = self.app.wallet.get_spendable_coins()
     config = self.app.electrum_config
     try:
         tx = self.app.wallet.make_unsigned_transaction(coins, outputs, config, None)
     except NotEnoughFunds:
         self.app.show_error(_("Not enough funds"))
         return
     except Exception as e:
         traceback.print_exc(file=sys.stdout)
         self.app.show_error(str(e))
         return
     if self.app.electrum_config.get('use_rbf'):
         tx.set_sequence(0)
     fee = tx.get_fee()
     msg = [
         _("Amount to be sent") + ": " + self.app.format_amount_and_units(amount),
         _("Mining fee") + ": " + self.app.format_amount_and_units(fee),
     ]
     if fee >= config.get('confirm_fee', 100000):
         msg.append(_('Warning')+ ': ' + _("The fee for this transaction seems unusually high."))
     msg.append(_("Enter your PIN code to proceed"))
     self.app.protected('\n'.join(msg), self.send_tx, (tx, message))
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid Omotenashicoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx(
                [TxOutput(TYPE_ADDRESS, self.str_recipient, amount)], password,
                self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        try:
            self.network.run_from_another_thread(
                self.network.broadcast_transaction(tx))
        except TxBroadcastError as e:
            msg = e.get_message_for_gui()
            self.show_message(msg)
        except BestEffortRequestFailed as e:
            msg = repr(e)
            self.show_message(msg)
        else:
            self.show_message(_('Payment sent.'))
            self.do_clear()
Exemple #29
0
 def doReloadForKey(self, key: Any) -> Any:
     t0 = time.time()
     hist = list()
     unk = False
     duped = ''
     if isinstance(key, (type(None), list)):
         # the common case, 'None' or [Address]
         hist = get_history(domain=key)
     # contacts entires store history entries within themselves.. so just return that
     elif isinstance(key, contacts.ContactsEntry):
         hist = contacts.build_contact_tx_list(
             key.address
         )  # force refresh of tx's from wallet -- this will call us again with 'None'
     elif isinstance(key, str):
         # support for string addresses or tx_hashes.. detect which and act accordingly
         if is_address(key):
             hist = self.get(
                 [key]
             )  # recursively call self with propery list data type, which will end up calling get_history (it's ok -- this is to cache results uniformly!)
             duped = ' (duped) '
         elif gui.ElectrumGui.gui.wallet and gui.ElectrumGui.gui.wallet.transactions.get(
                 key, None):
             fullHist = self.get(
                 None
             )  # recursively call self to get a full history (will be cached so it's ok!)
             for hentry in fullHist:
                 if hentry.tx_hash == key:
                     hist.append(hentry)
                     break
         else:
             unk = True
     else:
         unk = True
     dstr = str(key) if not isinstance(
         key, contacts.ContactsEntry
     ) else '[ContactsEntry: ' + key.address_str + ']'
     if unk:
         utils.NSLog(
             "HistoryMgr: failed to retrieve any data for unknown domain=%s, returning empty list",
             dstr[:80])
     else:
         utils.NSLog(
             "HistoryMgr: refresh %d entries for domain=%s in %f ms%s",
             len(hist), dstr[:80], (time.time() - t0) * 1e3, duped)
     return hist
Exemple #30
0
    def do_send(self):
        if not is_address(self.str_recipient):
            print(_(f'Invalid {constants.net.NAME} address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * constants.net.COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * constants.net.COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx([TxOutput(TYPE_ADDRESS, self.str_recipient, amount)],
                                  password, self.config, fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        print(_("Please wait..."))
        try:
            self.network.run_from_another_thread(self.network.broadcast_transaction(tx))
        except Exception as e:
            print(repr(e))
        else:
            print(_('Payment sent.'))
Exemple #31
0
def make_new_contact():
    code = droid.scanBarcode()
    r = code.result
    if r:
        data = str(r["extras"]["SCAN_RESULT"]).strip()
        if data:
            if re.match("^bitcoin:", data):
                out = util.parse_URI(data)
                address = out.get("address")
            elif is_address(data):
                address = data
            else:
                address = None
            if address:
                if modal_question("Add to contacts?", address):
                    # fixme: ask for key
                    contacts[address] = ("address", address)
        else:
            modal_dialog("Invalid address", data)
Exemple #32
0
 def address_changed(self, addr):
     if not addr :
         self.toggle_refresh()
         return
         
     if not is_address(addr) :
         return
         
     self.voter_ls = []
     ret_ls = []
     try :
         ret_ls = self.parent.network.synchronous_get(('blockchain.address.listvoteddelegates', [addr]))
     except BaseException as e:
         self.print_error("error: " + str(e))
     for item in ret_ls :
         self.print_error("error: " + item.get('voter'))
         self.voter_ls.append(item)
         
     self.update()
    def do_send(self):
        app = App.get_running_app()
        screen_send = app.root.main_screen.ids.tabs.ids.screen_send
        scrn = screen_send.ids
        label = unicode(scrn.message_e.text)

        r = unicode(scrn.payto_e.text).strip()

        # label or alias, with address in brackets
        global re
        if not re:
            import re
        m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
        to_address = m.group(2) if m else r

        global bitcoin
        if not bitcoin:
            from electrum import bitcoin

        if not bitcoin.is_address(to_address):
            app.show_error(_('Invalid Bitcoin Address') + ':\n' + to_address)
            return

        amount = scrn.amount_e.text
        fee = scrn.fee_e.amt
        if not fee:
            app.show_error(_('Invalid Fee'))
            return

        from pudb import set_trace
        set_trace()
        message = 'sending {} {} to {}'.format(\
            app.base_unit, scrn.amount_e.text, r)

        confirm_fee = self.config.get('confirm_amount', 100000)
        if fee >= confirm_fee:
            if not self.question(
                    _("The fee for this transaction seems unusually high.\nAre you really sure you want to pay %(fee)s in fees?"
                      ) %
                {'fee': self.format_amount(fee) + ' ' + self.base_unit()}):
                return

        self.send_tx(to_address, amount, fee, label)
Exemple #34
0
def make_new_contact():
    code = droid.scanBarcode()
    r = code.result
    if r:
        data = str(r['extras']['SCAN_RESULT']).strip()
        if data:
            if re.match('^monetaryunit:', data):
                out = util.parse_URI(data)
                address = out.get('address')
            elif is_address(data):
                address = data
            else:
                address = None
            if address:
                if modal_question('Add to contacts?', address):
                    # fixme: ask for key
                    contacts[address] = ('address', address)
        else:
            modal_dialog('Invalid address', data)
def make_new_contact():
    code = droid.scanBarcode()
    r = code.result
    if r:
        data = str(r['extras']['SCAN_RESULT']).strip()
        if data:
            if re.match('^bitcoin:', data):
                out = util.parse_URI(data)
                address = out.get('address')
            elif is_address(data):
                address = data
            else:
                address = None
            if address:
                if modal_question('Add to contacts?', address):
                    # fixme: ask for key
                    contacts[address] = ('address', address)
        else:
            modal_dialog('Invalid address', data)
Exemple #36
0
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx([TxOutput(TYPE_ADDRESS, self.str_recipient, amount)],
                                  password, self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        try:
            self.network.run_from_another_thread(self.network.broadcast_transaction(tx))
        except TxBroadcastError as e:
            msg = e.get_message_for_gui()
            self.show_message(msg)
        except BestEffortRequestFailed as e:
            msg = repr(e)
            self.show_message(msg)
        else:
            self.show_message(_('Payment sent.'))
            self.do_clear()
    def parse_args(self):
        if len(self.senders) > 0:
            sender = self.sender_combo.currentText().strip()
            if sender not in self.senders:
                raise ParseArgsException('invalid sender address')
        else:
            sender = ''
        args_str = f'[{self.args_e.text()}]'.replace("\n", "")
        try:
            args = json.loads(args_str)
        except BaseException as e:
            raise ParseArgsException(f"json decode error {e} for {args_str}")
        abi_index = self.abi_signatures[self.abi_combo.currentIndex()][0]
        if abi_index == -1:
            return None, [], sender
        abi = self.contract['interface'][abi_index]
        inputs = abi.get('inputs', [])
        if not len(args) == len(inputs):
            raise ParseArgsException(
                'invalid input count,expect {} got {}'.format(
                    len(inputs), len(args)))
        for index, _input in enumerate(inputs):
            _type = _input.get('type', '')
            if _type == 'address':
                addr = args[index]
                if is_address(addr):
                    __, hash160 = b58_address_to_hash160(addr)
                    addr = hash160.hex()
                if addr.startswith("0x"):
                    addr = addr[2:]
                if not is_hash160(addr):
                    raise ParseArgsException('invalid input:{}'.format(
                        args[index]))
                args[index] = addr.lower()
            elif 'int' in _type:
                if not isinstance(args[index], int):
                    raise ParseArgsException('inavlid input:{}'.format(
                        args[index]))
            elif _type == 'bytes':
                args[index] = bytes.fromhex(args[index])

        return abi, args, sender
Exemple #38
0
 def read_invoice(self):
     address = str(self.screen.address)
     if not address:
         self.app.show_error(
             _('Recipient not specified.') + ' ' +
             _('Please scan a Bitcoin address or a payment request'))
         return
     if not self.screen.amount:
         self.app.show_error(_('Please enter an amount'))
         return
     try:
         amount = self.app.get_amount(self.screen.amount)
     except:
         self.app.show_error(
             _('Invalid amount') + ':\n' + self.screen.amount)
         return
     message = self.screen.message
     if self.screen.destinationtype == PR_TYPE_LN:
         return {
             'type': PR_TYPE_LN,
             'invoice': address,
             'amount': amount,
             'message': message,
         }
     elif self.screen.destinationtype == PR_TYPE_ADDRESS:
         if not bitcoin.is_address(address):
             self.app.show_error(
                 _('Invalid Bitcoin Address') + ':\n' + address)
             return
         return {
             'type': PR_TYPE_ADDRESS,
             'address': address,
             'amount': amount,
             'message': message,
         }
     elif self.screen.destinationtype == PR_TYPE_BIP70:
         if self.payment_request.has_expired():
             self.app.show_error(_('Payment request has expired'))
             return
         return self.payment_request.get_dict()
     else:
         raise Exception('Unknown invoice type')
Exemple #39
0
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx(
                [TxOutput(TYPE_ADDRESS, self.str_recipient, amount)], password,
                self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        status, msg = self.network.broadcast_transaction_from_non_network_thread(
            tx)

        if status:
            self.show_message(_('Payment sent.'))
            self.do_clear()
            #self.update_contacts_tab()
        else:
            self.show_message(_('Error'))
Exemple #40
0
 def on_qr(self, data):
     from electrum.bitcoin import base_decode, is_address
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('bitcoin:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum.transaction import Transaction
     try:
         text = base_decode(data, None, base=43).encode('hex')
         tx = Transaction(text)
     except:
         tx = None
     if tx:
         self.tx_dialog(tx)
         return
     # show error
     self.show_error("Unable to decode QR data")
Exemple #41
0
 def do_send(self):
     if self.payment_request:
         if self.payment_request.has_expired():
             self.app.show_error(_("Payment request has expired"))
             return
         outputs = self.payment_request.get_outputs()
     else:
         address = str(self.screen.address)
         if not bitcoin.is_address(address):
             self.app.show_error(_("Invalid Bitcoin Address") + ":\n" + address)
             return
         try:
             amount = self.app.get_amount(self.screen.amount)
         except:
             self.app.show_error(_("Invalid amount") + ":\n" + self.screen.amount)
             return
         outputs = [(bitcoin.TYPE_ADDRESS, address, amount)]
     message = unicode(self.screen.message)
     fee = None
     self.app.protected(self.send_tx, (outputs, fee, message))
Exemple #42
0
 def on_qr(self, data):
     from electrum.bitcoin import base_decode, is_address
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('bitcoin:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum.transaction import Transaction
     try:
         text = base_decode(data, None, base=43).encode('hex')
         tx = Transaction(text)
     except:
         tx = None
     if tx:
         self.tx_dialog(tx)
         return
     # show error
     self.show_error("Unable to decode QR data")
Exemple #43
0
 def do_send(self):
     if self.payment_request:
         if self.payment_request.has_expired():
             self.app.show_error(_('Payment request has expired'))
             return
         outputs = self.payment_request.get_outputs()
     else:
         address = str(self.screen.address)
         if not bitcoin.is_address(address):
             self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + address)
             return
         try:
             amount = self.app.get_amount(self.screen.amount)
         except:
             self.app.show_error(_('Invalid amount') + ':\n' + self.screen.amount)
             return
         outputs = [('address', address, amount)]
     message = unicode(self.screen.message)
     fee = None
     self.app.protected(self.send_tx, (outputs, fee, message))
Exemple #44
0
 def read_invoice(self):
     address = str(self.address)
     if not address:
         self.app.show_error(
             _('Recipient not specified.') + ' ' +
             _('Please scan a Bitcoin address or a payment request'))
         return
     if not self.amount:
         self.app.show_error(_('Please enter an amount'))
         return
     if self.is_max:
         amount = '!'
     else:
         try:
             amount = self.app.get_amount(self.amount)
         except:
             self.app.show_error(_('Invalid amount') + ':\n' + self.amount)
             return
     message = self.message
     try:
         if self.is_lightning:
             return LNInvoice.from_bech32(address)
         else:  # on-chain
             if self.payment_request:
                 outputs = self.payment_request.get_outputs()
             else:
                 if not bitcoin.is_address(address):
                     self.app.show_error(
                         _('Invalid Bitcoin Address') + ':\n' + address)
                     return
                 outputs = [
                     PartialTxOutput.from_address_and_value(
                         address, amount)
                 ]
                 return self.app.wallet.create_invoice(
                     outputs=outputs,
                     message=message,
                     pr=self.payment_request,
                     URI=self.parsed_URI)
     except InvoiceError as e:
         self.app.show_error(_('Error creating payment') + ':\n' + str(e))
Exemple #45
0
    def do_send(self):
        scrn = self.ids
        label = unicode(scrn.message_e.text)
        r = unicode(scrn.payto_e.text).strip()
        # label or alias, with address in brackets
        m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
        to_address = m.group(2) if m else r

        if not bitcoin.is_address(to_address):
            self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + to_address)
            return

        amount = self.app.get_amount(scrn.amount_e.text)
        #fee = scrn.fee_e.amt
        #if not fee:
        #    app.show_error(_('Invalid Fee'))
        #    return
        fee = None
        message = 'sending {} {} to {}'.format(self.app.base_unit, scrn.amount_e.text, r)
        outputs = [('address', to_address, amount)]
        self.app.password_dialog(self.send_tx, (outputs, fee, label))
Exemple #46
0
    def do_send(self):
        app = App.get_running_app()
        screen_send = app.root.main_screen.ids.tabs.ids.screen_send
        scrn = screen_send.ids
        label = unicode(scrn.message_e.text)

        r = unicode(scrn.payto_e.text).strip()

        # label or alias, with address in brackets
        global re
        if not re:
            import re
        m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
        to_address = m.group(2) if m else r

        global bitcoin
        if not bitcoin:
            from electrum import bitcoin

        if not bitcoin.is_address(to_address):
            app.show_error(_('Invalid Bitcoin Address') +
                                            ':\n' + to_address)
            return

        amount = scrn.amount_e.text
        fee = scrn.fee_e.amt
        if not fee:
            app.show_error(_('Invalid Fee'))
            return

        from pudb import set_trace; set_trace()
        message = 'sending {} {} to {}'.format(\
            app.base_unit, scrn.amount_e.text, r)

        confirm_fee = self.config.get('confirm_amount', 100000)
        if fee >= confirm_fee:
            if not self.question(_("The fee for this transaction seems unusually high.\nAre you really sure you want to pay %(fee)s in fees?")%{ 'fee' : self.format_amount(fee) + ' '+ self.base_unit()}):
                return

        self.send_tx(to_address, amount, fee, label)
Exemple #47
0
class SendScreen(CScreen, Logger):

    kvname = 'send'
    payment_request = None  # type: Optional[PaymentRequest]
    parsed_URI = None
    lnurl_data = None  # type: Optional[LNURL6Data]

    def __init__(self, **kwargs):
        CScreen.__init__(self, **kwargs)
        Logger.__init__(self)
        self.is_max = False
        # note: most the fields get declared in send.kv, this way they are kivy Properties

    def set_URI(self, text: str):
        """Takes
        Lightning identifiers:
        * lightning-URI (containing bolt11 or lnurl)
        * bolt11 invoice
        * lnurl
        Bitcoin identifiers:
        * bitcoin-URI
        * bitcoin address
        and sets the sending screen.

        TODO maybe rename method...
        """
        if not self.app.wallet:
            return
        text = text.strip()
        if not text:
            return
        if invoice_or_lnurl := maybe_extract_lightning_payment_identifier(
                text):
            if invoice_or_lnurl.startswith('lnurl'):
                self.set_lnurl6(invoice_or_lnurl)
            else:
                self.set_bolt11(invoice_or_lnurl)
        elif text.lower().startswith(BITCOIN_BIP21_URI_SCHEME +
                                     ':') or bitcoin.is_address(text):
            self.set_bip21(text)
Exemple #48
0
 def read_invoice(self):
     address = str(self.screen.address)
     if not address:
         self.app.show_error(_('Recipient not specified.') + ' ' + _('Please scan a Bitcoin address or a payment request'))
         return
     if not self.screen.amount:
         self.app.show_error(_('Please enter an amount'))
         return
     try:
         amount = self.app.get_amount(self.screen.amount)
     except:
         self.app.show_error(_('Invalid amount') + ':\n' + self.screen.amount)
         return
     message = self.screen.message
     if self.screen.is_lightning:
         return self.app.wallet.lnworker.parse_bech32_invoice(address)
     else:
         if not bitcoin.is_address(address):
             self.app.show_error(_('Invalid Bitcoin Address') + ':\n' + address)
             return
         outputs = [TxOutput(TYPE_ADDRESS, address, amount)]
         return self.app.wallet.create_invoice(outputs, message, self.payment_request, self.parsed_URI)
Exemple #49
0
    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid Bitcoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx([(TYPE_ADDRESS, self.str_recipient, amount)], password, self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        status, msg = self.network.broadcast(tx)

        if status:
            self.show_message(_('Payment sent.'))
            self.do_clear()
            #self.update_contacts_tab()
        else:
            self.show_message(_('Error'))
 def on_qr(self, data):
     from electrum.bitcoin import base_decode, is_address
     data = data.strip()
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('bitcoingold:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum.transaction import Transaction
     from electrum.util import bh2u
     try:
         text = bh2u(base_decode(data, None, base=43))
         tx = Transaction(text)
         tx.deserialize()
     except:
         tx = None
     if tx:
         self.tx_dialog(tx)
         return
     # show error
     self.show_error("Unable to decode QR data")
Exemple #51
0
 def on_qr(self, data):
     from electrum.bitcoin import base_decode, is_address
     data = data.strip()
     if is_address(data):
         self.set_URI(data)
         return
     if data.startswith('bitcoin:'):
         self.set_URI(data)
         return
     # try to decode transaction
     from electrum.transaction import Transaction
     from electrum.util import bh2u
     try:
         text = bh2u(base_decode(data, None, base=43))
         tx = Transaction(text)
         tx.deserialize()
     except:
         tx = None
     if tx:
         self.tx_dialog(tx)
         return
     # show error
     self.show_error("Unable to decode QR data")
Exemple #52
0
    def do_send(self):
        scrn = self.ids
        label = unicode(scrn.message_e.text)
        r = unicode(scrn.payto_e.text).strip()
        # label or alias, with address in brackets
        m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
        to_address = m.group(2) if m else r

        if not bitcoin.is_address(to_address):
            self.app.show_error(
                _('Invalid Bitcoin Address') + ':\n' + to_address)
            return

        amount = self.app.get_amount(scrn.amount_e.text)
        #fee = scrn.fee_e.amt
        #if not fee:
        #    app.show_error(_('Invalid Fee'))
        #    return
        fee = None
        message = 'sending {} {} to {}'.format(self.app.base_unit,
                                               scrn.amount_e.text, r)
        outputs = [('address', to_address, amount)]
        self.app.password_dialog(self.send_tx, (outputs, fee, label))
Exemple #53
0
 def parse_address(self, line):
     r = line.strip()
     m = re.match('^'+RE_ALIAS+'$', r)
     address = m.group(2) if m else r
     assert bitcoin.is_address(address)
     return address
Exemple #54
0
 def parse_address(self, line):
     r = line.strip()
     m = re.match("^" + RE_ALIAS + "$", r)
     address = str(m.group(2) if m else r)
     assert bitcoin.is_address(address)
     return address
Exemple #55
0
def payto_loop():
    global recipient
    if recipient:
        droid.fullSetProperty("recipient", "text", recipient)
        recipient = None

    out = None
    while out is None:
        event = droid.eventWait().result
        if not event:
            continue
        print "got event in payto loop", event
        if event == "OK":
            continue
        if not event.get("name"):
            continue

        if event["name"] == "click":
            id = event["data"]["id"]

            if id == "buttonPay":

                droid.fullQuery()
                recipient = droid.fullQueryDetail("recipient").result.get("text")
                message = droid.fullQueryDetail("message").result.get("text")
                amount = droid.fullQueryDetail("amount").result.get("text")

                if not is_address(recipient):
                    modal_dialog("Error", "Invalid Bitcoin address")
                    continue

                try:
                    amount = int(COIN * Decimal(amount))
                except Exception:
                    modal_dialog("Error", "Invalid amount")
                    continue

                result = pay_to(recipient, amount, message)
                if result:
                    out = "main"

            elif id == "buttonContacts":
                addr = select_from_contacts()
                droid.fullSetProperty("recipient", "text", addr)

            elif id == "buttonQR":
                code = droid.scanBarcode()
                r = code.result
                if r:
                    data = str(r["extras"]["SCAN_RESULT"]).strip()
                    if data:
                        print "data", data
                        if re.match("^bitcoin:", data):
                            rr = util.parse_URI(data)
                            amount = rr.get("amount")
                            address = rr.get("address")
                            message = rr.get("message", "")
                            if amount:
                                amount = str(Decimal(amount) / COIN)
                            droid.fullSetProperty("recipient", "text", address)
                            droid.fullSetProperty("amount", "text", amount)
                            droid.fullSetProperty("message", "text", message)
                        elif is_address(data):
                            droid.fullSetProperty("recipient", "text", data)
                        else:
                            modal_dialog("Error", "cannot parse QR code\n" + data)

        elif event["name"] in menu_commands:
            out = event["name"]

        elif event["name"] == "key":
            if event["data"]["key"] == "4":
                out = "main"

        # elif event["name"]=="screen":
        #    if event["data"]=="destroy":
        #        out = 'main'

    return out
Exemple #56
0
def payto_loop():
    global recipient
    if recipient:
        droid.fullSetProperty("recipient","text",recipient)
        recipient = None

    out = None
    while out is None:
        event = droid.eventWait().result
        if not event: continue
        print "got event in payto loop", event
        if event == 'OK': continue
        if not event.get("name"): continue

        if event["name"] == "click":
            id = event["data"]["id"]

            if id=="buttonPay":

                droid.fullQuery()
                recipient = droid.fullQueryDetail("recipient").result.get('text')
                message = droid.fullQueryDetail("message").result.get('text')
                amount = droid.fullQueryDetail('amount').result.get('text')

                if not is_address(recipient):
                    modal_dialog('Error','Invalid MonetaryUnit address')
                    continue

                try:
                    amount = int(COIN * Decimal(amount))
                except Exception:
                    modal_dialog('Error','Invalid amount')
                    continue

                result = pay_to(recipient, amount, message)
                if result:
                    out = 'main'

            elif id=="buttonContacts":
                addr = select_from_contacts()
                droid.fullSetProperty("recipient", "text", addr)

            elif id=="buttonQR":
                code = droid.scanBarcode()
                r = code.result
                if r:
                    data = str(r['extras']['SCAN_RESULT']).strip()
                    if data:
                        print "data", data
                        if re.match('^monetaryunit:', data):
                            payto, amount, label, message, _ = util.parse_URI(data)
                            if amount:
                                amount = str(amount / COIN)
                            droid.fullSetProperty("recipient", "text", payto)
                            droid.fullSetProperty("amount", "text", amount)
                            droid.fullSetProperty("message", "text", message)
                        elif is_address(data):
                            droid.fullSetProperty("recipient", "text", data)
                        else:
                            modal_dialog('Error','cannot parse QR code\n'+data)


        elif event["name"] in menu_commands:
            out = event["name"]

        elif event["name"]=="key":
            if event["data"]["key"] == '4':
                out = 'main'

        #elif event["name"]=="screen":
        #    if event["data"]=="destroy":
        #        out = 'main'

    return out