electrum

Electrum Bitcoin wallet
git clone https://git.parazyd.org/electrum
Log | Files | Refs | Submodules

commit a563091f30652b2cff9e5e2d6f22a76637ebdd41
parent f9f59d8dffcd0b25eba87c6b0741e7eb4621e25a
Author: thomasv <thomasv@gitorious>
Date:   Sat,  2 Mar 2013 12:26:21 +0100

separate core and gui in different modules

Diffstat:
Melectrum | 14+++++++-------
Agui/__init__.py | 1+
Rlib/bmp.py -> gui/bmp.py | 0
Agui/gui.py | 1290+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agui/gui_android.py | 1002+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agui/gui_lite.py | 1007+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agui/gui_qt.py | 2539+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agui/gui_text.py | 423+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Rlib/history_widget.py -> gui/history_widget.py | 0
Rlib/i18n.py -> gui/i18n.py | 0
Agui/qrscanner.py | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Agui/qt_console.py | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Rlib/receiving_widget.py -> gui/receiving_widget.py | 0
Mlib/__init__.py | 3+--
Dlib/exchange_rate.py | 59-----------------------------------------------------------
Dlib/gui.py | 1290-------------------------------------------------------------------------------
Dlib/gui_android.py | 1003-------------------------------------------------------------------------------
Dlib/gui_lite.py | 1008-------------------------------------------------------------------------------
Dlib/gui_qt.py | 2535-------------------------------------------------------------------------------
Dlib/gui_text.py | 423-------------------------------------------------------------------------------
Dlib/pyqrnative.py | 962-------------------------------------------------------------------------------
Dlib/qrscanner.py | 83-------------------------------------------------------------------------------
Dlib/qt_console.py | 296-------------------------------------------------------------------------------
Msetup.py | 28++++++++++++++--------------
24 files changed, 6663 insertions(+), 7682 deletions(-)

diff --git a/electrum b/electrum @@ -38,6 +38,8 @@ if os.path.exists("lib"): import imp fp, pathname, description = imp.find_module('lib') imp.load_module('electrum', fp, pathname, description) + fp, pathname, description = imp.find_module('gui') + imp.load_module('electrumGUI', fp, pathname, description) from electrum import * @@ -115,17 +117,16 @@ if __name__ == '__main__': #right GUI toolkit based the GUI command line option given if cmd == 'gui': pref_gui = config.get('gui','classic') - if pref_gui == 'gtk': - import electrum.gui as gui + import electrumGUI.gui as gui elif pref_gui in ['classic', 'qt']: - import electrum.gui_qt as gui + import electrumGUI.gui_qt as gui elif pref_gui == 'lite': - import electrum.gui_lite as gui + import electrumGUI.gui_lite as gui elif pref_gui == 'text': - import electrum.gui_text as gui + import electrumGUI.gui_text as gui elif pref_gui == 'android': - import electrum.gui_android as gui + import electrumGUI.gui_android as gui else: sys.exit("Error: Unknown GUI: " + pref_gui ) @@ -136,7 +137,6 @@ if __name__ == '__main__': if interface.is_connected: interface.send([('server.peers.subscribe',[])]) - set_language(config.get('language')) gui = gui.ElectrumGui(wallet, config) found = config.wallet_file_exists diff --git a/gui/__init__.py b/gui/__init__.py @@ -0,0 +1 @@ +# do not remove this file diff --git a/lib/bmp.py b/gui/bmp.py diff --git a/gui/gui.py b/gui/gui.py @@ -0,0 +1,1290 @@ +#!/usr/bin/env python +# +# Electrum - lightweight Bitcoin client +# Copyright (C) 2011 thomasv@gitorious +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import datetime +import thread, time, ast, sys, re +import socket, traceback +import pygtk +pygtk.require('2.0') +import gtk, gobject +from decimal import Decimal +from electrum.util import print_error +from electrum import is_valid +from electrum import mnemonic +import pyqrnative + +gtk.gdk.threads_init() +APP_NAME = "Electrum" +import platform +MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' + +from electrum.util import format_satoshis +from electrum.interface import DEFAULT_SERVERS + +def numbify(entry, is_int = False): + text = entry.get_text().strip() + chars = '0123456789' + if not is_int: chars +='.' + s = ''.join([i for i in text if i in chars]) + if not is_int: + if '.' in s: + p = s.find('.') + s = s.replace('.','') + s = s[:p] + '.' + s[p:p+8] + try: + amount = int( Decimal(s) * 100000000 ) + except: + amount = None + else: + try: + amount = int( s ) + except: + amount = None + entry.set_text(s) + return amount + + + + +def show_seed_dialog(wallet, password, parent): + if not wallet.seed: + show_message("No seed") + return + try: + seed = wallet.decode_seed(password) + except: + show_message("Incorrect password") + return + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK, + message_format = "Your wallet generation seed is:\n\n" + seed \ + + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ + + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" + ' '.join(mnemonic.mn_encode(seed)) + "\"" ) + dialog.set_title("Seed") + dialog.show() + dialog.run() + dialog.destroy() + +def restore_create_dialog(wallet): + + # ask if the user wants to create a new wallet, or recover from a seed. + # if he wants to recover, and nothing is found, do not create wallet + dialog = gtk.Dialog("electrum", parent=None, + flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, + buttons= ("create", 0, "restore",1, "cancel",2) ) + + label = gtk.Label("Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" ) + label.show() + dialog.vbox.pack_start(label) + dialog.show() + r = dialog.run() + dialog.destroy() + + if r==2: return False + return 'restore' if r==1 else 'create' + + + +def run_recovery_dialog(wallet): + message = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." + dialog = gtk.MessageDialog( + parent = None, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK_CANCEL, + message_format = message) + + vbox = dialog.vbox + dialog.set_default_response(gtk.RESPONSE_OK) + + # ask seed, server and gap in the same dialog + seed_box = gtk.HBox() + seed_label = gtk.Label('Seed or mnemonic:') + seed_label.set_size_request(150,-1) + seed_box.pack_start(seed_label, False, False, 10) + seed_label.show() + seed_entry = gtk.Entry() + seed_entry.show() + seed_entry.set_size_request(450,-1) + seed_box.pack_start(seed_entry, False, False, 10) + add_help_button(seed_box, '.') + seed_box.show() + vbox.pack_start(seed_box, False, False, 5) + + gap = gtk.HBox() + gap_label = gtk.Label('Gap limit:') + gap_label.set_size_request(150,10) + gap_label.show() + gap.pack_start(gap_label,False, False, 10) + gap_entry = gtk.Entry() + gap_entry.set_text("%d"%wallet.gap_limit) + gap_entry.connect('changed', numbify, True) + gap_entry.show() + gap.pack_start(gap_entry,False,False, 10) + add_help_button(gap, 'The maximum gap that is allowed between unused addresses in your wallet. During wallet recovery, this parameter is used to decide when to stop the recovery process. If you increase this value, you will need to remember it in order to be able to recover your wallet from seed.') + gap.show() + vbox.pack_start(gap, False,False, 5) + + dialog.show() + r = dialog.run() + gap = gap_entry.get_text() + seed = seed_entry.get_text() + dialog.destroy() + + if r==gtk.RESPONSE_CANCEL: + return False + + try: + gap = int(gap) + except: + show_message("error") + return False + + try: + seed.decode('hex') + except: + print_error("Warning: Not hex, trying decode") + seed = mnemonic.mn_decode( seed.split(' ') ) + if not seed: + show_message("no seed") + return False + + return seed, gap + + + +def run_settings_dialog(wallet, parent): + + message = "Here are the settings of your wallet. For more explanations, click on the question mark buttons next to each input field." + + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK_CANCEL, + message_format = message) + + image = gtk.Image() + image.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_DIALOG) + image.show() + dialog.set_image(image) + dialog.set_title("Settings") + + vbox = dialog.vbox + dialog.set_default_response(gtk.RESPONSE_OK) + + fee = gtk.HBox() + fee_entry = gtk.Entry() + fee_label = gtk.Label('Transaction fee:') + fee_label.set_size_request(150,10) + fee_label.show() + fee.pack_start(fee_label,False, False, 10) + fee_entry.set_text( str( Decimal(wallet.fee) /100000000 ) ) + fee_entry.connect('changed', numbify, False) + fee_entry.show() + fee.pack_start(fee_entry,False,False, 10) + add_help_button(fee, 'Fee per transaction input. Transactions involving multiple inputs tend to have a higher fee. Recommended value:0.0005') + fee.show() + vbox.pack_start(fee, False,False, 5) + + nz = gtk.HBox() + nz_entry = gtk.Entry() + nz_label = gtk.Label('Display zeros:') + nz_label.set_size_request(150,10) + nz_label.show() + nz.pack_start(nz_label,False, False, 10) + nz_entry.set_text( str( wallet.num_zeros )) + nz_entry.connect('changed', numbify, True) + nz_entry.show() + nz.pack_start(nz_entry,False,False, 10) + add_help_button(nz, "Number of zeros displayed after the decimal point.\nFor example, if this number is 2, then '5.' is displayed as '5.00'") + nz.show() + vbox.pack_start(nz, False,False, 5) + + # gui setting + gui_box = gtk.HBox() + gui_label = gtk.Label('Default GUI:') + gui_label.set_size_request(150,10) + gui_label.show() + gui_box.pack_start(gui_label,False, False, 10) + gui_combo = gtk.combo_box_new_text() + gui_names = ['lite', 'classic', 'gtk', 'text'] + for name in gui_names: gui_combo.append_text(name.capitalize()) + gui_combo.show() + gui_box.pack_start(gui_combo,False, False, 10) + gui_combo.set_active( gui_names.index( wallet.config.get("gui","lite")) ) + gui_box.show() + add_help_button(gui_box, "Select which GUI mode to use at start up.") + + vbox.pack_start(gui_box, False,False, 5) + + dialog.show() + r = dialog.run() + fee = fee_entry.get_text() + nz = nz_entry.get_text() + gui = gui_names[ gui_combo.get_active()] + + dialog.destroy() + if r==gtk.RESPONSE_CANCEL: + return + + try: + fee = int( 100000000 * Decimal(fee) ) + except: + show_message("error") + return + if wallet.fee != fee: + wallet.fee = fee + wallet.save() + + try: + nz = int( nz ) + if nz>8: nz = 8 + except: + show_message("error") + return + if wallet.num_zeros != nz: + wallet.num_zeros = nz + wallet.save() + + wallet.config.set_key('gui',gui,True) + + + + +def run_network_dialog( wallet, parent ): + image = gtk.Image() + image.set_from_stock(gtk.STOCK_NETWORK, gtk.ICON_SIZE_DIALOG) + interface = wallet.interface + if parent: + if interface.is_connected: + status = "Connected to %s:%d\n%d blocks"%(interface.host, interface.port, wallet.verifier.height) + else: + status = "Not connected" + else: + import random + status = "Please choose a server.\nSelect cancel if you are offline." + + server = interface.server + plist, servers_list = interface.get_servers_list() + + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, + gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status) + dialog.set_title("Server") + dialog.set_image(image) + image.show() + + vbox = dialog.vbox + host_box = gtk.HBox() + host_label = gtk.Label('Connect to:') + host_label.set_size_request(100,-1) + host_label.show() + host_box.pack_start(host_label, False, False, 10) + host_entry = gtk.Entry() + host_entry.set_size_request(200,-1) + host_entry.set_text(server) + host_entry.show() + host_box.pack_start(host_entry, False, False, 10) + add_help_button(host_box, 'The name and port number of your Electrum server, separated by a colon. Example: "ecdsa.org:50000". If no port number is provided, port 50000 will be tried. Some servers allow you to connect through http (port 80) or https (port 443)') + host_box.show() + + + p_box = gtk.HBox(False, 10) + p_box.show() + + p_label = gtk.Label('Protocol:') + p_label.set_size_request(100,-1) + p_label.show() + p_box.pack_start(p_label, False, False, 10) + + radio1 = gtk.RadioButton(None, "tcp") + p_box.pack_start(radio1, True, True, 0) + radio1.show() + radio2 = gtk.RadioButton(radio1, "http") + p_box.pack_start(radio2, True, True, 0) + radio2.show() + + def current_line(): + return unicode(host_entry.get_text()).split(':') + + def set_button(protocol): + if protocol == 't': + radio1.set_active(1) + elif protocol == 'h': + radio2.set_active(1) + + def set_protocol(protocol): + host = current_line()[0] + pp = plist[host] + if protocol not in pp.keys(): + protocol = pp.keys()[0] + set_button(protocol) + port = pp[protocol] + host_entry.set_text( host + ':' + port + ':' + protocol) + + radio1.connect("toggled", lambda x,y:set_protocol('t'), "radio button 1") + radio2.connect("toggled", lambda x,y:set_protocol('h'), "radio button 1") + + server_list = gtk.ListStore(str) + for host in plist.keys(): + server_list.append([host]) + + treeview = gtk.TreeView(model=server_list) + treeview.show() + + if wallet.interface.servers: + label = 'Active Servers' + else: + label = 'Default Servers' + + tvcolumn = gtk.TreeViewColumn(label) + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 0) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + scroll.show() + + vbox.pack_start(host_box, False,False, 5) + vbox.pack_start(p_box, True, True, 0) + vbox.pack_start(scroll) + + def my_treeview_cb(treeview): + path, view_column = treeview.get_cursor() + host = server_list.get_value( server_list.get_iter(path), 0) + + pp = plist[host] + if 't' in pp.keys(): + protocol = 't' + else: + protocol = pp.keys()[0] + port = pp[protocol] + host_entry.set_text( host + ':' + port + ':' + protocol) + set_button(protocol) + + treeview.connect('cursor-changed', my_treeview_cb) + + dialog.show() + r = dialog.run() + server = host_entry.get_text() + dialog.destroy() + + if r==gtk.RESPONSE_CANCEL: + return False + + try: + interface.set_server(server) + except: + show_message("error:" + server) + return False + + if parent: + wallet.config.set_key("server", server, True) + return True + + + +def show_message(message, parent=None): + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_CLOSE, + message_format = message ) + dialog.show() + dialog.run() + dialog.destroy() + +def password_line(label): + password = gtk.HBox() + password_label = gtk.Label(label) + password_label.set_size_request(120,10) + password_label.show() + password.pack_start(password_label,False, False, 10) + password_entry = gtk.Entry() + password_entry.set_size_request(300,-1) + password_entry.set_visibility(False) + password_entry.show() + password.pack_start(password_entry,False,False, 10) + password.show() + return password, password_entry + +def password_dialog(parent): + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, + gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Please enter your password.") + dialog.get_image().set_visible(False) + current_pw, current_pw_entry = password_line('Password:') + current_pw_entry.connect("activate", lambda entry, dialog, response: dialog.response(response), dialog, gtk.RESPONSE_OK) + dialog.vbox.pack_start(current_pw, False, True, 0) + dialog.show() + result = dialog.run() + pw = current_pw_entry.get_text() + dialog.destroy() + if result != gtk.RESPONSE_CANCEL: return pw + +def change_password_dialog(wallet, parent, icon): + if not wallet.seed: + show_message("No seed") + return + + if parent: + msg = 'Your wallet is encrypted. Use this dialog to change the password. To disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' + else: + msg = "Please choose a password to encrypt your wallet keys" + + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) + dialog.set_title("Change password") + image = gtk.Image() + image.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG) + image.show() + dialog.set_image(image) + + if wallet.use_encryption: + current_pw, current_pw_entry = password_line('Current password:') + dialog.vbox.pack_start(current_pw, False, True, 0) + + password, password_entry = password_line('New password:') + dialog.vbox.pack_start(password, False, True, 5) + password2, password2_entry = password_line('Confirm password:') + dialog.vbox.pack_start(password2, False, True, 5) + + dialog.show() + result = dialog.run() + password = current_pw_entry.get_text() if wallet.use_encryption else None + new_password = password_entry.get_text() + new_password2 = password2_entry.get_text() + dialog.destroy() + if result == gtk.RESPONSE_CANCEL: + return + + try: + seed = wallet.decode_seed(password) + except: + show_message("Incorrect password") + return + + if new_password != new_password2: + show_message("passwords do not match") + return + + wallet.update_password(seed, password, new_password) + + if icon: + if wallet.use_encryption: + icon.set_tooltip_text('wallet is encrypted') + else: + icon.set_tooltip_text('wallet is unencrypted') + + +def add_help_button(hbox, message): + button = gtk.Button('?') + button.connect("clicked", lambda x: show_message(message)) + button.show() + hbox.pack_start(button,False, False) + + +class MyWindow(gtk.Window): __gsignals__ = dict( mykeypress = (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_ACTION, None, (str,)) ) + +gobject.type_register(MyWindow) +gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.W, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+W') +gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.Q, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+Q') + + +class ElectrumWindow: + + def show_message(self, msg): + show_message(msg, self.window) + + def __init__(self, wallet, config): + self.config = config + self.wallet = wallet + self.funds_error = False # True if not enough funds + + self.window = MyWindow(gtk.WINDOW_TOPLEVEL) + title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.config.path + if not self.wallet.seed: title += ' [seedless]' + self.window.set_title(title) + self.window.connect("destroy", gtk.main_quit) + self.window.set_border_width(0) + self.window.connect('mykeypress', gtk.main_quit) + self.window.set_default_size(720, 350) + self.wallet_updated = False + + vbox = gtk.VBox() + + self.notebook = gtk.Notebook() + self.create_history_tab() + if self.wallet.seed: + self.create_send_tab() + self.create_recv_tab() + self.create_book_tab() + self.create_about_tab() + self.notebook.show() + vbox.pack_start(self.notebook, True, True, 2) + + self.status_bar = gtk.Statusbar() + vbox.pack_start(self.status_bar, False, False, 0) + + self.status_image = gtk.Image() + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + self.status_image.set_alignment(True, 0.5 ) + self.status_image.show() + + self.network_button = gtk.Button() + self.network_button.connect("clicked", lambda x: run_network_dialog(self.wallet, self.window) ) + self.network_button.add(self.status_image) + self.network_button.set_relief(gtk.RELIEF_NONE) + self.network_button.show() + self.status_bar.pack_end(self.network_button, False, False) + + if self.wallet.seed: + def seedb(w, wallet): + if wallet.use_encryption: + password = password_dialog(self.window) + if not password: return + else: password = None + show_seed_dialog(wallet, password, self.window) + button = gtk.Button('S') + button.connect("clicked", seedb, wallet ) + button.set_relief(gtk.RELIEF_NONE) + button.show() + self.status_bar.pack_end(button,False, False) + + settings_icon = gtk.Image() + settings_icon.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU) + settings_icon.set_alignment(0.5, 0.5) + settings_icon.set_size_request(16,16 ) + settings_icon.show() + + prefs_button = gtk.Button() + prefs_button.connect("clicked", lambda x: run_settings_dialog(self.wallet, self.window) ) + prefs_button.add(settings_icon) + prefs_button.set_tooltip_text("Settings") + prefs_button.set_relief(gtk.RELIEF_NONE) + prefs_button.show() + self.status_bar.pack_end(prefs_button,False,False) + + pw_icon = gtk.Image() + pw_icon.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU) + pw_icon.set_alignment(0.5, 0.5) + pw_icon.set_size_request(16,16 ) + pw_icon.show() + + if self.wallet.seed: + password_button = gtk.Button() + password_button.connect("clicked", lambda x: change_password_dialog(self.wallet, self.window, pw_icon)) + password_button.add(pw_icon) + password_button.set_relief(gtk.RELIEF_NONE) + password_button.show() + self.status_bar.pack_end(password_button,False,False) + + self.window.add(vbox) + self.window.show_all() + #self.fee_box.hide() + + self.context_id = self.status_bar.get_context_id("statusbar") + self.update_status_bar() + + self.wallet.interface.register_callback('updated', self.update_callback) + + + def update_status_bar_thread(): + while True: + gobject.idle_add( self.update_status_bar ) + time.sleep(0.5) + + + def check_recipient_thread(): + old_r = '' + while True: + time.sleep(0.5) + if self.payto_entry.is_focus(): + continue + r = self.payto_entry.get_text() + if r != old_r: + old_r = r + r = r.strip() + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): + try: + to_address = self.wallet.get_alias(r, interactive=False) + except: + continue + if to_address: + s = r + ' <' + to_address + '>' + gobject.idle_add( lambda: self.payto_entry.set_text(s) ) + + + thread.start_new_thread(update_status_bar_thread, ()) + if self.wallet.seed: + thread.start_new_thread(check_recipient_thread, ()) + self.notebook.set_current_page(0) + + def update_callback(self): + self.wallet_updated = True + + + def add_tab(self, page, name): + tab_label = gtk.Label(name) + tab_label.show() + self.notebook.append_page(page, tab_label) + + + def create_send_tab(self): + + page = vbox = gtk.VBox() + page.show() + + payto = gtk.HBox() + payto_label = gtk.Label('Pay to:') + payto_label.set_size_request(100,-1) + payto.pack_start(payto_label, False) + payto_entry = gtk.Entry() + payto_entry.set_size_request(450, 26) + payto.pack_start(payto_entry, False) + vbox.pack_start(payto, False, False, 5) + + message = gtk.HBox() + message_label = gtk.Label('Description:') + message_label.set_size_request(100,-1) + message.pack_start(message_label, False) + message_entry = gtk.Entry() + message_entry.set_size_request(450, 26) + message.pack_start(message_entry, False) + vbox.pack_start(message, False, False, 5) + + amount_box = gtk.HBox() + amount_label = gtk.Label('Amount:') + amount_label.set_size_request(100,-1) + amount_box.pack_start(amount_label, False) + amount_entry = gtk.Entry() + amount_entry.set_size_request(120, -1) + amount_box.pack_start(amount_entry, False) + vbox.pack_start(amount_box, False, False, 5) + + self.fee_box = fee_box = gtk.HBox() + fee_label = gtk.Label('Fee:') + fee_label.set_size_request(100,-1) + fee_box.pack_start(fee_label, False) + fee_entry = gtk.Entry() + fee_entry.set_size_request(60, 26) + fee_box.pack_start(fee_entry, False) + vbox.pack_start(fee_box, False, False, 5) + + end_box = gtk.HBox() + empty_label = gtk.Label('') + empty_label.set_size_request(100,-1) + end_box.pack_start(empty_label, False) + send_button = gtk.Button("Send") + send_button.show() + end_box.pack_start(send_button, False, False, 0) + clear_button = gtk.Button("Clear") + clear_button.show() + end_box.pack_start(clear_button, False, False, 15) + send_button.connect("clicked", self.do_send, (payto_entry, message_entry, amount_entry, fee_entry)) + clear_button.connect("clicked", self.do_clear, (payto_entry, message_entry, amount_entry, fee_entry)) + + vbox.pack_start(end_box, False, False, 5) + + # display this line only if there is a signature + payto_sig = gtk.HBox() + payto_sig_id = gtk.Label('') + payto_sig.pack_start(payto_sig_id, False) + vbox.pack_start(payto_sig, True, True, 5) + + + self.user_fee = False + + def entry_changed( entry, is_fee ): + self.funds_error = False + amount = numbify(amount_entry) + fee = numbify(fee_entry) + if not is_fee: fee = None + if amount is None: + return + inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) + if not is_fee: + fee_entry.set_text( str( Decimal( fee ) / 100000000 ) ) + self.fee_box.show() + if inputs: + amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) + fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) + send_button.set_sensitive(True) + else: + send_button.set_sensitive(False) + amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) + fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) + self.funds_error = True + + amount_entry.connect('changed', entry_changed, False) + fee_entry.connect('changed', entry_changed, True) + + self.payto_entry = payto_entry + self.payto_fee_entry = fee_entry + self.payto_sig_id = payto_sig_id + self.payto_sig = payto_sig + self.amount_entry = amount_entry + self.message_entry = message_entry + self.add_tab(page, 'Send') + + def set_frozen(self,entry,frozen): + if frozen: + entry.set_editable(False) + entry.set_has_frame(False) + entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#eeeeee")) + else: + entry.set_editable(True) + entry.set_has_frame(True) + entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#ffffff")) + + def set_url(self, url): + payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) + self.notebook.set_current_page(1) + self.payto_entry.set_text(payto) + self.message_entry.set_text(message) + self.amount_entry.set_text(amount) + if identity: + self.set_frozen(self.payto_entry,True) + self.set_frozen(self.amount_entry,True) + self.set_frozen(self.message_entry,True) + self.payto_sig_id.set_text( ' The bitcoin URI was signed by ' + identity ) + else: + self.payto_sig.set_visible(False) + + def create_about_tab(self): + import pango + page = gtk.VBox() + page.show() + tv = gtk.TextView() + tv.set_editable(False) + tv.set_cursor_visible(False) + tv.modify_font(pango.FontDescription(MONOSPACE_FONT)) + scroll = gtk.ScrolledWindow() + scroll.add(tv) + page.pack_start(scroll) + self.info = tv.get_buffer() + self.add_tab(page, 'Wall') + + def do_clear(self, w, data): + self.payto_sig.set_visible(False) + self.payto_fee_entry.set_text('') + for entry in [self.payto_entry,self.amount_entry,self.message_entry]: + self.set_frozen(entry,False) + entry.set_text('') + + def question(self,msg): + dialog = gtk.MessageDialog( self.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) + dialog.show() + result = dialog.run() + dialog.destroy() + return result == gtk.RESPONSE_OK + + def do_send(self, w, data): + payto_entry, label_entry, amount_entry, fee_entry = data + label = label_entry.get_text() + r = payto_entry.get_text() + r = r.strip() + + m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) + m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) + + if m1: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + if not to_address: + return + else: + self.update_sending_tab() + + elif m2: + to_address = m2.group(5) + else: + to_address = r + + if not is_valid(to_address): + self.show_message( "invalid bitcoin address:\n"+to_address) + return + + try: + amount = int( Decimal(amount_entry.get_text()) * 100000000 ) + except: + self.show_message( "invalid amount") + return + try: + fee = int( Decimal(fee_entry.get_text()) * 100000000 ) + except: + self.show_message( "invalid fee") + return + + if self.wallet.use_encryption: + password = password_dialog(self.window) + if not password: + return + else: + password = None + + try: + tx = self.wallet.mktx( [(to_address, amount)], password, fee ) + except BaseException, e: + self.show_message(str(e)) + return + + if label: + self.wallet.labels[tx.hash()] = label + + status, msg = self.wallet.sendtx( tx ) + if status: + self.show_message( "payment sent.\n" + msg ) + payto_entry.set_text("") + label_entry.set_text("") + amount_entry.set_text("") + fee_entry.set_text("") + #self.fee_box.hide() + self.update_sending_tab() + else: + self.show_message( msg ) + + + def treeview_button_press(self, treeview, event): + if event.type == gtk.gdk._2BUTTON_PRESS: + c = treeview.get_cursor()[0] + if treeview == self.history_treeview: + tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) + self.show_message(tx_details) + elif treeview == self.contacts_treeview: + m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self-signed" + msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] + self.show_message(msg) + + + def treeview_key_press(self, treeview, event): + c = treeview.get_cursor()[0] + if event.keyval == gtk.keysyms.Up: + if c and c[0] == 0: + treeview.parent.grab_focus() + treeview.set_cursor((0,)) + elif event.keyval == gtk.keysyms.Return: + if treeview == self.history_treeview: + tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) + self.show_message(tx_details) + elif treeview == self.contacts_treeview: + m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self" + msg = 'Alias:'+ m + '\n\nTarget: '+ a[1] + '\nSigned by: ' + s + '\nSigning address:' + a[0] + self.show_message(msg) + + return False + + def create_history_tab(self): + + self.history_list = gtk.ListStore(str, str, str, str, 'gboolean', str, str, str, str) + treeview = gtk.TreeView(model=self.history_list) + self.history_treeview = treeview + treeview.set_tooltip_column(7) + treeview.show() + treeview.connect('key-press-event', self.treeview_key_press) + treeview.connect('button-press-event', self.treeview_button_press) + + tvcolumn = gtk.TreeViewColumn('') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererPixbuf() + tvcolumn.pack_start(cell, False) + tvcolumn.set_attributes(cell, stock_id=1) + + tvcolumn = gtk.TreeViewColumn('Date') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 2) + + tvcolumn = gtk.TreeViewColumn('Description') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('foreground', 'grey') + cell.set_property('family', MONOSPACE_FONT) + cell.set_property('editable', True) + def edited_cb(cell, path, new_text, h_list): + tx = h_list.get_value( h_list.get_iter(path), 0) + self.wallet.labels[tx] = new_text + self.wallet.save() + self.update_history_tab() + cell.connect('edited', edited_cb, self.history_list) + def editing_started(cell, entry, path, h_list): + tx = h_list.get_value( h_list.get_iter(path), 0) + if not self.wallet.labels.get(tx): entry.set_text('') + cell.connect('editing-started', editing_started, self.history_list) + tvcolumn.set_expand(True) + tvcolumn.pack_start(cell, True) + tvcolumn.set_attributes(cell, text=3, foreground_set = 4) + + tvcolumn = gtk.TreeViewColumn('Amount') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_alignment(1, 0.5) + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 5) + + tvcolumn = gtk.TreeViewColumn('Balance') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_alignment(1, 0.5) + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 6) + + tvcolumn = gtk.TreeViewColumn('Tooltip') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 7) + tvcolumn.set_visible(False) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + + self.add_tab(scroll, 'History') + self.update_history_tab() + + + def create_recv_tab(self): + self.recv_list = gtk.ListStore(str, str, str) + self.add_tab( self.make_address_list(True), 'Receive') + self.update_receiving_tab() + + def create_book_tab(self): + self.addressbook_list = gtk.ListStore(str, str, str) + self.add_tab( self.make_address_list(False), 'Contacts') + self.update_sending_tab() + + def make_address_list(self, is_recv): + liststore = self.recv_list if is_recv else self.addressbook_list + treeview = gtk.TreeView(model= liststore) + treeview.connect('key-press-event', self.treeview_key_press) + treeview.connect('button-press-event', self.treeview_button_press) + treeview.show() + if not is_recv: + self.contacts_treeview = treeview + + tvcolumn = gtk.TreeViewColumn('Address') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 0) + + tvcolumn = gtk.TreeViewColumn('Label') + tvcolumn.set_expand(True) + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('editable', True) + def edited_cb2(cell, path, new_text, liststore): + address = liststore.get_value( liststore.get_iter(path), 0) + self.wallet.labels[address] = new_text + self.wallet.save() + self.update_receiving_tab() + self.update_sending_tab() + self.update_history_tab() + cell.connect('edited', edited_cb2, liststore) + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 1) + + tvcolumn = gtk.TreeViewColumn('Tx') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 2) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + + hbox = gtk.HBox() + if not is_recv: + button = gtk.Button("New") + button.connect("clicked", self.newaddress_dialog) + button.show() + hbox.pack_start(button,False) + + def showqrcode(w, treeview, liststore): + path, col = treeview.get_cursor() + if not path: return + address = liststore.get_value(liststore.get_iter(path), 0) + qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) + qr.addData(address) + qr.make() + boxsize = 7 + size = qr.getModuleCount()*boxsize + def area_expose_cb(area, event): + style = area.get_style() + k = qr.getModuleCount() + for r in range(k): + for c in range(k): + gc = style.black_gc if qr.isDark(r, c) else style.white_gc + area.window.draw_rectangle(gc, True, c*boxsize, r*boxsize, boxsize, boxsize) + area = gtk.DrawingArea() + area.set_size_request(size, size) + area.connect("expose-event", area_expose_cb) + area.show() + dialog = gtk.Dialog(address, parent=self.window, flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, buttons = ("ok",1)) + dialog.vbox.add(area) + dialog.run() + dialog.destroy() + + button = gtk.Button("QR") + button.connect("clicked", showqrcode, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + button = gtk.Button("Copy to clipboard") + def copy2clipboard(w, treeview, liststore): + import platform + path, col = treeview.get_cursor() + if path: + address = liststore.get_value( liststore.get_iter(path), 0) + if platform.system() == 'Windows': + from Tkinter import Tk + r = Tk() + r.withdraw() + r.clipboard_clear() + r.clipboard_append( address ) + r.destroy() + else: + c = gtk.clipboard_get() + c.set_text( address ) + button.connect("clicked", copy2clipboard, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + if not is_recv: + button = gtk.Button("Pay to") + def payto(w, treeview, liststore): + path, col = treeview.get_cursor() + if path: + address = liststore.get_value( liststore.get_iter(path), 0) + self.payto_entry.set_text( address ) + self.notebook.set_current_page(1) + self.amount_entry.grab_focus() + + button.connect("clicked", payto, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + vbox = gtk.VBox() + vbox.pack_start(scroll,True) + vbox.pack_start(hbox, False) + return vbox + + def update_status_bar(self): + interface = self.wallet.interface + if self.funds_error: + text = "Not enough funds" + elif interface and interface.is_connected: + self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks"%(interface.host, interface.port, self.wallet.verifier.height)) + if not self.wallet.up_to_date: + self.status_image.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) + text = "Synchronizing..." + else: + self.status_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_MENU) + self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks"%(interface.host, interface.port, self.wallet.verifier.height)) + c, u = self.wallet.get_balance() + text = "Balance: %s "%( format_satoshis(c,False,self.wallet.num_zeros) ) + if u: text += "[%s unconfirmed]"%( format_satoshis(u,True,self.wallet.num_zeros).strip() ) + else: + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + self.network_button.set_tooltip_text("Not connected.") + text = "Not connected" + + self.status_bar.pop(self.context_id) + self.status_bar.push(self.context_id, text) + + if self.wallet.up_to_date and self.wallet_updated: + self.update_history_tab() + self.update_receiving_tab() + # addressbook too... + self.info.set_text( self.wallet.banner ) + self.wallet_updated = False + + def update_receiving_tab(self): + self.recv_list.clear() + for address in self.wallet.addresses(True): + if self.wallet.is_change(address):continue + label = self.wallet.labels.get(address) + h = self.wallet.history.get(address,[]) + n = len(h) + tx = "None" if n==0 else "%d"%n + self.recv_list.append((address, label, tx )) + + def update_sending_tab(self): + # detect addresses that are not mine in history, add them here... + self.addressbook_list.clear() + for alias, v in self.wallet.aliases.items(): + s, target = v + label = self.wallet.labels.get(alias) + self.addressbook_list.append((alias, label, '-')) + + for address in self.wallet.addressbook: + label = self.wallet.labels.get(address) + n = 0 + for tx in self.wallet.transactions.values(): + if address in map(lambda x:x[0], tx.outputs): n += 1 + + self.addressbook_list.append((address, label, "%d"%n)) + + def update_history_tab(self): + cursor = self.history_treeview.get_cursor()[0] + self.history_list.clear() + + for item in self.wallet.get_tx_history(): + tx_hash, conf, is_mine, value, fee, balance, timestamp = item + if conf: + try: + time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] + except: + time_str = "------" + conf_icon = gtk.STOCK_APPLY + else: + time_str = 'pending' + conf_icon = gtk.STOCK_EXECUTE + + label, is_default_label = self.wallet.get_label(tx_hash) + tooltip = tx_hash + "\n%d confirmations"%conf if tx_hash else '' + details = self.wallet.get_tx_details(tx_hash) + + self.history_list.prepend( [tx_hash, conf_icon, time_str, label, is_default_label, + format_satoshis(value,True,self.wallet.num_zeros), + format_satoshis(balance,False,self.wallet.num_zeros), tooltip, details] ) + if cursor: self.history_treeview.set_cursor( cursor ) + + + + def newaddress_dialog(self, w): + + title = "New Contact" + dialog = gtk.Dialog(title, parent=self.window, + flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, + buttons= ("cancel", 0, "ok",1) ) + dialog.show() + + label = gtk.HBox() + label_label = gtk.Label('Label:') + label_label.set_size_request(120,10) + label_label.show() + label.pack_start(label_label) + label_entry = gtk.Entry() + label_entry.show() + label.pack_start(label_entry) + label.show() + dialog.vbox.pack_start(label, False, True, 5) + + address = gtk.HBox() + address_label = gtk.Label('Address:') + address_label.set_size_request(120,10) + address_label.show() + address.pack_start(address_label) + address_entry = gtk.Entry() + address_entry.show() + address.pack_start(address_entry) + address.show() + dialog.vbox.pack_start(address, False, True, 5) + + result = dialog.run() + address = address_entry.get_text() + label = label_entry.get_text() + dialog.destroy() + + if result == 1: + if is_valid(address): + self.wallet.addressbook.append(address) + if label: self.wallet.labels[address] = label + self.wallet.save() + self.update_sending_tab() + else: + errorDialog = gtk.MessageDialog( + parent=self.window, + flags=gtk.DIALOG_MODAL, + buttons= gtk.BUTTONS_CLOSE, + message_format = "Invalid address") + errorDialog.show() + errorDialog.run() + errorDialog.destroy() + + + +class ElectrumGui(): + + def __init__(self, wallet, config): + self.wallet = wallet + self.config = config + + def main(self, url=None): + ew = ElectrumWindow(self.wallet, self.config) + if url: ew.set_url(url) + gtk.main() + + def restore_or_create(self): + return restore_create_dialog(self.wallet) + + def seed_dialog(self): + return run_recovery_dialog( self.wallet ) + + def network_dialog(self): + return run_network_dialog( self.wallet, parent=None ) + + def show_seed(self): + show_seed_dialog(self.wallet, None, None) + + def password_dialog(self): + change_password_dialog(self.wallet, None, None) + + def restore_wallet(self): + wallet = self.wallet + + dialog = gtk.MessageDialog( + parent = None, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_CANCEL, + message_format = "Please wait..." ) + dialog.show() + + def recover_thread( wallet, dialog ): + while not wallet.is_up_to_date(): + time.sleep(0.1) + gobject.idle_add( dialog.destroy ) + + thread.start_new_thread( recover_thread, ( wallet, dialog ) ) + r = dialog.run() + dialog.destroy() + if r==gtk.RESPONSE_CANCEL: return False + if not wallet.is_found(): + show_message("No transactions found for this seed") + + wallet.save() + return True diff --git a/gui/gui_android.py b/gui/gui_android.py @@ -0,0 +1,1002 @@ +#!/usr/bin/env python +# +# Electrum - lightweight Bitcoin client +# Copyright (C) 2011 thomasv@gitorious +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + + + + +import android + +from electrum import SimpleConfig, Interface, WalletSynchronizer, Wallet, format_satoshis, mnemonic_encode, mnemonic_decode, is_valid +from decimal import Decimal +import datetime, re + + + +def modal_dialog(title, msg = None): + droid.dialogCreateAlert(title,msg) + droid.dialogSetPositiveButtonText('OK') + droid.dialogShow() + droid.dialogGetResponse() + droid.dialogDismiss() + +def modal_input(title, msg, value = None, etype=None): + droid.dialogCreateInput(title, msg, value, etype) + droid.dialogSetPositiveButtonText('OK') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse() + result = response.result + if result is None: + print "modal input: result is none" + return False + droid.dialogDismiss() + if result.get('which') == 'positive': + return result.get('value') + +def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'): + droid.dialogCreateAlert(q, msg) + droid.dialogSetPositiveButtonText(pos_text) + droid.dialogSetNegativeButtonText(neg_text) + droid.dialogShow() + response = droid.dialogGetResponse() + result = response.result + if result is None: + print "modal question: result is none" + return False + droid.dialogDismiss() + return result.get('which') == 'positive' + +def edit_label(addr): + v = modal_input('Edit label',None,wallet.labels.get(addr)) + if v is not None: + if v: + wallet.labels[addr] = v + else: + if addr in wallet.labels.keys(): + wallet.labels.pop(addr) + wallet.update_tx_history() + wallet.save() + droid.fullSetProperty("labelTextView", "text", v) + +def select_from_contacts(): + title = 'Contacts:' + droid.dialogCreateAlert(title) + l = [] + for i in range(len(wallet.addressbook)): + addr = wallet.addressbook[i] + label = wallet.labels.get(addr,addr) + l.append( label ) + droid.dialogSetItems(l) + droid.dialogSetPositiveButtonText('New contact') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + + if response.get('which') == 'positive': + return 'newcontact' + + result = response.get('item') + print result + if result is not None: + addr = wallet.addressbook[result] + return addr + + +def select_from_addresses(): + droid.dialogCreateAlert("Addresses:") + l = [] + addresses = wallet.addresses() + for i in range(len(addresses)): + addr = addresses[i] + label = wallet.labels.get(addr,addr) + l.append( label ) + droid.dialogSetItems(l) + droid.dialogShow() + response = droid.dialogGetResponse() + result = response.result.get('item') + droid.dialogDismiss() + if result is not None: + addr = addresses[result] + return addr + + +def protocol_name(p): + if p == 't': return 'TCP' + if p == 'h': return 'HTTP' + if p == 's': return 'TCP/SSL' + if p == 'g': return 'HTTPS' + + +def protocol_dialog(host, protocol, z): + droid.dialogCreateAlert('Protocol',host) + if z: + protocols = z.keys() + else: + protocols = 'thsg' + l = [] + current = protocols.index(protocol) + for p in protocols: + l.append(protocol_name(p)) + droid.dialogSetSingleChoiceItems(l, current) + droid.dialogSetPositiveButtonText('OK') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse().result + selected_item = droid.dialogGetSelectedItems().result + droid.dialogDismiss() + + if not response: return + if not selected_item: return + if response.get('which') == 'positive': + p = protocols[selected_item[0]] + port = z[p] + return host + ':' + port + ':' + p + + + + +def make_layout(s, scrollable = False): + content = """ + + <LinearLayout + android:id="@+id/zz" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="#ff222222"> + + <TextView + android:id="@+id/textElectrum" + android:text="Electrum" + android:textSize="7pt" + android:textColor="#ff4444ff" + android:gravity="left" + android:layout_height="wrap_content" + android:layout_width="match_parent" + /> + </LinearLayout> + + %s """%s + + if scrollable: + content = """ + <ScrollView + android:id="@+id/scrollview" + android:layout_width="match_parent" + android:layout_height="match_parent" > + + <LinearLayout + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="wrap_content" > + + %s + + </LinearLayout> + </ScrollView> + """%content + + + return """<?xml version="1.0" encoding="utf-8"?> + <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/background" + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:background="#ff000022"> + + %s + </LinearLayout>"""%content + + + + +def main_layout(): + return make_layout(""" + <TextView android:id="@+id/balanceTextView" + android:layout_width="match_parent" + android:text="" + android:textColor="#ffffffff" + android:textAppearance="?android:attr/textAppearanceLarge" + android:padding="7dip" + android:textSize="8pt" + android:gravity="center_vertical|center_horizontal|left"> + </TextView> + + <TextView android:id="@+id/historyTextView" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Recent transactions" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="center_vertical|center_horizontal|center"> + </TextView> + + %s """%get_history_layout(15),True) + + + +def qr_layout(addr): + return make_layout(""" + + <TextView android:id="@+id/addrTextView" + android:layout_width="match_parent" + android:layout_height="50" + android:text="%s" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="center_vertical|center_horizontal|center"> + </TextView> + + <ImageView + android:id="@+id/qrView" + android:gravity="center" + android:layout_width="match_parent" + android:layout_height="350" + android:antialias="false" + android:src="file:///sdcard/sl4a/qrcode.bmp" /> + + <TextView android:id="@+id/labelTextView" + android:layout_width="match_parent" + android:layout_height="50" + android:text="%s" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="center_vertical|center_horizontal|center"> + </TextView> + + """%(addr,wallet.labels.get(addr,'')), True) + +payto_layout = make_layout(""" + + <TextView android:id="@+id/recipientTextView" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Pay to:" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="left"> + </TextView> + + + <EditText android:id="@+id/recipient" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:tag="Tag Me" android:inputType="text"> + </EditText> + + <LinearLayout android:id="@+id/linearLayout1" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + <Button android:id="@+id/buttonQR" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:text="From QR code"></Button> + <Button android:id="@+id/buttonContacts" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:text="From Contacts"></Button> + </LinearLayout> + + + <TextView android:id="@+id/labelTextView" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Description:" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="left"> + </TextView> + + <EditText android:id="@+id/label" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:tag="Tag Me" android:inputType="text"> + </EditText> + + <TextView android:id="@+id/amountLabelTextView" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Amount:" + android:textAppearance="?android:attr/textAppearanceLarge" + android:gravity="left"> + </TextView> + + <EditText android:id="@+id/amount" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:tag="Tag Me" android:inputType="numberDecimal"> + </EditText> + + <LinearLayout android:layout_width="match_parent" + android:layout_height="wrap_content" android:id="@+id/linearLayout1"> + <Button android:id="@+id/buttonPay" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:text="Send"></Button> + </LinearLayout>""",False) + + + +settings_layout = make_layout(""" <ListView + android:id="@+id/myListView" + android:layout_width="match_parent" + android:layout_height="wrap_content" />""") + + + +def get_history_values(n): + values = [] + h = wallet.get_tx_history() + length = min(n, len(h)) + for i in range(length): + tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1] + try: + dt = datetime.datetime.fromtimestamp( timestamp ) + if dt.date() == dt.today().date(): + time_str = str( dt.time() ) + else: + time_str = str( dt.date() ) + except: + time_str = 'pending' + + conf_str = 'v' if conf else 'o' + label, is_default_label = wallet.get_label(tx_hash) + values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label )) + + return values + + +def get_history_layout(n): + rows = "" + i = 0 + values = get_history_values(n) + for v in values: + a,b,c,d = v + color = "#ff00ff00" if a == 'v' else "#ffff0000" + rows += """ + <TableRow> + <TextView + android:id="@+id/hl_%d_col1" + android:layout_column="0" + android:text="%s" + android:textColor="%s" + android:padding="3" /> + <TextView + android:id="@+id/hl_%d_col2" + android:layout_column="1" + android:text="%s" + android:padding="3" /> + <TextView + android:id="@+id/hl_%d_col3" + android:layout_column="2" + android:text="%s" + android:padding="3" /> + <TextView + android:id="@+id/hl_%d_col4" + android:layout_column="3" + android:text="%s" + android:padding="4" /> + </TableRow>"""%(i,a,color,i,b,i,c,i,d) + i += 1 + + output = """ +<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:stretchColumns="0,1,2,3"> + %s +</TableLayout>"""% rows + return output + + +def set_history_layout(n): + values = get_history_values(n) + i = 0 + for v in values: + a,b,c,d = v + droid.fullSetProperty("hl_%d_col1"%i,"text", a) + + if a == 'v': + droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00") + else: + droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000") + + droid.fullSetProperty("hl_%d_col2"%i,"text", b) + droid.fullSetProperty("hl_%d_col3"%i,"text", c) + droid.fullSetProperty("hl_%d_col4"%i,"text", d) + i += 1 + + + + +status_text = '' +def update_layout(): + global status_text + if not wallet.interface.is_connected: + text = "Not connected..." + elif not wallet.up_to_date: + text = "Synchronizing..." + else: + c, u = wallet.get_balance() + text = "Balance:"+format_satoshis(c) + if u : text += ' [' + format_satoshis(u,True).strip() + ']' + + + # vibrate if status changed + if text != status_text: + if status_text and wallet.interface.is_connected and wallet.up_to_date: + droid.vibrate() + status_text = text + + droid.fullSetProperty("balanceTextView", "text", status_text) + + if wallet.up_to_date: + set_history_layout(15) + + + + +def pay_to(recipient, amount, fee, label): + + if wallet.use_encryption: + password = droid.dialogGetPassword('Password').result + if not password: return + else: + password = None + + droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...") + droid.dialogShow() + + try: + tx = wallet.mktx( [(recipient, amount)], password, fee) + except BaseException, e: + modal_dialog('error', e.message) + droid.dialogDismiss() + return + + if label: + self.wallet.labels[tx.hash()] = label + + droid.dialogDismiss() + + r, h = wallet.sendtx( tx ) + if r: + modal_dialog('Payment sent', h) + return True + else: + modal_dialog('Error', h) + + + + + + + +def make_new_contact(): + code = droid.scanBarcode() + r = code.result + if r: + data = r['extras']['SCAN_RESULT'] + if data: + if re.match('^bitcoin:', data): + address, _, _, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question',x)) + elif is_valid(data): + address = data + else: + address = None + if address: + if modal_question('Add to contacts?', address): + wallet.addressbook.append(address) + wallet.save() + else: + modal_dialog('Invalid address', data) + + +do_refresh = False + +def update_callback(): + global do_refresh + print "gui callback", wallet.interface.is_connected, wallet.up_to_date + do_refresh = True + droid.eventPost("refresh",'z') + +def main_loop(): + global do_refresh + + update_layout() + out = None + quitting = False + while out is None: + + event = droid.eventWait(1000).result + if event is None: + if do_refresh: + update_layout() + do_refresh = False + continue + + print "got event in main loop", repr(event) + if event == 'OK': continue + if event is None: continue + if not event.get("name"): continue + + # request 2 taps before we exit + if event["name"]=="key": + if event["data"]["key"] == '4': + if quitting: + out = 'quit' + else: + quitting = True + else: quitting = False + + if event["name"]=="click": + id=event["data"]["id"] + + elif event["name"]=="settings": + out = 'settings' + + elif event["name"] in menu_commands: + out = event["name"] + + if out == 'contacts': + global contact_addr + contact_addr = select_from_contacts() + if contact_addr == 'newcontact': + make_new_contact() + contact_addr = None + if not contact_addr: + out = None + + elif out == "receive": + global receive_addr + receive_addr = select_from_addresses() + if receive_addr: + amount = modal_input('Amount', 'Amount you want receive. ', '', "numberDecimal") + if amount: + receive_addr = 'bitcoin:%s?amount=%s'%(receive_addr, amount) + + if not receive_addr: + out = None + + + return out + + +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') + label = droid.fullQueryDetail("label").result.get('text') + amount = droid.fullQueryDetail('amount').result.get('text') + + if not is_valid(recipient): + modal_dialog('Error','Invalid Bitcoin address') + continue + + try: + amount = int( 100000000 * Decimal(amount) ) + except: + modal_dialog('Error','Invalid amount') + continue + + result = pay_to(recipient, amount, wallet.fee, label) + 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 = r['extras']['SCAN_RESULT'] + if data: + if re.match('^bitcoin:', data): + payto, amount, label, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question', x)) + droid.fullSetProperty("recipient", "text",payto) + droid.fullSetProperty("amount", "text", amount) + droid.fullSetProperty("label", "text", label) + else: + droid.fullSetProperty("recipient", "text", 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 + + +receive_addr = '' +contact_addr = '' +recipient = '' + +def receive_loop(): + out = None + while out is None: + event = droid.eventWait().result + print "got event", event + if event["name"]=="key": + if event["data"]["key"] == '4': + out = 'main' + + elif event["name"]=="clipboard": + droid.setClipboard(receive_addr) + modal_dialog('Address copied to clipboard',receive_addr) + + elif event["name"]=="edit": + edit_label(receive_addr) + + return out + +def contacts_loop(): + global recipient + out = None + while out is None: + event = droid.eventWait().result + print "got event", event + if event["name"]=="key": + if event["data"]["key"] == '4': + out = 'main' + + elif event["name"]=="clipboard": + droid.setClipboard(contact_addr) + modal_dialog('Address copied to clipboard',contact_addr) + + elif event["name"]=="edit": + edit_label(contact_addr) + + elif event["name"]=="paytocontact": + recipient = contact_addr + out = 'send' + + elif event["name"]=="deletecontact": + if modal_question('delete contact', contact_addr): + out = 'main' + + return out + + +def server_dialog(plist): + droid.dialogCreateAlert("Public servers") + droid.dialogSetItems( plist.keys() ) + droid.dialogSetPositiveButtonText('Private server') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + if not response: return + + if response.get('which') == 'positive': + return modal_input('Private server', None) + + i = response.get('item') + if i is not None: + response = plist.keys()[i] + return response + + +def seed_dialog(): + if wallet.use_encryption: + password = droid.dialogGetPassword('Seed').result + if not password: return + else: + password = None + + try: + seed = wallet.decode_seed(password) + except: + modal_dialog('error','incorrect password') + return + + modal_dialog('Your seed is',seed) + modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) ) + +def change_password_dialog(): + if wallet.use_encryption: + password = droid.dialogGetPassword('Your wallet is encrypted').result + if password is None: return + else: + password = None + + try: + seed = wallet.decode_seed(password) + except: + modal_dialog('error','incorrect password') + return + + new_password = droid.dialogGetPassword('Choose a password').result + if new_password == None: + return + + if new_password != '': + password2 = droid.dialogGetPassword('Confirm new password').result + if new_password != password2: + modal_dialog('error','passwords do not match') + return + + wallet.update_password(seed, password, new_password) + if new_password: + modal_dialog('Password updated','your wallet is encrypted') + else: + modal_dialog('No password','your wallet is not encrypted') + return True + + +def settings_loop(): + + + def set_listview(): + server, port, p = interface.server.split(':') + fee = str( Decimal( wallet.fee)/100000000 ) + is_encrypted = 'yes' if wallet.use_encryption else 'no' + protocol = protocol_name(p) + droid.fullShow(settings_layout) + droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed']) + + set_listview() + + out = None + while out is None: + event = droid.eventWait() + event = event.result + print "got event", event + if event == 'OK': continue + if not event: continue + + plist, servers_list = interface.get_servers_list() + name = event.get("name") + if not name: continue + + if name == "itemclick": + pos = event["data"]["position"] + host, port, protocol = interface.server.split(':') + + if pos == "0": #server + host = server_dialog(plist) + if host: + p = plist[host] + port = p['t'] + srv = host + ':' + port + ':t' + wallet.config.set_key("server", srv, True) + try: + wallet.interface.set_server(srv) + except: + modal_dialog('error','invalid server') + set_listview() + + elif pos == "1": #protocol + if host in plist: + srv = protocol_dialog(host, protocol, plist[host]) + if srv: + wallet.config.set_key("server", srv, True) + try: + wallet.interface.set_server(srv) + except: + modal_dialog('error','invalid server') + set_listview() + + elif pos == "2": #port + a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number") + if a_port: + if a_port != port: + srv = host + ':' + a_port + ':'+ protocol + wallet.config.set_key("server", srv, True) + try: + wallet.interface.set_server(srv) + except: + modal_dialog('error','invalid port number') + set_listview() + + elif pos == "3": #fee + fee = modal_input('Transaction fee', 'The fee will be this amount multiplied by the number of inputs in your transaction. ', str( Decimal( wallet.fee)/100000000 ), "numberDecimal") + if fee: + try: + fee = int( 100000000 * Decimal(fee) ) + except: + modal_dialog('error','invalid fee value') + if wallet.fee != fee: + wallet.fee = fee + wallet.save() + set_listview() + + elif pos == "4": + if change_password_dialog(): + set_listview() + + elif pos == "5": + seed_dialog() + + + elif name in menu_commands: + out = event["name"] + + elif name == 'cancel': + out = 'main' + + elif name == "key": + if event["data"]["key"] == '4': + out = 'main' + + return out + +def add_menu(s): + droid.clearOptionsMenu() + if s == 'main': + droid.addOptionsMenuItem("Send","send",None,"") + droid.addOptionsMenuItem("Receive","receive",None,"") + droid.addOptionsMenuItem("Contacts","contacts",None,"") + droid.addOptionsMenuItem("Settings","settings",None,"") + elif s == 'receive': + droid.addOptionsMenuItem("Copy","clipboard",None,"") + droid.addOptionsMenuItem("Label","edit",None,"") + elif s == 'contacts': + droid.addOptionsMenuItem("Copy","clipboard",None,"") + droid.addOptionsMenuItem("Label","edit",None,"") + droid.addOptionsMenuItem("Pay to","paytocontact",None,"") + #droid.addOptionsMenuItem("Delete","deletecontact",None,"") + + +def make_bitmap(addr): + # fixme: this is highly inefficient + droid.dialogCreateSpinnerProgress("please wait") + droid.dialogShow() + try: + import pyqrnative, bmp + qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.L) + qr.addData(addr) + qr.make() + k = qr.getModuleCount() + assert k == 33 + bmp.save_qrcode(qr,"/sdcard/sl4a/qrcode.bmp") + finally: + droid.dialogDismiss() + + + + +droid = android.Android() +menu_commands = ["send", "receive", "settings", "contacts", "main"] +wallet = None +interface = None + +class ElectrumGui: + + def __init__(self, w, config, app=None): + global wallet, interface + wallet = w + interface = wallet.interface + interface.register_callback('updated',update_callback) + interface.register_callback('connected', update_callback) + interface.register_callback('disconnected', update_callback) + interface.register_callback('disconnecting', update_callback) + + + def main(self, url): + s = 'main' + while True: + add_menu(s) + if s == 'main': + droid.fullShow(main_layout()) + s = main_loop() + + elif s == 'send': + droid.fullShow(payto_layout) + s = payto_loop() + + elif s == 'receive': + make_bitmap(receive_addr) + droid.fullShow(qr_layout(receive_addr)) + s = receive_loop() + + elif s == 'contacts': + make_bitmap(contact_addr) + droid.fullShow(qr_layout(contact_addr)) + s = contacts_loop() + + elif s == 'settings': + s = settings_loop() + + else: + break + + droid.makeToast("Bye!") + + def restore_or_create(self): + droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?") + droid.dialogSetPositiveButtonText('Create') + droid.dialogSetNeutralButtonText('Restore') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + if not response: return + if response.get('which') == 'negative': + return + + return 'restore' if response.get('which') == 'neutral' else 'create' + + def seed_dialog(self): + if modal_question("Input method",None,'QR Code', 'mnemonic'): + code = droid.scanBarcode() + r = code.result + if r: + seed = r['extras']['SCAN_RESULT'] + else: + return + else: + m = modal_input('Mnemonic','please enter your code') + try: + seed = mnemonic_decode(m.split(' ')) + except: + modal_dialog('error: could not decode this seed') + return + + gap = 5 # default + + return str(seed), gap + + + def network_dialog(self): + return True + + + def show_seed(self): + modal_dialog('Your seed is:', wallet.seed) + modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) ) + + + def password_dialog(self): + change_password_dialog() + + + def restore_wallet(self): + + msg = "recovering wallet..." + droid.dialogCreateSpinnerProgress("Electrum", msg) + droid.dialogShow() + + wallet.update() + + droid.dialogDismiss() + droid.vibrate() + + if wallet.is_found(): + wallet.fill_addressbook() + modal_dialog("recovery successful") + else: + if not modal_question("no transactions found for this seed","do you want to keep this wallet?"): + return False + + wallet.save() + return True + diff --git a/gui/gui_lite.py b/gui/gui_lite.py @@ -0,0 +1,1007 @@ +import sys + +# Let's do some dep checking and handle missing ones gracefully +try: + from PyQt4.QtCore import * + from PyQt4.QtGui import * + import PyQt4.QtCore as QtCore + +except ImportError: + print "You need to have PyQT installed to run Electrum in graphical mode." + print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'." + sys.exit(0) + +from decimal import Decimal as D +from electrum.util import get_resource_path as rsrc +from electrum.bitcoin import is_valid +from i18n import _ +import decimal +import exchange_rate +import os.path +import random +import re +import time +from electrum import wallet +import webbrowser +import history_widget +import receiving_widget +from electrum import util +import csv +import datetime + +from electrum.version import ELECTRUM_VERSION as electrum_version +from electrum.util import format_satoshis, age +import gui_qt +import shutil + +bitcoin = lambda v: v * 100000000 + +def IconButton(filename, parent=None): + pixmap = QPixmap(filename) + icon = QIcon(pixmap) + return QPushButton(icon, "", parent) + +class Timer(QThread): + def run(self): + while True: + self.emit(SIGNAL('timersignal')) + time.sleep(0.5) + +def resize_line_edit_width(line_edit, text_input): + metrics = QFontMetrics(qApp.font()) + # Create an extra character to add some space on the end + text_input += "A" + line_edit.setMinimumWidth(metrics.width(text_input)) + +def load_theme_name(theme_path): + try: + with open(os.path.join(theme_path, "name.cfg")) as name_cfg_file: + return name_cfg_file.read().rstrip("\n").strip() + except IOError: + return None + + +def theme_dirs_from_prefix(prefix): + if not os.path.exists(prefix): + return [] + theme_paths = {} + for potential_theme in os.listdir(prefix): + theme_full_path = os.path.join(prefix, potential_theme) + theme_css = os.path.join(theme_full_path, "style.css") + if not os.path.exists(theme_css): + continue + theme_name = load_theme_name(theme_full_path) + if theme_name is None: + continue + theme_paths[theme_name] = prefix, potential_theme + return theme_paths + +def load_theme_paths(): + theme_paths = {} + prefixes = (util.local_data_dir(), util.appdata_dir()) + for prefix in prefixes: + theme_paths.update(theme_dirs_from_prefix(prefix)) + return theme_paths + + +def csv_transaction(wallet): + try: + select_export = _('Select file to export your wallet transactions to') + fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-history.csv'), "*.csv") + if fileName: + with open(fileName, "w+") as csvfile: + transaction = csv.writer(csvfile) + transaction.writerow(["transaction_hash","label", "confirmations", "value", "fee", "balance", "timestamp"]) + for item in wallet.get_tx_history(): + tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item + if confirmations: + if timestamp is not None: + try: + time_string = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] + except [RuntimeError, TypeError, NameError] as reason: + time_string = "unknown" + pass + else: + time_string = "unknown" + else: + time_string = "pending" + + if value is not None: + value_string = format_satoshis(value, True, wallet.num_zeros) + else: + value_string = '--' + + if fee is not None: + fee_string = format_satoshis(fee, True, wallet.num_zeros) + else: + fee_string = '0' + + if tx_hash: + label, is_default_label = wallet.get_label(tx_hash) + else: + label = "" + + balance_string = format_satoshis(balance, False, wallet.num_zeros) + transaction.writerow([tx_hash, label, confirmations, value_string, fee_string, balance_string, time_string]) + QMessageBox.information(None,"CSV Export created", "Your CSV export has been successfully created.") + except (IOError, os.error), reason: + export_error_label = _("Electrum was unable to produce a transaction export.") + QMessageBox.critical(None,"Unable to create csv", export_error_label + "\n" + str(reason)) + + +class ElectrumGui(QObject): + + def __init__(self, wallet, config, expert=None): + super(QObject, self).__init__() + + self.wallet = wallet + self.config = config + self.check_qt_version() + self.expert = expert + if self.expert != None: + self.app = self.expert.app + else: + self.app = QApplication(sys.argv) + + def check_qt_version(self): + qtVersion = qVersion() + if not(int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7): + app = QApplication(sys.argv) + QMessageBox.warning(None,"Could not start Lite GUI.", "Electrum was unable to load the 'Lite GUI' because it needs Qt version >= 4.7.\nChanging your config to use the 'Classic' GUI") + self.config.set_key('gui','classic',True) + sys.exit(0) + + + def main(self, url): + actuator = MiniActuator(self.wallet) + # Should probably not modify the current path but instead + # change the behaviour of rsrc(...) + old_path = QDir.currentPath() + actuator.load_theme() + + self.mini = MiniWindow(actuator, self.expand, self.config) + driver = MiniDriver(self.wallet, self.mini) + + # Reset path back to original value now that loading the GUI + # is completed. + QDir.setCurrent(old_path) + + if url: + self.set_url(url) + + if self.expert == None: + timer = Timer() + timer.start() + self.expert = gui_qt.ElectrumWindow(self.wallet, self.config) + self.expert.app = self.app + self.expert.connect_slots(timer) + self.expert.update_wallet() + self.app.exec_() + + def expand(self): + """Hide the lite mode window and show pro-mode.""" + self.config.set_key('gui', 'classic', True) + self.mini.hide() + self.expert.show() + + def set_url(self, url): + payto, amount, label, message, signature, identity, url = \ + self.wallet.parse_url(url, self.show_message, self.show_question) + self.mini.set_payment_fields(payto, amount) + + def show_message(self, message): + QMessageBox.information(self.mini, _("Message"), message, _("OK")) + + def show_question(self, message): + choice = QMessageBox.question(self.mini, _("Message"), message, + QMessageBox.Yes|QMessageBox.No, + QMessageBox.No) + return choice == QMessageBox.Yes + + def restore_or_create(self): + qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app) + return qt_gui_object.restore_or_create() + +class TransactionWindow(QDialog): + + def set_label(self): + label = unicode(self.label_edit.text()) + self.parent.wallet.labels[self.tx_id] = label + + super(TransactionWindow, self).accept() + + 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_() + +class MiniWindow(QDialog): + + def __init__(self, actuator, expand_callback, config): + super(MiniWindow, self).__init__() + tx = "e08115d0f7819aee65b9d24f81ef9d46eb62bb67ddef5318156cbc3ceb7b703e" + + self.actuator = actuator + self.config = config + self.btc_balance = None + self.quote_currencies = ["BRL", "CNY", "EUR", "GBP", "RUB", "USD"] + self.actuator.set_configured_currency(self.set_quote_currency) + self.exchanger = exchange_rate.Exchanger(self) + # Needed because price discovery is done in a different thread + # which needs to be sent back to this main one to update the GUI + self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance) + + self.balance_label = BalanceLabel(self.change_quote_currency) + self.balance_label.setObjectName("balance_label") + + + # Bitcoin address code + self.address_input = QLineEdit() + self.address_input.setPlaceholderText(_("Enter a Bitcoin address or contact")) + self.address_input.setObjectName("address_input") + + self.address_input.setFocusPolicy(Qt.ClickFocus) + + self.address_input.textChanged.connect(self.address_field_changed) + resize_line_edit_width(self.address_input, + "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy") + + self.address_completions = QStringListModel() + address_completer = QCompleter(self.address_input) + address_completer.setCaseSensitivity(False) + address_completer.setModel(self.address_completions) + self.address_input.setCompleter(address_completer) + + address_layout = QHBoxLayout() + address_layout.addWidget(self.address_input) + + self.amount_input = QLineEdit() + self.amount_input.setPlaceholderText(_("... and amount")) + self.amount_input.setObjectName("amount_input") + + self.amount_input.setFocusPolicy(Qt.ClickFocus) + # This is changed according to the user's displayed balance + self.amount_validator = QDoubleValidator(self.amount_input) + self.amount_validator.setNotation(QDoubleValidator.StandardNotation) + self.amount_validator.setDecimals(8) + self.amount_input.setValidator(self.amount_validator) + + # This removes the very ugly OSX highlighting, please leave this in :D + self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0) + self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0) + self.amount_input.textChanged.connect(self.amount_input_changed) + + self.send_button = QPushButton(_("&Send")) + self.send_button.setObjectName("send_button") + self.send_button.setDisabled(True); + self.send_button.clicked.connect(self.send) + + # Creating the receive button + self.switch_button = QPushButton( QIcon(":icons/switchgui.png"),'' ) + self.switch_button.setMaximumWidth(25) + self.switch_button.setFlat(True) + self.switch_button.clicked.connect(expand_callback) + + main_layout = QGridLayout(self) + + main_layout.addWidget(self.balance_label, 0, 0, 1, 3) + main_layout.addWidget(self.switch_button, 0, 3) + + main_layout.addWidget(self.address_input, 1, 0, 1, 4) + main_layout.addWidget(self.amount_input, 2, 0, 1, 2) + main_layout.addWidget(self.send_button, 2, 2, 1, 2) + + self.send_button.setMaximumWidth(125) + + self.history_list = history_widget.HistoryWidget() + self.history_list.setObjectName("history") + self.history_list.hide() + self.history_list.setAlternatingRowColors(True) + + main_layout.addWidget(self.history_list, 3, 0, 1, 4) + + self.receiving = receiving_widget.ReceivingWidget(self) + self.receiving.setObjectName("receiving") + + # Add to the right side + self.receiving_box = QGroupBox(_("Select a receiving address")) + extra_layout = QGridLayout() + + # Checkbox to filter used addresses + hide_used = QCheckBox(_('Hide used addresses')) + hide_used.setChecked(True) + hide_used.stateChanged.connect(self.receiving.toggle_used) + + # Events for receiving addresses + self.receiving.clicked.connect(self.receiving.copy_address) + self.receiving.itemDoubleClicked.connect(self.receiving.edit_label) + self.receiving.itemChanged.connect(self.receiving.update_label) + + + # Label + extra_layout.addWidget( QLabel(_('Selecting an address will copy it to the clipboard.') + '\n' + _('Double clicking the label will allow you to edit it.') ),0,0) + + extra_layout.addWidget(self.receiving, 1,0) + extra_layout.addWidget(hide_used, 2,0) + extra_layout.setColumnMinimumWidth(0,200) + + self.receiving_box.setLayout(extra_layout) + main_layout.addWidget(self.receiving_box,0,4,-1,3) + self.receiving_box.hide() + + # Creating the menu bar + menubar = QMenuBar() + electrum_menu = menubar.addMenu(_("&Electrum")) + + quit_option = electrum_menu.addAction(_("&Close")) + + quit_option.triggered.connect(self.close) + + view_menu = menubar.addMenu(_("&View")) + extra_menu = menubar.addMenu(_("&Extra")) + + backup_wallet = extra_menu.addAction( _("&Create wallet backup")) + backup_wallet.triggered.connect(self.backup_wallet) + + export_csv = extra_menu.addAction( _("&Export transactions to CSV") ) + export_csv.triggered.connect(lambda: csv_transaction(self.actuator.wallet)) + + master_key = extra_menu.addAction( _("Copy master public key to clipboard") ) + master_key.triggered.connect(self.actuator.copy_master_public_key) + + expert_gui = view_menu.addAction(_("&Classic GUI")) + expert_gui.triggered.connect(expand_callback) + 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_toggle = self.config.get("gui_show_receiving",False) + show_receiving.setChecked(show_receiving_toggle) + self.show_receiving = show_receiving + + self.toggle_receiving_layout(show_receiving_toggle) + + + show_history = view_menu.addAction(_("Show History")) + show_history.setCheckable(True) + show_history.toggled.connect(self.show_history) + + help_menu = menubar.addMenu(_("&Help")) + the_website = help_menu.addAction(_("&Website")) + the_website.triggered.connect(self.the_website) + help_menu.addSeparator() + report_bug = help_menu.addAction(_("&Report Bug")) + report_bug.triggered.connect(self.show_report_bug) + show_about = help_menu.addAction(_("&About")) + show_about.triggered.connect(self.show_about) + main_layout.setMenuBar(menubar) + self.main_layout = main_layout + + quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) + quit_shortcut.activated.connect(self.close) + close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self) + close_shortcut.activated.connect(self.close) + + g = self.config.get("winpos-lite",[4, 25, 351, 149]) + self.setGeometry(g[0], g[1], g[2], g[3]) + + show_hist = self.config.get("gui_show_history",False) + show_history.setChecked(show_hist) + self.show_history(show_hist) + + self.setWindowIcon(QIcon(":electrum.png")) + self.setWindowTitle("Electrum") + self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint) + self.layout().setSizeConstraint(QLayout.SetFixedSize) + self.setObjectName("main_window") + self.show() + + + def toggle_theme(self, theme_name): + old_path = QDir.currentPath() + self.actuator.change_theme(theme_name) + # Recompute style globally + qApp.style().unpolish(self) + qApp.style().polish(self) + QDir.setCurrent(old_path) + + def closeEvent(self, event): + g = self.geometry() + self.config.set_key("winpos-lite", [g.left(),g.top(),g.width(),g.height()],True) + self.config.set_key("gui_show_history", self.history_list.isVisible(),True) + self.config.set_key("gui_show_receiving", self.receiving_box.isVisible(),True) + + super(MiniWindow, self).closeEvent(event) + qApp.quit() + + def set_payment_fields(self, dest_address, amount): + self.address_input.setText(dest_address) + self.address_field_changed(dest_address) + self.amount_input.setText(amount) + + def activate(self): + pass + + def deactivate(self): + pass + + def set_quote_currency(self, currency): + """Set and display the fiat currency country.""" + assert currency in self.quote_currencies + self.quote_currencies.remove(currency) + self.quote_currencies.insert(0, currency) + self.refresh_balance() + + def change_quote_currency(self): + self.quote_currencies = \ + self.quote_currencies[1:] + self.quote_currencies[0:1] + self.actuator.set_config_currency(self.quote_currencies[0]) + self.refresh_balance() + + def refresh_balance(self): + if self.btc_balance is None: + # Price has been discovered before wallet has been loaded + # and server connect... so bail. + return + self.set_balances(self.btc_balance) + self.amount_input_changed(self.amount_input.text()) + + def set_balances(self, btc_balance): + """Set the bitcoin balance and update the amount label accordingly.""" + self.btc_balance = btc_balance + quote_text = self.create_quote_text(btc_balance) + if quote_text: + quote_text = "(%s)" % quote_text + btc_balance = "%.2f" % (btc_balance / bitcoin(1)) + self.balance_label.set_balance_text(btc_balance, quote_text) + self.setWindowTitle("Electrum %s - %s BTC" % (electrum_version, btc_balance)) + + def amount_input_changed(self, amount_text): + """Update the number of bitcoins displayed.""" + self.check_button_status() + + try: + amount = D(str(amount_text)) + except decimal.InvalidOperation: + self.balance_label.show_balance() + else: + quote_text = self.create_quote_text(amount * bitcoin(1)) + if quote_text: + self.balance_label.set_amount_text(quote_text) + self.balance_label.show_amount() + else: + self.balance_label.show_balance() + + def create_quote_text(self, btc_balance): + """Return a string copy of the amount fiat currency the + user has in bitcoins.""" + quote_currency = self.quote_currencies[0] + quote_balance = self.exchanger.exchange(btc_balance, quote_currency) + if quote_balance is None: + quote_text = "" + else: + quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)), + quote_currency) + return quote_text + + def send(self): + if self.actuator.send(self.address_input.text(), + self.amount_input.text(), self): + self.address_input.setText("") + self.amount_input.setText("") + + def check_button_status(self): + """Check that the bitcoin address is valid and that something + is entered in the amount before making the send button clickable.""" + try: + value = D(str(self.amount_input.text())) * 10**8 + except decimal.InvalidOperation: + value = None + # self.address_input.property(...) returns a qVariant, not a bool. + # The == is needed to properly invoke a comparison. + if (self.address_input.property("isValid") == True and + value is not None and 0 < value <= self.btc_balance): + self.send_button.setDisabled(False) + else: + self.send_button.setDisabled(True) + + def address_field_changed(self, address): + # label or alias, with address in brackets + match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", + address) + if match2: + address = match2.group(2) + self.address_input.setText(address) + + if is_valid(address): + self.check_button_status() + self.address_input.setProperty("isValid", True) + self.recompute_style(self.address_input) + else: + self.send_button.setDisabled(True) + self.address_input.setProperty("isValid", False) + self.recompute_style(self.address_input) + + if len(address) == 0: + self.address_input.setProperty("isValid", None) + self.recompute_style(self.address_input) + + def recompute_style(self, element): + self.style().unpolish(element) + self.style().polish(element) + + def copy_address(self): + receive_popup = ReceivePopup(self.receive_button) + self.actuator.copy_address(receive_popup) + + def update_completions(self, completions): + self.address_completions.setStringList(completions) + + + def update_history(self, tx_history): + + self.history_list.empty() + + for item in tx_history[-10:]: + tx_hash, conf, is_mine, value, fee, balance, timestamp = item + label = self.actuator.wallet.get_label(tx_hash)[0] + #amount = D(value) / 10**8 + v_str = format_satoshis(value, True) + self.history_list.append(label, v_str, age(timestamp)) + + def acceptbit(self): + self.actuator.acceptbit(self.quote_currencies[0]) + + def the_website(self): + webbrowser.open("http://electrum.org") + + def show_about(self): + QMessageBox.about(self, "Electrum", + _("Version")+" %s" % (electrum_version) + "\n\n" + _("Electrum's focus is speed, with low resource usage and simplifying Bitcoin. You do not need to perform regular backups, because your wallet can be recovered from a secret phrase that you can memorize or write on paper. Startup times are instant because it operates in conjunction with high-performance servers that handle the most complicated parts of the Bitcoin system.")) + + def show_report_bug(self): + QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"), + _("Please report any bugs as issues on github:")+" <a href=\"https://github.com/spesmilo/electrum/issues\">https://github.com/spesmilo/electrum/issues</a>") + + def toggle_receiving_layout(self, toggle_state): + if toggle_state: + self.receiving_box.show() + else: + self.receiving_box.hide() + + def show_history(self, toggle_state): + if toggle_state: + self.main_layout.setRowMinimumHeight(3,200) + self.history_list.show() + else: + self.main_layout.setRowMinimumHeight(3,0) + self.history_list.hide() + + def backup_wallet(self): + try: + folderName = QFileDialog.getExistingDirectory(QWidget(), _('Select folder to save a copy of your wallet to'), os.path.expanduser('~/')) + if folderName: + sourceFile = util.user_dir() + '/electrum.dat' + shutil.copy2(sourceFile, str(folderName)) + QMessageBox.information(None,"Wallet backup created", _("A copy of your wallet file was created in")+" '%s'" % str(folderName)) + except (IOError, os.error), reason: + QMessageBox.critical(None,"Unable to create backup", _("Electrum was unable to copy your wallet file to the specified location.")+"\n" + str(reason)) + + + + +class BalanceLabel(QLabel): + + SHOW_CONNECTING = 1 + SHOW_BALANCE = 2 + SHOW_AMOUNT = 3 + + 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 = "" + + def mousePressEvent(self, event): + """Change the fiat currency selection if window background is clicked.""" + if self.state != self.SHOW_CONNECTING: + self.change_quote_currency() + + def set_balance_text(self, btc_balance, quote_text): + """Set the amount of bitcoins in the gui.""" + if self.state == self.SHOW_CONNECTING: + self.state = self.SHOW_BALANCE + self.balance_text = "<span style='font-size: 18pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text) + if self.state == self.SHOW_BALANCE: + self.setText(self.balance_text) + + def set_amount_text(self, quote_text): + self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text + if self.state == self.SHOW_AMOUNT: + self.setText(self.amount_text) + + def show_balance(self): + if self.state == self.SHOW_AMOUNT: + self.state = self.SHOW_BALANCE + self.setText(self.balance_text) + + def show_amount(self): + if self.state == self.SHOW_BALANCE: + self.state = self.SHOW_AMOUNT + self.setText(self.amount_text) + +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 + +class PasswordDialog(QDialog): + + def __init__(self, parent): + super(QDialog, self).__init__(parent) + + self.setModal(True) + + self.password_input = QLineEdit() + self.password_input.setEchoMode(QLineEdit.Password) + + main_layout = QVBoxLayout(self) + message = _('Please enter your password') + main_layout.addWidget(QLabel(message)) + + grid = QGridLayout() + grid.setSpacing(8) + grid.addWidget(QLabel(_('Password')), 1, 0) + grid.addWidget(self.password_input, 1, 1) + main_layout.addLayout(grid) + + main_layout.addLayout(ok_cancel_buttons(self)) + self.setLayout(main_layout) + + def run(self): + if not self.exec_(): + return + return unicode(self.password_input.text()) + +class ReceivePopup(QDialog): + + def leaveEvent(self, event): + self.close() + + def setup(self, address): + label = QLabel(_("Copied your Bitcoin 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 - " + _("Receive Bitcoin payment")) + self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint| + Qt.MSWindowsFixedSizeDialogHint) + self.layout().setSizeConstraint(QLayout.SetFixedSize) + #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised) + #self.setAlignment(Qt.AlignCenter) + + def popup(self): + parent = self.parent() + top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft()) + self.move(top_left_pos) + center_mouse_pos = self.mapToGlobal(self.rect().center()) + QCursor.setPos(center_mouse_pos) + self.show() + +class MiniActuator: + """Initialize the definitions relating to themes and + sending/receiving bitcoins.""" + + + def __init__(self, wallet): + """Retrieve the gui theme used in previous session.""" + self.wallet = wallet + self.theme_name = self.wallet.config.get('litegui_theme','Cleanlook') + self.themes = load_theme_paths() + + def load_theme(self): + """Load theme retrieved from wallet file.""" + try: + theme_prefix, theme_path = self.themes[self.theme_name] + except KeyError: + util.print_error("Theme not found!", self.theme_name) + return + QDir.setCurrent(os.path.join(theme_prefix, theme_path)) + with open(rsrc("style.css")) as style_file: + qApp.setStyleSheet(style_file.read()) + + def theme_names(self): + """Sort themes.""" + return sorted(self.themes.keys()) + + def selected_theme(self): + """Select theme.""" + return self.theme_name + + def change_theme(self, theme_name): + """Change theme.""" + self.theme_name = theme_name + self.wallet.config.set_key('litegui_theme',theme_name) + self.load_theme() + + def set_configured_currency(self, set_quote_currency): + """Set the inital fiat currency conversion country (USD/EUR/GBP) in + the GUI to what it was set to in the wallet.""" + currency = self.wallet.config.get('conversion_currency') + # currency can be none when Electrum is used for the first + # time and no setting has been created yet. + if currency is not None: + set_quote_currency(currency) + + def set_config_currency(self, conversion_currency): + """Change the wallet fiat currency country.""" + self.wallet.config.set_key('conversion_currency',conversion_currency,True) + + def copy_address(self, receive_popup): + """Copy the wallet addresses into the client.""" + addrs = [addr for addr in self.wallet.addresses(True) + if not self.wallet.is_change(addr)] + # Select most recent addresses from gap limit + addrs = addrs[-self.wallet.gap_limit:] + copied_address = random.choice(addrs) + qApp.clipboard().setText(copied_address) + receive_popup.setup(copied_address) + receive_popup.popup() + + def waiting_dialog(self, f): + s = Timer() + s.start() + w = QDialog() + w.resize(200, 70) + w.setWindowTitle('Electrum') + l = QLabel('Sending transaction, please wait.') + vbox = QVBoxLayout() + vbox.addWidget(l) + w.setLayout(vbox) + w.show() + def ff(): + s = f() + if s: l.setText(s) + else: w.close() + w.connect(s, QtCore.SIGNAL('timersignal'), ff) + w.exec_() + w.destroy() + + + def send(self, address, amount, parent_window): + """Send bitcoins to the target address.""" + dest_address = self.fetch_destination(address) + + if dest_address is None or not is_valid(dest_address): + QMessageBox.warning(parent_window, _('Error'), + _('Invalid Bitcoin Address') + ':\n' + address, _('OK')) + return False + + convert_amount = lambda amount: \ + int(D(unicode(amount)) * bitcoin(1)) + amount = convert_amount(amount) + + if self.wallet.use_encryption: + password_dialog = PasswordDialog(parent_window) + password = password_dialog.run() + if not password: + return + else: + password = None + + fee = 0 + # 0.1 BTC = 10000000 + if amount < bitcoin(1) / 10: + # 0.001 BTC + fee = bitcoin(1) / 1000 + + try: + tx = self.wallet.mktx([(dest_address, amount)], password, fee) + except BaseException as error: + QMessageBox.warning(parent_window, _('Error'), str(error), _('OK')) + return False + + h = self.wallet.send_tx(tx) + + self.waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Sending transaction, please wait...")) + + status, message = self.wallet.receive_tx(h) + + if not status: + import tempfile + dumpf = tempfile.NamedTemporaryFile(delete=False) + dumpf.write(tx) + dumpf.close() + print "Dumped error tx to", dumpf.name + QMessageBox.warning(parent_window, _('Error'), message, _('OK')) + return False + + TransactionWindow(message, self) +# QMessageBox.information(parent_window, '', +# _('Your transaction has been sent.') + '\n' + message, _('OK')) + return True + + def fetch_destination(self, address): + recipient = unicode(address).strip() + + # alias + match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$", + recipient) + + # label or alias, with address in brackets + match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", + recipient) + + if match1: + dest_address = \ + self.wallet.get_alias(recipient, True, + self.show_message, self.question) + return dest_address + elif match2: + return match2.group(2) + else: + return recipient + + + def copy_master_public_key(self): + master_pubkey = self.wallet.master_public_key + qApp.clipboard().setText(master_pubkey) + QMessageBox.information(None, _("Copy successful"), _("Your master public key has been copied to your clipboard.")) + + + def acceptbit(self, currency): + master_pubkey = self.wallet.master_public_key + url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency) + webbrowser.open(url) + + def show_seed_dialog(self): + gui_qt.ElectrumWindow.show_seed_dialog(self.wallet) + +class MiniDriver(QObject): + + INITIALIZING = 0 + CONNECTING = 1 + SYNCHRONIZING = 2 + READY = 3 + + def __init__(self, wallet, window): + super(QObject, self).__init__() + + self.wallet = wallet + self.window = window + + self.wallet.interface.register_callback('updated',self.update_callback) + self.wallet.interface.register_callback('connected', self.update_callback) + self.wallet.interface.register_callback('disconnected', self.update_callback) + + self.state = None + + self.initializing() + self.connect(self, SIGNAL("updatesignal()"), self.update) + self.update_callback() + + # This is a hack to workaround that Qt does not like changing the + # window properties from this other thread before the runloop has + # been called from. + def update_callback(self): + self.emit(SIGNAL("updatesignal()")) + + def update(self): + if not self.wallet.interface: + self.initializing() + elif not self.wallet.interface.is_connected: + self.connecting() + elif not self.wallet.up_to_date: + self.synchronizing() + else: + self.ready() + + if self.wallet.up_to_date: + self.update_balance() + self.update_completions() + self.update_history() + + def initializing(self): + if self.state == self.INITIALIZING: + return + self.state = self.INITIALIZING + self.window.deactivate() + + def connecting(self): + if self.state == self.CONNECTING: + return + self.state = self.CONNECTING + self.window.deactivate() + + def synchronizing(self): + if self.state == self.SYNCHRONIZING: + return + self.state = self.SYNCHRONIZING + self.window.deactivate() + + def ready(self): + if self.state == self.READY: + return + self.state = self.READY + self.window.activate() + + def update_balance(self): + conf_balance, unconf_balance = self.wallet.get_balance() + balance = D(conf_balance + unconf_balance) + self.window.set_balances(balance) + + def update_completions(self): + completions = [] + for addr, label in self.wallet.labels.items(): + if addr in self.wallet.addressbook: + completions.append("%s <%s>" % (label, addr)) + completions = completions + self.wallet.aliases.keys() + self.window.update_completions(completions) + + def update_history(self): + tx_history = self.wallet.get_tx_history() + self.window.update_history(tx_history) + + +if __name__ == "__main__": + app = QApplication(sys.argv) + with open(rsrc("style.css")) as style_file: + app.setStyleSheet(style_file.read()) + mini = MiniWindow() + sys.exit(app.exec_()) + diff --git a/gui/gui_qt.py b/gui/gui_qt.py @@ -0,0 +1,2539 @@ +#!/usr/bin/env python +# +# Electrum - lightweight Bitcoin client +# Copyright (C) 2012 thomasv@gitorious +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import sys, time, datetime, re +from i18n import _, set_language +from electrum.util import print_error +import os.path, json, ast + +try: + import PyQt4 +except: + sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") + +from PyQt4.QtGui import * +from PyQt4.QtCore import * +import PyQt4.QtCore as QtCore +import PyQt4.QtGui as QtGui +from electrum.interface import DEFAULT_SERVERS + +try: + import icons_rc +except: + sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o lib/icons_rc.py'") + +from electrum.wallet import format_satoshis +from electrum.bitcoin import Transaction, is_valid +from electrum import mnemonic + +import bmp, pyqrnative, qrscanner +import exchange_rate + +from decimal import Decimal + +import platform +import httplib +import socket +import webbrowser +import csv + +if platform.system() == 'Windows': + MONOSPACE_FONT = 'Lucida Console' +elif platform.system() == 'Darwin': + MONOSPACE_FONT = 'Monaco' +else: + MONOSPACE_FONT = 'monospace' + +ALIAS_REGEXP = '^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$' + +from electrum import ELECTRUM_VERSION +import re + +class UpdateLabel(QtGui.QLabel): + def __init__(self, config, parent=None): + QtGui.QLabel.__init__(self, parent) + self.new_version = False + + try: + con = httplib.HTTPConnection('electrum.org', 80, timeout=5) + con.request("GET", "/version") + res = con.getresponse() + except socket.error as msg: + print_error("Could not retrieve version information") + return + + if res.status == 200: + self.latest_version = res.read() + self.latest_version = self.latest_version.replace("\n","") + if(re.match('^\d+(\.\d+)*$', self.latest_version)): + self.config = config + self.current_version = ELECTRUM_VERSION + if(self.compare_versions(self.latest_version, self.current_version) == 1): + latest_seen = self.config.get("last_seen_version",ELECTRUM_VERSION) + if(self.compare_versions(self.latest_version, latest_seen) == 1): + self.new_version = True + self.setText(_("New version available") + ": " + self.latest_version) + + + def compare_versions(self, version1, version2): + def normalize(v): + return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] + return cmp(normalize(version1), normalize(version2)) + + def ignore_this_version(self): + self.setText("") + self.config.set_key("last_seen_version", self.latest_version, True) + QMessageBox.information(self, _("Preference saved"), _("Notifications about this update will not be shown again.")) + self.dialog.done(0) + + def ignore_all_version(self): + self.setText("") + self.config.set_key("last_seen_version", "9.9.9", True) + QMessageBox.information(self, _("Preference saved"), _("No more notifications about version updates will be shown.")) + self.dialog.done(0) + + def open_website(self): + webbrowser.open("http://electrum.org/download.html") + self.dialog.done(0) + + 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 numbify(entry, is_int = False): + text = unicode(entry.text()).strip() + pos = entry.cursorPosition() + chars = '0123456789' + if not is_int: chars +='.' + s = ''.join([i for i in text if i in chars]) + if not is_int: + if '.' in s: + p = s.find('.') + s = s.replace('.','') + s = s[:p] + '.' + s[p:p+8] + try: + amount = int( Decimal(s) * 100000000 ) + except: + amount = None + else: + try: + amount = int( s ) + except: + amount = None + entry.setText(s) + entry.setCursorPosition(pos) + return amount + + +class Timer(QtCore.QThread): + def run(self): + while True: + self.emit(QtCore.SIGNAL('timersignal')) + time.sleep(0.5) + +class HelpButton(QPushButton): + def __init__(self, text): + QPushButton.__init__(self, '?') + self.setFocusPolicy(Qt.NoFocus) + self.setFixedWidth(20) + self.clicked.connect(lambda: QMessageBox.information(self, 'Help', text, 'OK') ) + + +class EnterButton(QPushButton): + def __init__(self, text, func): + QPushButton.__init__(self, text) + self.func = func + self.clicked.connect(func) + + def keyPressEvent(self, e): + if e.key() == QtCore.Qt.Key_Return: + apply(self.func,()) + +class MyTreeWidget(QTreeWidget): + def __init__(self, parent): + QTreeWidget.__init__(self, parent) + def ddfr(item): + if not item: return + for i in range(0,self.viewport().height()/5): + if self.itemAt(QPoint(0,i*5)) == item: + break + else: + return + for j in range(0,30): + if self.itemAt(QPoint(0,i*5 + j)) != item: + break + self.emit(SIGNAL('customContextMenuRequested(const QPoint&)'), QPoint(50, i*5 + j - 1)) + + self.connect(self, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), ddfr) + + + + +class StatusBarButton(QPushButton): + def __init__(self, icon, tooltip, func): + QPushButton.__init__(self, icon, '') + self.setToolTip(tooltip) + self.setFlat(True) + self.setMaximumWidth(25) + self.clicked.connect(func) + self.func = func + + def keyPressEvent(self, e): + if e.key() == QtCore.Qt.Key_Return: + apply(self.func,()) + + +class QRCodeWidget(QWidget): + + def __init__(self, data = None, size=4): + QWidget.__init__(self) + self.setMinimumSize(210, 210) + self.addr = None + self.qr = None + self.size = size + if data: + self.set_addr(data) + self.update_qr() + + def set_addr(self, addr): + if self.addr != addr: + self.addr = addr + self.qr = None + self.update() + + def update_qr(self): + if self.addr and not self.qr: + self.qr = pyqrnative.QRCode(self.size, pyqrnative.QRErrorCorrectLevel.L) + self.qr.addData(self.addr) + self.qr.make() + self.update() + + def paintEvent(self, e): + + if not self.addr: + return + + black = QColor(0, 0, 0, 255) + white = QColor(255, 255, 255, 255) + + if not self.qr: + qp = QtGui.QPainter() + qp.begin(self) + qp.setBrush(white) + qp.setPen(white) + qp.drawRect(0, 0, 198, 198) + qp.end() + return + + k = self.qr.getModuleCount() + qp = QtGui.QPainter() + qp.begin(self) + r = qp.viewport() + boxsize = min(r.width(), r.height())*0.8/k + size = k*boxsize + left = (r.width() - size)/2 + top = (r.height() - size)/2 + + for r in range(k): + for c in range(k): + if self.qr.isDark(r, c): + qp.setBrush(black) + qp.setPen(black) + else: + qp.setBrush(white) + qp.setPen(white) + qp.drawRect(left+c*boxsize, top+r*boxsize, boxsize, boxsize) + qp.end() + + + +class QR_Window(QWidget): + + def __init__(self, exchanger): + QWidget.__init__(self) + self.exchanger = exchanger + self.setWindowTitle('Electrum - '+_('Invoice')) + self.setMinimumSize(800, 250) + self.address = '' + self.labe = '' + 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 set_content(self, addr, label, amount, currency): + self.address = addr + address_text = "<span style='font-size: 18pt'>%s</span>" % addr if addr else "" + self.address_label.setText(address_text) + + if currency == 'BTC': currency = None + amount_text = '' + if amount: + if currency: + self.amount = Decimal(amount) / self.exchanger.exchange(1, currency) if currency else amount + else: + self.amount = Decimal(amount) + self.amount = self.amount.quantize(Decimal('1.0000')) + + if currency: + amount_text += "<span style='font-size: 18pt'>%s %s</span><br/>" % (amount, currency) + amount_text += "<span style='font-size: 21pt'>%s</span> <span style='font-size: 16pt'>BTC</span> " % str(self.amount) + self.amount_label.setText(amount_text) + + self.label = label + label_text = "<span style='font-size: 21pt'>%s</span>" % label if label else "" + self.label_label.setText(label_text) + + msg = 'bitcoin:'+self.address + if self.amount is not None: + msg += '?amount=%s'%(str( self.amount)) + if self.label is not None: + msg += '&label=%s'%(self.label) + elif self.label is not None: + msg += '?label=%s'%(self.label) + + self.qrw.set_addr( msg ) + + + + +def waiting_dialog(f): + + s = Timer() + s.start() + w = QDialog() + w.resize(200, 70) + w.setWindowTitle('Electrum') + l = QLabel('') + vbox = QVBoxLayout() + vbox.addWidget(l) + w.setLayout(vbox) + w.show() + def ff(): + s = f() + if s: l.setText(s) + else: w.close() + w.connect(s, QtCore.SIGNAL('timersignal'), ff) + w.exec_() + w.destroy() + + +def ok_cancel_buttons(dialog): + hbox = QHBoxLayout() + hbox.addStretch(1) + b = QPushButton("OK") + hbox.addWidget(b) + b.clicked.connect(dialog.accept) + b = QPushButton("Cancel") + hbox.addWidget(b) + b.clicked.connect(dialog.reject) + return hbox + + +default_column_widths = { "history":[40,140,350,140], "contacts":[350,330], + "receive":[[310],[310,200,130,130],[310,200,130,130]] } + +class ElectrumWindow(QMainWindow): + + def __init__(self, wallet, config): + QMainWindow.__init__(self) + self.lite = None + self.wallet = wallet + self.config = config + self.wallet.interface.register_callback('updated', self.update_callback) + self.wallet.interface.register_callback('banner', lambda: self.emit(QtCore.SIGNAL('banner_signal')) ) + self.wallet.interface.register_callback('disconnected', self.update_callback) + self.wallet.interface.register_callback('disconnecting', self.update_callback) + + self.receive_tab_mode = config.get('qt_receive_tab_mode', 0) + self.merchant_name = config.get('merchant_name', 'Invoice') + + set_language(config.get('language')) + + self.qr_window = None + self.funds_error = False + self.completions = QStringListModel() + + self.tabs = tabs = QTabWidget(self) + self.column_widths = self.config.get("column-widths", default_column_widths ) + tabs.addTab(self.create_history_tab(), _('History') ) + tabs.addTab(self.create_send_tab(), _('Send') ) + tabs.addTab(self.create_receive_tab(), _('Receive') ) + tabs.addTab(self.create_contacts_tab(), _('Contacts') ) + tabs.addTab(self.create_console_tab(), _('Console') ) + tabs.setMinimumSize(600, 400) + tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.setCentralWidget(tabs) + self.create_status_bar() + + g = self.config.get("winpos-qt",[100, 100, 840, 400]) + self.setGeometry(g[0], g[1], g[2], g[3]) + title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.config.path + if not self.wallet.seed: title += ' [%s]' % (_('seedless')) + self.setWindowTitle( title ) + + QShortcut(QKeySequence("Ctrl+W"), self, self.close) + QShortcut(QKeySequence("Ctrl+Q"), self, self.close) + QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() )) + QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() )) + + self.connect(self, QtCore.SIGNAL('updatesignal'), self.update_wallet) + self.connect(self, QtCore.SIGNAL('banner_signal'), lambda: self.console.showMessage(self.wallet.banner) ) + self.history_list.setFocus(True) + + self.exchanger = exchange_rate.Exchanger(self) + self.toggle_QR_window(self.receive_tab_mode == 2) + self.connect(self, SIGNAL("refresh_balance()"), self.update_wallet) + + # dark magic fix by flatfly; https://bitcointalk.org/index.php?topic=73651.msg959913#msg959913 + if platform.system() == 'Windows': + n = 3 if self.wallet.seed else 2 + tabs.setCurrentIndex (n) + tabs.setCurrentIndex (0) + + # set initial message + self.console.showMessage(self.wallet.banner) + + def close(self): + QMainWindow.close(self) + if self.qr_window: + self.qr_window.close() + self.qr_window = None + + def connect_slots(self, sender): + self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions) + self.previous_payto_e='' + + def timer_actions(self): + if self.qr_window: + self.qr_window.qrw.update_qr() + + if self.payto_e.hasFocus(): + return + r = unicode( self.payto_e.text() ) + if r != self.previous_payto_e: + self.previous_payto_e = r + r = r.strip() + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): + try: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + except: + return + if to_address: + s = r + ' <' + to_address + '>' + self.payto_e.setText(s) + + + def update_callback(self): + self.emit(QtCore.SIGNAL('updatesignal')) + + def update_wallet(self): + if self.wallet.interface and self.wallet.interface.is_connected: + if not self.wallet.up_to_date: + text = _("Synchronizing...") + icon = QIcon(":icons/status_waiting.png") + else: + c, u = self.wallet.get_balance() + text = _( "Balance" ) + ": %s "%( format_satoshis(c,False,self.wallet.num_zeros) ) + if u: text += "[%s unconfirmed]"%( format_satoshis(u,True,self.wallet.num_zeros).strip() ) + text += self.create_quote_text(Decimal(c+u)/100000000) + icon = QIcon(":icons/status_connected.png") + else: + text = _("Not connected") + icon = QIcon(":icons/status_disconnected.png") + + self.status_text = text + self.statusBar().showMessage(text) + self.status_button.setIcon( icon ) + + if self.wallet.up_to_date or not self.wallet.interface.is_connected: + self.update_history_tab() + self.update_receive_tab() + self.update_contacts_tab() + self.update_completions() + + + def create_quote_text(self, btc_balance): + quote_currency = self.config.get("currency", "None") + quote_balance = self.exchanger.exchange(btc_balance, quote_currency) + if quote_balance is None: + quote_text = "" + else: + quote_text = " (%.2f %s)" % (quote_balance, quote_currency) + return quote_text + + def create_history_tab(self): + self.history_list = l = MyTreeWidget(self) + l.setColumnCount(5) + for i,width in enumerate(self.column_widths['history']): + l.setColumnWidth(i, width) + l.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] ) + self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked) + self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed) + + l.setContextMenuPolicy(Qt.CustomContextMenu) + l.customContextMenuRequested.connect(self.create_history_menu) + return l + + + def create_history_menu(self, position): + self.history_list.selectedIndexes() + item = self.history_list.currentItem() + if not item: return + tx_hash = str(item.data(0, Qt.UserRole).toString()) + if not tx_hash: return + menu = QMenu() + #menu.addAction(_("Copy ID to Clipboard"), lambda: self.app.clipboard().setText(tx_hash)) + menu.addAction(_("Details"), lambda: self.show_tx_details(self.wallet.transactions.get(tx_hash))) + menu.addAction(_("Edit description"), lambda: self.tx_label_clicked(item,2)) + menu.exec_(self.contacts_list.viewport().mapToGlobal(position)) + + + def show_tx_details(self, tx): + dialog = QDialog(None) + dialog.setModal(1) + dialog.setWindowTitle(_("Transaction Details")) + vbox = QVBoxLayout() + dialog.setLayout(vbox) + dialog.setMinimumSize(600,300) + + tx_hash = tx.hash() + if tx_hash in self.wallet.transactions.keys(): + is_mine, v, fee = self.wallet.get_tx_value(tx) + conf, timestamp = self.wallet.verifier.get_confirmations(tx_hash) + if timestamp: + time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] + else: + time_str = 'pending' + else: + is_mine = False + + vbox.addWidget(QLabel("Transaction ID:")) + e = QLineEdit(tx_hash) + e.setReadOnly(True) + vbox.addWidget(e) + + vbox.addWidget(QLabel("Date: %s"%time_str)) + vbox.addWidget(QLabel("Status: %d confirmations"%conf)) + if is_mine: + if fee: + vbox.addWidget(QLabel("Amount sent: %s"% format_satoshis(v-fee, False))) + vbox.addWidget(QLabel("Transaction fee: %s"% format_satoshis(fee, False))) + else: + vbox.addWidget(QLabel("Amount sent: %s"% format_satoshis(v, False))) + vbox.addWidget(QLabel("Transaction fee: unknown")) + else: + vbox.addWidget(QLabel("Amount received: %s"% format_satoshis(v, False))) + + vbox.addWidget( self.generate_transaction_information_widget(tx) ) + + ok_button = QPushButton(_("Close")) + ok_button.setDefault(True) + ok_button.clicked.connect(dialog.accept) + + hbox = QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(ok_button) + vbox.addLayout(hbox) + dialog.exec_() + + def tx_label_clicked(self, item, column): + if column==2 and item.isSelected(): + self.is_edit=True + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + self.history_list.editItem( item, column ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + self.is_edit=False + + def tx_label_changed(self, item, column): + if self.is_edit: + return + self.is_edit=True + tx_hash = str(item.data(0, Qt.UserRole).toString()) + tx = self.wallet.transactions.get(tx_hash) + s = self.wallet.labels.get(tx_hash) + text = unicode( item.text(2) ) + if text: + self.wallet.labels[tx_hash] = text + item.setForeground(2, QBrush(QColor('black'))) + else: + if s: self.wallet.labels.pop(tx_hash) + text = self.wallet.get_default_label(tx_hash) + item.setText(2, text) + item.setForeground(2, QBrush(QColor('gray'))) + self.is_edit=False + + + def edit_label(self, is_recv): + l = self.receive_list if is_recv else self.contacts_list + c = 2 if is_recv else 1 + item = l.currentItem() + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + l.editItem( item, c ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + + def edit_amount(self): + l = self.receive_list + item = l.currentItem() + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + l.editItem( item, 3 ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + + + def address_label_clicked(self, item, column, l, column_addr, column_label): + if column == column_label and item.isSelected(): + addr = unicode( item.text(column_addr) ) + label = unicode( item.text(column_label) ) + if label in self.wallet.aliases.keys(): + return + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + l.editItem( item, column ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + + + def address_label_changed(self, item, column, l, column_addr, column_label): + + if column == column_label: + addr = unicode( item.text(column_addr) ) + text = unicode( item.text(column_label) ) + changed = False + + if text: + if text not in self.wallet.aliases.keys(): + old_addr = self.wallet.labels.get(text) + if old_addr != addr: + self.wallet.labels[addr] = text + changed = True + else: + print_error("Error: This is one of your aliases") + label = self.wallet.labels.get(addr,'') + item.setText(column_label, QString(label)) + else: + s = self.wallet.labels.get(addr) + if s: + self.wallet.labels.pop(addr) + changed = True + + if changed: + self.update_history_tab() + self.update_completions() + + self.recv_changed(item) + + if column == 2: + address = str( item.text(column_addr) ) + text = str( item.text(3) ) + try: + index = self.wallet.addresses.index(address) + except: + return + + text = text.strip().upper() + m = re.match('^(\d+(|\.\d*))\s*(|BTC|EUR|USD|GBP|CNY|JPY|RUB|BRL)$', text) + if m: + amount = m.group(1) + currency = m.group(3) + if not currency: + currency = 'BTC' + else: + currency = currency.upper() + self.wallet.requested_amounts[address] = (amount, currency) + + label = self.wallet.labels.get(address) + if label is None: + label = self.merchant_name + ' - %04d'%(index+1) + self.wallet.labels[address] = label + + if self.qr_window: + self.qr_window.set_content( address, label, amount, currency ) + + else: + item.setText(3,'') + if address in self.wallet.requested_amounts: + self.wallet.requested_amounts.pop(address) + + self.update_receive_item(self.receive_list.currentItem()) + + + def recv_changed(self, a): + "current item changed" + if a is not None and self.qr_window and self.qr_window.isVisible(): + address = str(a.text(1)) + label = self.wallet.labels.get(address) + try: + amount, currency = self.wallet.requested_amounts.get(address, (None, None)) + except: + amount, currency = None, None + self.qr_window.set_content( address, label, amount, currency ) + + + def update_history_tab(self): + + self.history_list.clear() + for item in self.wallet.get_tx_history(): + tx_hash, conf, is_mine, value, fee, balance, timestamp = item + if conf: + try: + time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] + except: + time_str = "unknown" + if conf == -1: + icon = None + if conf == 0: + icon = QIcon(":icons/unconfirmed.png") + elif conf < 6: + icon = QIcon(":icons/clock%d.png"%conf) + else: + icon = QIcon(":icons/confirmed.png") + else: + time_str = 'pending' + icon = QIcon(":icons/unconfirmed.png") + + if value is not None: + v_str = format_satoshis(value, True, self.wallet.num_zeros) + else: + v_str = '--' + + balance_str = format_satoshis(balance, False, self.wallet.num_zeros) + + if tx_hash: + label, is_default_label = self.wallet.get_label(tx_hash) + else: + label = _('Pruned transaction outputs') + is_default_label = False + + item = QTreeWidgetItem( [ '', time_str, label, v_str, balance_str] ) + item.setFont(2, QFont(MONOSPACE_FONT)) + item.setFont(3, QFont(MONOSPACE_FONT)) + item.setFont(4, QFont(MONOSPACE_FONT)) + if value < 0: + item.setForeground(3, QBrush(QColor("#BC1E1E"))) + if tx_hash: + item.setData(0, Qt.UserRole, tx_hash) + item.setToolTip(0, "%d %s\nTxId:%s" % (conf, _('Confirmations'), tx_hash) ) + if is_default_label: + item.setForeground(2, QBrush(QColor('grey'))) + + item.setIcon(0, icon) + self.history_list.insertTopLevelItem(0,item) + + + self.history_list.setCurrentItem(self.history_list.topLevelItem(0)) + + + def create_send_tab(self): + w = QWidget() + + grid = QGridLayout() + grid.setSpacing(8) + grid.setColumnMinimumWidth(3,300) + grid.setColumnStretch(5,1) + + self.payto_e = QLineEdit() + grid.addWidget(QLabel(_('Pay to')), 1, 0) + grid.addWidget(self.payto_e, 1, 1, 1, 3) + + def fill_from_qr(): + qrcode = qrscanner.scan_qr() + if 'address' in qrcode: + self.payto_e.setText(qrcode['address']) + if 'amount' in qrcode: + self.amount_e.setText(str(qrcode['amount'])) + if 'label' in qrcode: + self.message_e.setText(qrcode['label']) + if 'message' in qrcode: + self.message_e.setText("%s (%s)" % (self.message_e.text(), qrcode['message'])) + + + if qrscanner.is_available(): + b = QPushButton(_("Scan QR code")) + b.clicked.connect(fill_from_qr) + grid.addWidget(b, 1, 5) + + grid.addWidget(HelpButton(_('Recipient of the funds.') + '\n\n' + _('You may enter a Bitcoin address, a label from your list of contacts (a list of completions will be proposed), or an alias (email-like address that forwards to a Bitcoin address)')), 1, 4) + + completer = QCompleter() + completer.setCaseSensitivity(False) + self.payto_e.setCompleter(completer) + completer.setModel(self.completions) + + self.message_e = QLineEdit() + grid.addWidget(QLabel(_('Description')), 2, 0) + grid.addWidget(self.message_e, 2, 1, 1, 3) + grid.addWidget(HelpButton(_('Description of the transaction (not mandatory).') + '\n\n' + _('The description is not sent to the recipient of the funds. It is stored in your wallet file, and displayed in the \'History\' tab.')), 2, 4) + + self.amount_e = QLineEdit() + grid.addWidget(QLabel(_('Amount')), 3, 0) + grid.addWidget(self.amount_e, 3, 1, 1, 2) + grid.addWidget(HelpButton( + _('Amount to be sent.') + '\n\n' \ + + _('The amount will be displayed in red if you do not have enough funds in your wallet. Note that if you have frozen some of your addresses, the available funds will be lower than your total balance.')), 3, 3) + + self.fee_e = QLineEdit() + grid.addWidget(QLabel(_('Fee')), 4, 0) + grid.addWidget(self.fee_e, 4, 1, 1, 2) + grid.addWidget(HelpButton( + _('Bitcoin transactions are in general not free. A transaction fee is paid by the sender of the funds.') + '\n\n'\ + + _('The amount of fee can be decided freely by the sender. However, transactions with low fees take more time to be processed.') + '\n\n'\ + + _('A suggested fee is automatically added to this field. You may override it. The suggested fee increases with the size of the transaction.')), 4, 3) + b = '' + if self.wallet.seed: + b = EnterButton(_("Send"), self.do_send) + else: + b = EnterButton(_("Create unsigned transaction"), self.do_send) + grid.addWidget(b, 6, 1) + + b = EnterButton(_("Clear"),self.do_clear) + grid.addWidget(b, 6, 2) + + self.payto_sig = QLabel('') + grid.addWidget(self.payto_sig, 7, 0, 1, 4) + + QShortcut(QKeySequence("Up"), w, w.focusPreviousChild) + QShortcut(QKeySequence("Down"), w, w.focusNextChild) + w.setLayout(grid) + + w2 = QWidget() + vbox = QVBoxLayout() + vbox.addWidget(w) + vbox.addStretch(1) + w2.setLayout(vbox) + + def entry_changed( is_fee ): + self.funds_error = False + amount = numbify(self.amount_e) + fee = numbify(self.fee_e) + if not is_fee: fee = None + if amount is None: + return + inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) + if not is_fee: + self.fee_e.setText( str( Decimal( fee ) / 100000000 ) ) + if inputs: + palette = QPalette() + palette.setColor(self.amount_e.foregroundRole(), QColor('black')) + text = self.status_text + else: + palette = QPalette() + palette.setColor(self.amount_e.foregroundRole(), QColor('red')) + self.funds_error = True + text = _( "Not enough funds" ) + + self.statusBar().showMessage(text) + self.amount_e.setPalette(palette) + self.fee_e.setPalette(palette) + + self.amount_e.textChanged.connect(lambda: entry_changed(False) ) + self.fee_e.textChanged.connect(lambda: entry_changed(True) ) + + return w2 + + + def update_completions(self): + l = [] + for addr,label in self.wallet.labels.items(): + if addr in self.wallet.addressbook: + l.append( label + ' <' + addr + '>') + l = l + self.wallet.aliases.keys() + + self.completions.setStringList(l) + + + + def do_send(self): + + label = unicode( self.message_e.text() ) + r = unicode( self.payto_e.text() ) + r = r.strip() + + # alias + m1 = re.match(ALIAS_REGEXP, r) + # label or alias, with address in brackets + m2 = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) + + if m1: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + if not to_address: + return + elif m2: + to_address = m2.group(2) + else: + to_address = r + + if not is_valid(to_address): + QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK')) + return + + try: + amount = int( Decimal( unicode( self.amount_e.text())) * 100000000 ) + except: + QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK')) + return + try: + fee = int( Decimal( unicode( self.fee_e.text())) * 100000000 ) + except: + QMessageBox.warning(self, _('Error'), _('Invalid Fee'), _('OK')) + return + + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + tx = self.wallet.mktx( [(to_address, amount)], password, fee) + except BaseException, e: + self.show_message(str(e)) + return + + if label: + self.wallet.labels[tx.hash()] = label + + if tx.is_complete: + h = self.wallet.send_tx(tx) + waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Please wait...")) + status, msg = self.wallet.receive_tx( h ) + if status: + QMessageBox.information(self, '', _('Payment sent.')+'\n'+msg, _('OK')) + self.do_clear() + self.update_contacts_tab() + else: + QMessageBox.warning(self, _('Error'), msg, _('OK')) + else: + filename = 'unsigned_tx_%s' % (time.mktime(time.gmtime())) + try: + fileName = QFileDialog.getSaveFileName(QWidget(), _("Select a transaction filename"), os.path.expanduser('~/%s' % (filename))) + with open(fileName,'w') as f: + f.write(json.dumps(tx.as_dict(),indent=4) + '\n') + QMessageBox.information(self, _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK')) + except: + QMessageBox.warning(self, _('Error'), _('Could not write transaction to file'), _('OK')) + + + + + def set_url(self, url): + payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) + self.tabs.setCurrentIndex(1) + label = self.wallet.labels.get(payto) + m_addr = label + ' <'+ payto+'>' if label else payto + self.payto_e.setText(m_addr) + + self.message_e.setText(message) + self.amount_e.setText(amount) + if identity: + self.set_frozen(self.payto_e,True) + self.set_frozen(self.amount_e,True) + self.set_frozen(self.message_e,True) + self.payto_sig.setText( ' The bitcoin URI was signed by ' + identity ) + else: + self.payto_sig.setVisible(False) + + def do_clear(self): + self.payto_sig.setVisible(False) + for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]: + e.setText('') + self.set_frozen(e,False) + + def set_frozen(self,entry,frozen): + if frozen: + entry.setReadOnly(True) + entry.setFrame(False) + palette = QPalette() + palette.setColor(entry.backgroundRole(), QColor('lightgray')) + entry.setPalette(palette) + else: + entry.setReadOnly(False) + entry.setFrame(True) + palette = QPalette() + palette.setColor(entry.backgroundRole(), QColor('white')) + entry.setPalette(palette) + + + def toggle_freeze(self,addr): + if not addr: return + if addr in self.wallet.frozen_addresses: + self.wallet.unfreeze(addr) + else: + self.wallet.freeze(addr) + self.update_receive_tab() + + def toggle_priority(self,addr): + if not addr: return + if addr in self.wallet.prioritized_addresses: + self.wallet.unprioritize(addr) + else: + self.wallet.prioritize(addr) + self.update_receive_tab() + + + def create_list_tab(self, headers): + "generic tab creation method" + l = MyTreeWidget(self) + l.setColumnCount( len(headers) ) + l.setHeaderLabels( headers ) + + w = QWidget() + vbox = QVBoxLayout() + w.setLayout(vbox) + + vbox.setMargin(0) + vbox.setSpacing(0) + vbox.addWidget(l) + buttons = QWidget() + vbox.addWidget(buttons) + + hbox = QHBoxLayout() + hbox.setMargin(0) + hbox.setSpacing(0) + buttons.setLayout(hbox) + + return l,w,hbox + + + def create_receive_tab(self): + l,w,hbox = self.create_list_tab([ _('Address'), _('Label'), _('Requested'), _('Balance'), _('Tx')]) + l.setContextMenuPolicy(Qt.CustomContextMenu) + l.customContextMenuRequested.connect(self.create_receive_menu) + self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1)) + self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1)) + self.connect(l, SIGNAL('currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)'), lambda a,b: self.recv_changed(a)) + self.receive_list = l + self.receive_buttons_hbox = hbox + hbox.addStretch(1) + return w + + + def receive_tab_set_mode(self, i): + self.save_column_widths() + self.receive_tab_mode = i + self.config.set_key('qt_receive_tab_mode', self.receive_tab_mode, True) + self.wallet.save() + self.update_receive_tab() + self.toggle_QR_window(self.receive_tab_mode == 2) + + + def save_column_widths(self): + if self.receive_tab_mode == 0: + widths = [ self.receive_list.columnWidth(0) ] + else: + widths = [] + for i in range(self.receive_list.columnCount() -1): + widths.append(self.receive_list.columnWidth(i)) + self.column_widths["receive"][self.receive_tab_mode] = widths + + self.column_widths["history"] = [] + for i in range(self.history_list.columnCount() - 1): + self.column_widths["history"].append(self.history_list.columnWidth(i)) + + self.column_widths["contacts"] = [] + for i in range(self.contacts_list.columnCount() - 1): + self.column_widths["contacts"].append(self.contacts_list.columnWidth(i)) + + + def create_contacts_tab(self): + l,w,hbox = self.create_list_tab([_('Address'), _('Label'), _('Tx')]) + l.setContextMenuPolicy(Qt.CustomContextMenu) + l.customContextMenuRequested.connect(self.create_contact_menu) + for i,width in enumerate(self.column_widths['contacts']): + l.setColumnWidth(i, width) + + self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1)) + self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1)) + self.contacts_list = l + self.contacts_buttons_hbox = hbox + hbox.addWidget(EnterButton(_("New"), self.new_contact_dialog)) + hbox.addStretch(1) + return w + + + def delete_imported_key(self, addr): + if self.question(_("Do you want to remove")+" %s "%addr +_("from your wallet?")): + self.wallet.imported_keys.pop(addr) + self.update_receive_tab() + self.update_history_tab() + self.wallet.save() + + + def create_receive_menu(self, position): + # fixme: this function apparently has a side effect. + # if it is not called the menu pops up several times + #self.receive_list.selectedIndexes() + + item = self.receive_list.itemAt(position) + if not item: return + addr = unicode(item.text(0)) + menu = QMenu() + menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(addr)) + if self.receive_tab_mode == 2: + menu.addAction(_("Request amount"), lambda: self.edit_amount()) + menu.addAction(_("View QR"), lambda: ElectrumWindow.show_qrcode(_("Address"),"bitcoin:"+addr) ) + menu.addAction(_("Edit label"), lambda: self.edit_label(True)) + menu.addAction(_("Private key"), lambda: self.view_private_key(addr)) + menu.addAction(_("Sign message"), lambda: self.sign_message(addr)) + if addr in self.wallet.imported_keys: + menu.addAction(_("Remove from wallet"), lambda: self.delete_imported_key(addr)) + + if self.receive_tab_mode == 1: + t = _("Unfreeze") if addr in self.wallet.frozen_addresses else _("Freeze") + menu.addAction(t, lambda: self.toggle_freeze(addr)) + t = _("Unprioritize") if addr in self.wallet.prioritized_addresses else _("Prioritize") + menu.addAction(t, lambda: self.toggle_priority(addr)) + + menu.exec_(self.receive_list.viewport().mapToGlobal(position)) + + + def payto(self, x, is_alias): + if not x: return + if is_alias: + label = x + m_addr = label + else: + addr = x + label = self.wallet.labels.get(addr) + m_addr = label + ' <' + addr + '>' if label else addr + self.tabs.setCurrentIndex(1) + self.payto_e.setText(m_addr) + self.amount_e.setFocus() + + def delete_contact(self, x, is_alias): + if self.question(_("Do you want to remove")+" %s "%x +_("from your list of contacts?")): + if not is_alias and x in self.wallet.addressbook: + self.wallet.addressbook.remove(x) + if x in self.wallet.labels.keys(): + self.wallet.labels.pop(x) + elif is_alias and x in self.wallet.aliases: + self.wallet.aliases.pop(x) + self.update_history_tab() + self.update_contacts_tab() + self.update_completions() + + def create_contact_menu(self, position): + # fixme: this function apparently has a side effect. + # if it is not called the menu pops up several times + #self.contacts_list.selectedIndexes() + + item = self.contacts_list.itemAt(position) + if not item: return + addr = unicode(item.text(0)) + label = unicode(item.text(1)) + is_alias = label in self.wallet.aliases.keys() + x = label if is_alias else addr + menu = QMenu() + menu.addAction(_("Copy to Clipboard"), lambda: self.app.clipboard().setText(addr)) + menu.addAction(_("Pay to"), lambda: self.payto(x, is_alias)) + menu.addAction(_("View QR code"),lambda: self.show_qrcode(_("Address"),"bitcoin:"+addr)) + if not is_alias: + menu.addAction(_("Edit label"), lambda: self.edit_label(False)) + else: + menu.addAction(_("View alias details"), lambda: self.show_contact_details(label)) + menu.addAction(_("Delete"), lambda: self.delete_contact(x,is_alias)) + menu.exec_(self.contacts_list.viewport().mapToGlobal(position)) + + + def update_receive_item(self, item): + address = str(item.data(0,0).toString()) + label = self.wallet.labels.get(address,'') + item.setData(1,0,label) + + try: + amount, currency = self.wallet.requested_amounts.get(address, (None, None)) + except: + amount, currency = None, None + + amount_str = amount + (' ' + currency if currency else '') if amount is not None else '' + item.setData(2,0,amount_str) + + c, u = self.wallet.get_addr_balance(address) + balance = format_satoshis( c + u, False, self.wallet.num_zeros ) + item.setData(3,0,balance) + + if self.receive_tab_mode == 1: + if address in self.wallet.frozen_addresses: + item.setBackgroundColor(0, QColor('lightblue')) + elif address in self.wallet.prioritized_addresses: + item.setBackgroundColor(0, QColor('lightgreen')) + + + def update_receive_tab(self): + l = self.receive_list + + l.clear() + l.setColumnHidden(2, not self.receive_tab_mode == 2) + l.setColumnHidden(3, self.receive_tab_mode == 0) + l.setColumnHidden(4, not self.receive_tab_mode == 1) + if self.receive_tab_mode == 0: + width = self.column_widths['receive'][0][0] + l.setColumnWidth(0, width) + else: + for i,width in enumerate(self.column_widths['receive'][self.receive_tab_mode]): + l.setColumnWidth(i, width) + + + for k, account in self.wallet.accounts.items(): + name = account.get('name',str(k)) + account_item = QTreeWidgetItem( [ name, '', '', '', ''] ) + l.addTopLevelItem(account_item) + account_item.setExpanded(True) + + for is_change in [0,1]: + name = "Receiving" if not is_change else "Change" + seq_item = QTreeWidgetItem( [ name, '', '', '', ''] ) + account_item.addChild(seq_item) + if not is_change: seq_item.setExpanded(True) + is_red = False + gap = 0 + + for address in account[is_change]: + h = self.wallet.history.get(address,[]) + + if not is_change: + if h == []: + gap += 1 + if gap > self.wallet.gap_limit: + is_red = True + else: + gap = 0 + + num_tx = '*' if h == ['*'] else "%d"%len(h) + item = QTreeWidgetItem( [ address, '', '', '', num_tx] ) + item.setFont(0, QFont(MONOSPACE_FONT)) + item.setFont(2, QFont(MONOSPACE_FONT)) + self.update_receive_item(item) + if is_red and not is_change: + item.setBackgroundColor(1, QColor('red')) + seq_item.addChild(item) + + if self.wallet.imported_keys: + account_item = QTreeWidgetItem( [ "Imported", '', '', '', ''] ) + l.addTopLevelItem(account_item) + account_item.setExpanded(True) + for address in self.wallet.imported_keys.keys(): + item = QTreeWidgetItem( [ address, '', '', '', ''] ) + item.setFont(0, QFont(MONOSPACE_FONT)) + item.setFont(2, QFont(MONOSPACE_FONT)) + self.update_receive_item(item) + if is_red and not is_change: + item.setBackgroundColor(1, QColor('red')) + account_item.addChild(item) + + + # we use column 1 because column 0 may be hidden + l.setCurrentItem(l.topLevelItem(0),1) + + def show_contact_details(self, m): + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self-signed" + msg = _('Alias:')+' '+ m + '\n'+_('Target address:')+' '+ a[1] + '\n\n'+_('Signed by:')+' ' + s + '\n'+_('Signing address:')+' ' + a[0] + QMessageBox.information(self, 'Alias', msg, 'OK') + + def update_contacts_tab(self): + + l = self.contacts_list + l.clear() + + alias_targets = [] + for alias, v in self.wallet.aliases.items(): + s, target = v + alias_targets.append(target) + item = QTreeWidgetItem( [ target, alias, '-'] ) + item.setBackgroundColor(0, QColor('lightgray')) + l.addTopLevelItem(item) + + for address in self.wallet.addressbook: + if address in alias_targets: continue + label = self.wallet.labels.get(address,'') + n = 0 + for tx in self.wallet.transactions.values(): + if address in map(lambda x: x[0], tx.outputs): n += 1 + + item = QTreeWidgetItem( [ address, label, "%d"%n] ) + item.setFont(0, QFont(MONOSPACE_FONT)) + l.addTopLevelItem(item) + + l.setCurrentItem(l.topLevelItem(0)) + + + def create_console_tab(self): + from qt_console import Console + from electrum import util, bitcoin, commands + self.console = console = Console() + console.updateNamespace({'wallet' : self.wallet, 'interface' : self.wallet.interface, 'gui':self}) + console.updateNamespace({'util' : util, 'bitcoin':bitcoin}) + + c = commands.Commands(self.wallet, self.wallet.interface, lambda: self.console.set_json(True)) + methods = {} + def mkfunc(f, method): + return lambda *args: apply( f, (method, args, self.password_dialog )) + for m in dir(c): + if m[0]=='_' or m=='wallet' or m == 'interface': continue + methods[m] = mkfunc(c._run, m) + + console.updateNamespace(methods) + return console + + + def create_status_bar(self): + self.status_text = "" + sb = QStatusBar() + sb.setFixedHeight(35) + qtVersion = qVersion() + + update_notification = UpdateLabel(self.config) + if(update_notification.new_version): + sb.addPermanentWidget(update_notification) + + if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7): + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) ) + if self.wallet.seed: + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/lock.png"), _("Password"), lambda: self.change_password_dialog(self.wallet, self) ) ) + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), _("Preferences"), self.settings_dialog ) ) + if self.wallet.seed: + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/seed.png"), _("Seed"), lambda: self.show_seed_dialog(self.wallet, self) ) ) + self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), _("Network"), lambda: self.network_dialog(self.wallet, self) ) + sb.addPermanentWidget( self.status_button ) + + self.setStatusBar(sb) + + def go_lite(self): + import gui_lite + self.config.set_key('gui', 'lite', True) + self.hide() + if self.lite: + self.lite.mini.show() + else: + self.lite = gui_lite.ElectrumGui(self.wallet, self.config, self) + self.lite.main(None) + + def new_contact_dialog(self): + text, ok = QInputDialog.getText(self, _('New Contact'), _('Address') + ':') + address = unicode(text) + if ok: + if is_valid(address): + self.wallet.addressbook.append(address) + self.wallet.save() + self.update_contacts_tab() + self.update_history_tab() + self.update_completions() + else: + QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK')) + + def show_master_public_key(self): + dialog = QDialog(None) + dialog.setModal(1) + dialog.setWindowTitle(_("Master Public Key")) + + main_text = QTextEdit() + main_text.setText(self.wallet.get_master_public_key()) + main_text.setReadOnly(True) + main_text.setMaximumHeight(170) + qrw = QRCodeWidget(self.wallet.get_master_public_key(), 6) + + ok_button = QPushButton(_("OK")) + ok_button.setDefault(True) + ok_button.clicked.connect(dialog.accept) + + main_layout = QGridLayout() + main_layout.addWidget(QLabel(_('Your Master Public Key is:')), 0, 0, 1, 2) + + main_layout.addWidget(main_text, 1, 0) + main_layout.addWidget(qrw, 1, 1 ) + + vbox = QVBoxLayout() + vbox.addLayout(main_layout) + hbox = QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(ok_button) + vbox.addLayout(hbox) + + dialog.setLayout(vbox) + dialog.exec_() + + + @classmethod + def show_seed_dialog(self, wallet, parent=None): + if not wallet.seed: + QMessageBox.information(parent, _('Message'), _('No seed'), _('OK')) + return + + if wallet.use_encryption: + password = parent.password_dialog() + if not password: + return + else: + password = None + + try: + seed = wallet.decode_seed(password) + except: + QMessageBox.warning(parent, _('Error'), _('Incorrect Password'), _('OK')) + return + + self.show_seed(seed) + + @classmethod + def show_seed(self, seed): + dialog = QDialog(None) + dialog.setModal(1) + dialog.setWindowTitle('Electrum' + ' - ' + _('Seed')) + + brainwallet = ' '.join(mnemonic.mn_encode(seed)) + + label1 = QLabel(_("Your wallet generation seed is")+ ":") + + seed_text = QTextEdit(brainwallet) + seed_text.setReadOnly(True) + seed_text.setMaximumHeight(130) + + msg2 = _("Please write down or memorize these 12 words (order is important).") + " " \ + + _("This seed will allow you to recover your wallet in case of computer failure.") + " " \ + + _("Your seed is also displayed as QR code, in case you want to transfer it to a mobile phone.") + "<p>" \ + + "<b>"+_("WARNING")+":</b> " + _("Never disclose your seed. Never type it on a website.") + "</b><p>" + label2 = QLabel(msg2) + label2.setWordWrap(True) + + logo = QLabel() + logo.setPixmap(QPixmap(":icons/seed.png").scaledToWidth(56)) + logo.setMaximumWidth(60) + + qrw = QRCodeWidget(seed, 4) + + ok_button = QPushButton(_("OK")) + ok_button.setDefault(True) + ok_button.clicked.connect(dialog.accept) + + grid = QGridLayout() + #main_layout.addWidget(logo, 0, 0) + + grid.addWidget(logo, 0, 0) + grid.addWidget(label1, 0, 1) + + grid.addWidget(seed_text, 1, 0, 1, 2) + + grid.addWidget(qrw, 0, 2, 2, 1) + + vbox = QVBoxLayout() + vbox.addLayout(grid) + vbox.addWidget(label2) + + hbox = QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(ok_button) + vbox.addLayout(hbox) + + dialog.setLayout(vbox) + dialog.exec_() + + @staticmethod + def show_qrcode(title, data): + if not data: return + d = QDialog(None) + d.setModal(1) + d.setWindowTitle(title) + d.setMinimumSize(270, 300) + vbox = QVBoxLayout() + qrw = QRCodeWidget(data) + vbox.addWidget(qrw, 1) + vbox.addWidget(QLabel(data), 0, Qt.AlignHCenter) + hbox = QHBoxLayout() + hbox.addStretch(1) + + def print_qr(self): + filename = "qrcode.bmp" + bmp.save_qrcode(qrw.qr, filename) + QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK')) + + b = QPushButton(_("Print")) + hbox.addWidget(b) + b.clicked.connect(print_qr) + + b = QPushButton(_("Close")) + hbox.addWidget(b) + b.clicked.connect(d.accept) + + vbox.addLayout(hbox) + d.setLayout(vbox) + d.exec_() + + def view_private_key(self,address): + if not address: return + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + pk = self.wallet.get_private_key(address, password) + except BaseException, e: + self.show_message(str(e)) + return + + QMessageBox.information(self, _('Private key'), 'Address'+ ': ' + address + '\n\n' + _('Private key') + ': ' + pk, _('OK')) + + + def sign_message(self,address): + if not address: return + d = QDialog(self) + d.setModal(1) + d.setWindowTitle(_('Sign Message')) + d.setMinimumSize(410, 290) + + tab_widget = QTabWidget() + tab = QWidget() + layout = QGridLayout(tab) + + sign_address = QLineEdit() + + sign_address.setText(address) + layout.addWidget(QLabel(_('Address')), 1, 0) + layout.addWidget(sign_address, 1, 1) + + sign_message = QTextEdit() + layout.addWidget(QLabel(_('Message')), 2, 0) + layout.addWidget(sign_message, 2, 1) + layout.setRowStretch(2,3) + + sign_signature = QTextEdit() + layout.addWidget(QLabel(_('Signature')), 3, 0) + layout.addWidget(sign_signature, 3, 1) + layout.setRowStretch(3,1) + + def do_sign(): + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + signature = self.wallet.sign_message(str(sign_address.text()), str(sign_message.toPlainText()), password) + sign_signature.setText(signature) + except BaseException, e: + self.show_message(str(e)) + return + + hbox = QHBoxLayout() + b = QPushButton(_("Sign")) + hbox.addWidget(b) + b.clicked.connect(do_sign) + b = QPushButton(_("Close")) + b.clicked.connect(d.accept) + hbox.addWidget(b) + layout.addLayout(hbox, 4, 1) + tab_widget.addTab(tab, _("Sign")) + + + tab = QWidget() + layout = QGridLayout(tab) + + verify_address = QLineEdit() + layout.addWidget(QLabel(_('Address')), 1, 0) + layout.addWidget(verify_address, 1, 1) + + verify_message = QTextEdit() + layout.addWidget(QLabel(_('Message')), 2, 0) + layout.addWidget(verify_message, 2, 1) + layout.setRowStretch(2,3) + + verify_signature = QTextEdit() + layout.addWidget(QLabel(_('Signature')), 3, 0) + layout.addWidget(verify_signature, 3, 1) + layout.setRowStretch(3,1) + + def do_verify(): + try: + self.wallet.verify_message(verify_address.text(), str(verify_signature.toPlainText()), str(verify_message.toPlainText())) + self.show_message(_("Signature verified")) + except BaseException, e: + self.show_message(str(e)) + return + + hbox = QHBoxLayout() + b = QPushButton(_("Verify")) + b.clicked.connect(do_verify) + hbox.addWidget(b) + b = QPushButton(_("Close")) + b.clicked.connect(d.accept) + hbox.addWidget(b) + layout.addLayout(hbox, 4, 1) + tab_widget.addTab(tab, _("Verify")) + + vbox = QVBoxLayout() + vbox.addWidget(tab_widget) + d.setLayout(vbox) + d.exec_() + + + def toggle_QR_window(self, show): + if show and not self.qr_window: + self.qr_window = QR_Window(self.exchanger) + self.qr_window.setVisible(True) + self.qr_window_geometry = self.qr_window.geometry() + item = self.receive_list.currentItem() + if item: + address = str(item.text(1)) + label = self.wallet.labels.get(address) + amount, currency = self.wallet.requested_amounts.get(address, (None, None)) + self.qr_window.set_content( address, label, amount, currency ) + + elif show and self.qr_window and not self.qr_window.isVisible(): + self.qr_window.setVisible(True) + self.qr_window.setGeometry(self.qr_window_geometry) + + elif not show and self.qr_window and self.qr_window.isVisible(): + self.qr_window_geometry = self.qr_window.geometry() + self.qr_window.setVisible(False) + + #self.print_button.setHidden(self.qr_window is None or not self.qr_window.isVisible()) + self.receive_list.setColumnHidden(2, self.qr_window is None or not self.qr_window.isVisible()) + self.receive_list.setColumnWidth(1, 200) + + + def question(self, msg): + return QMessageBox.question(self, _('Message'), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes + + def show_message(self, msg): + QMessageBox.information(self, _('Message'), msg, _('OK')) + + def password_dialog(self ): + d = QDialog(self) + d.setModal(1) + + pw = QLineEdit() + pw.setEchoMode(2) + + vbox = QVBoxLayout() + msg = _('Please enter your password') + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + grid.addWidget(QLabel(_('Password')), 1, 0) + grid.addWidget(pw, 1, 1) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + return unicode(pw.text()) + + + + + + @staticmethod + def change_password_dialog( wallet, parent=None ): + + if not wallet.seed: + QMessageBox.information(parent, _('Error'), _('No seed'), _('OK')) + return + + d = QDialog(parent) + d.setModal(1) + + pw = QLineEdit() + pw.setEchoMode(2) + new_pw = QLineEdit() + new_pw.setEchoMode(2) + conf_pw = QLineEdit() + conf_pw.setEchoMode(2) + + vbox = QVBoxLayout() + if parent: + msg = (_('Your wallet is encrypted. Use this dialog to change your password.')+'\n'\ + +_('To disable wallet encryption, enter an empty new password.')) \ + if wallet.use_encryption else _('Your wallet keys are not encrypted') + else: + msg = _("Please choose a password to encrypt your wallet keys.")+'\n'\ + +_("Leave these fields empty if you want to disable encryption.") + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + + if wallet.use_encryption: + grid.addWidget(QLabel(_('Password')), 1, 0) + grid.addWidget(pw, 1, 1) + + grid.addWidget(QLabel(_('New Password')), 2, 0) + grid.addWidget(new_pw, 2, 1) + + grid.addWidget(QLabel(_('Confirm Password')), 3, 0) + grid.addWidget(conf_pw, 3, 1) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + password = unicode(pw.text()) if wallet.use_encryption else None + new_password = unicode(new_pw.text()) + new_password2 = unicode(conf_pw.text()) + + try: + seed = wallet.decode_seed(password) + except: + QMessageBox.warning(parent, _('Error'), _('Incorrect Password'), _('OK')) + return + + if new_password != new_password2: + QMessageBox.warning(parent, _('Error'), _('Passwords do not match'), _('OK')) + return ElectrumWindow.change_password_dialog(wallet, parent) # Retry + + wallet.update_password(seed, password, new_password) + + @staticmethod + def seed_dialog(wallet, parent=None): + d = QDialog(parent) + d.setModal(1) + + vbox = QVBoxLayout() + msg = _("Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet.") + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + + seed_e = QLineEdit() + grid.addWidget(QLabel(_('Seed or mnemonic')), 1, 0) + grid.addWidget(seed_e, 1, 1) + + gap_e = QLineEdit() + gap_e.setText("5") + grid.addWidget(QLabel(_('Gap limit')), 2, 0) + grid.addWidget(gap_e, 2, 1) + gap_e.textChanged.connect(lambda: numbify(gap_e,True)) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + try: + gap = int(unicode(gap_e.text())) + except: + QMessageBox.warning(None, _('Error'), 'error', 'OK') + return + + try: + seed = str(seed_e.text()) + seed.decode('hex') + except: + print_error("Warning: Not hex, trying decode") + try: + seed = mnemonic.mn_decode( seed.split(' ') ) + except: + QMessageBox.warning(None, _('Error'), _('I cannot decode this'), _('OK')) + return + + if not seed: + QMessageBox.warning(None, _('Error'), _('No seed'), _('OK')) + return + + return seed, gap + + def generate_transaction_information_widget(self, tx): + tabs = QTabWidget(self) + + tab1 = QWidget() + grid_ui = QGridLayout(tab1) + grid_ui.setColumnStretch(0,1) + tabs.addTab(tab1, _('Outputs') ) + + tree_widget = MyTreeWidget(self) + tree_widget.setColumnCount(2) + tree_widget.setHeaderLabels( [_('Address'), _('Amount')] ) + tree_widget.setColumnWidth(0, 300) + tree_widget.setColumnWidth(1, 50) + + for output in tx.d["outputs"]: + item = QTreeWidgetItem( ["%s" %(output["address"]), "%s" % ( format_satoshis(output["value"]))] ) + tree_widget.addTopLevelItem(item) + + tree_widget.setMaximumHeight(100) + + grid_ui.addWidget(tree_widget) + + tab2 = QWidget() + grid_ui = QGridLayout(tab2) + grid_ui.setColumnStretch(0,1) + tabs.addTab(tab2, _('Inputs') ) + + tree_widget = MyTreeWidget(self) + tree_widget.setColumnCount(2) + tree_widget.setHeaderLabels( [ _('Address'), _('Previous output')] ) + + for input_line in tx.inputs: + item = QTreeWidgetItem( [ str(input_line["address"]), str(input_line["prevout_hash"])] ) + tree_widget.addTopLevelItem(item) + + tree_widget.setMaximumHeight(100) + + grid_ui.addWidget(tree_widget) + return tabs + + + def tx_dict_from_text(self, txt): + try: + tx_dict = json.loads(str(txt)) + assert "hex" in tx_dict.keys() + assert "complete" in tx_dict.keys() + if not tx_dict["complete"]: + assert "input_info" in tx_dict.keys() + except: + QMessageBox.critical(None, "Unable to parse transaction", _("Electrum was unable to parse your transaction:")) + return None + return tx_dict + + + def read_tx_from_file(self): + fileName = QFileDialog.getOpenFileName(QWidget(), _("Select your transaction file"), os.path.expanduser('~')) + if not fileName: + return + try: + with open(fileName, "r") as f: + file_content = f.read() + except (ValueError, IOError, os.error), reason: + QMessageBox.critical(None,"Unable to read file or no transaction found", _("Electrum was unable to open your transaction file") + "\n" + str(reason)) + + return self.tx_dict_from_text(file_content) + + + def sign_raw_transaction(self, tx, input_info): + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + self.wallet.signrawtransaction(tx, input_info, [], password) + + fileName = QFileDialog.getSaveFileName(QWidget(), _("Select where to save your signed transaction"), os.path.expanduser('~/signed_tx_%s' % (tx.hash()[0:8]))) + if fileName: + with open(fileName, "w+") as f: + f.write(json.dumps(tx.as_dict(),indent=4) + '\n') + self.show_message(_("Transaction saved succesfully")) + except BaseException, e: + self.show_message(str(e)) + + + def create_sign_transaction_window(self, tx_dict): + tx = Transaction(tx_dict["hex"]) + + dialog = QDialog(self) + dialog.setMinimumWidth(500) + dialog.setWindowTitle(_('Sign unsigned transaction')) + dialog.setModal(1) + + vbox = QVBoxLayout() + dialog.setLayout(vbox) + vbox.addWidget( self.generate_transaction_information_widget(tx) ) + + if tx_dict["complete"] == True: + vbox.addWidget(QLabel(_("This transaction is already signed."))) + else: + vbox.addWidget(QLabel(_("Create a signed transaction."))) + vbox.addLayout(ok_cancel_buttons(dialog)) + input_info = json.loads(tx_dict["input_info"]) + + if dialog.exec_(): + self.sign_raw_transaction(tx, input_info) + + + + def do_sign_from_text(self): + txt, ok = QInputDialog.getText(QTextEdit(), _('Sign raw transaction'), _('Transaction data in JSON') + ':') + if not ok: + return + tx_dict = self.tx_dict_from_text(unicode(txt)) + if tx_dict: + self.create_sign_transaction_window(tx_dict) + + + def do_sign_from_file(self): + tx_dict = self.read_tx_from_file() + if tx_dict: + self.create_sign_transaction_window(tx_dict) + + + def send_raw_transaction(self, raw_tx): + result, result_message = self.wallet.sendtx( raw_tx ) + if result: + self.show_message("Transaction succesfully sent: %s" % (result_message)) + else: + self.show_message("There was a problem sending your transaction:\n %s" % (result_message)) + + + def create_send_transaction_window(self, tx_dict): + tx = Transaction(tx_dict["hex"]) + + dialog = QDialog(self) + dialog.setMinimumWidth(500) + dialog.setWindowTitle(_('Send raw transaction')) + dialog.setModal(1) + + vbox = QVBoxLayout() + dialog.setLayout(vbox) + vbox.addWidget( self.generate_transaction_information_widget(tx)) + + if tx_dict["complete"] == False: + vbox.addWidget(QLabel(_("This transaction is not signed yet."))) + else: + vbox.addWidget(QLabel(_("Broadcast this transaction"))) + vbox.addLayout(ok_cancel_buttons(dialog)) + + if dialog.exec_(): + self.send_raw_transaction(tx_dict["hex"]) + + + def do_send_from_file(self): + tx_dict = self.read_tx_from_file() + if tx_dict: + self.create_send_transaction_window(tx_dict) + + + def do_send_from_text(self): + txt, ok = QInputDialog.getText(QTextEdit(), _('Send raw transaction'), _('Transaction data in JSON') + ':') + if not ok: + return + tx_dict = self.tx_dict_from_text(unicode(txt)) + if tx_dict: + self.create_send_transaction_window(tx_dict) + + + def do_export_privkeys(self): + self.show_message("%s\n%s\n%s" % (_("WARNING: ALL your private keys are secret."), _("Exposing a single private key can compromise your entire wallet!"), _("In particular, DO NOT use 'redeem private key' services proposed by third parties."))) + + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + try: + select_export = _('Select file to export your private keys to') + fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-private-keys.csv'), "*.csv") + if fileName: + with open(fileName, "w+") as csvfile: + transaction = csv.writer(csvfile) + transaction.writerow(["address", "private_key"]) + + + for addr, pk in self.wallet.get_private_keys(self.wallet.addresses(True), password).items(): + transaction.writerow(["%34s"%addr,pk]) + + self.show_message(_("Private keys exported.")) + + except (IOError, os.error), reason: + export_error_label = _("Electrum was unable to produce a private key-export.") + QMessageBox.critical(None,"Unable to create csv", export_error_label + "\n" + str(reason)) + + except BaseException, e: + self.show_message(str(e)) + return + + + def do_import_labels(self): + labelsFile = QFileDialog.getOpenFileName(QWidget(), _("Open text file"), util.user_dir(), self.tr("Text Files (labels.dat)")) + if not labelsFile: return + try: + f = open(labelsFile, 'r') + data = f.read() + f.close() + for key, value in json.loads(data).items(): + self.wallet.labels[key] = value + self.wallet.save() + QMessageBox.information(None, _("Labels imported"), _("Your labels where imported from")+" '%s'" % str(labelsFile)) + except (IOError, os.error), reason: + QMessageBox.critical(None, _("Unable to import labels"), _("Electrum was unable to import your labels.")+"\n" + str(reason)) + + + + def do_export_labels(self): + labels = self.wallet.labels + try: + labelsFile = util.user_dir() + '/labels.dat' + f = open(labelsFile, 'w+') + json.dump(labels, f) + f.close() + QMessageBox.information(None, "Labels exported", _("Your labels where exported to")+" '%s'" % str(labelsFile)) + except (IOError, os.error), reason: + QMessageBox.critical(None, "Unable to export labels", _("Electrum was unable to export your labels.")+"\n" + str(reason)) + + def do_export_history(self): + from gui_lite import csv_transaction + csv_transaction(self.wallet) + + def do_import_privkey(self): + if not self.wallet.imported_keys: + r = QMessageBox.question(None, _('Warning'), _('Warning: Imported keys are not recoverable from seed.') + ' ' \ + + _('If you ever need to restore your wallet from its seed, these keys will be lost.') + '\n\n' \ + + _('Are you sure you understand what you are doing?'), 3, 4) + if r == 4: return + + text, ok = QInputDialog.getText(self, _('Import private key'), _('Private Key') + ':') + if not ok: return + sec = str(text).strip() + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + try: + addr = self.wallet.import_key(sec, password) + if not addr: + QMessageBox.critical(None, _("Unable to import key"), "error") + else: + QMessageBox.information(None, _("Key imported"), addr) + self.update_receive_tab() + self.update_history_tab() + except BaseException as e: + QMessageBox.critical(None, _("Unable to import key"), str(e)) + + def settings_dialog(self): + d = QDialog(self) + d.setWindowTitle(_('Electrum Settings')) + d.setModal(1) + vbox = QVBoxLayout() + + tabs = QTabWidget(self) + vbox.addWidget(tabs) + + tab1 = QWidget() + grid_ui = QGridLayout(tab1) + grid_ui.setColumnStretch(0,1) + tabs.addTab(tab1, _('Display') ) + + nz_label = QLabel(_('Display zeros')) + grid_ui.addWidget(nz_label, 3, 0) + nz_e = QLineEdit() + nz_e.setText("%d"% self.wallet.num_zeros) + grid_ui.addWidget(nz_e, 3, 1) + msg = _('Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"') + grid_ui.addWidget(HelpButton(msg), 3, 2) + nz_e.textChanged.connect(lambda: numbify(nz_e,True)) + if not self.config.is_modifiable('num_zeros'): + for w in [nz_e, nz_label]: w.setEnabled(False) + + lang_label=QLabel(_('Language') + ':') + grid_ui.addWidget(lang_label , 8, 0) + lang_combo = QComboBox() + from i18n import languages + lang_combo.addItems(languages.values()) + try: + index = languages.keys().index(self.config.get("language",'')) + except: + index = 0 + lang_combo.setCurrentIndex(index) + grid_ui.addWidget(lang_combo, 8, 1) + grid_ui.addWidget(HelpButton(_('Select which language is used in the GUI (after restart).')+' '), 8, 2) + if not self.config.is_modifiable('language'): + for w in [lang_combo, lang_label]: w.setEnabled(False) + + currencies = self.exchanger.get_currencies() + currencies.insert(0, "None") + + cur_label=QLabel(_('Currency') + ':') + grid_ui.addWidget(cur_label , 9, 0) + cur_combo = QComboBox() + cur_combo.addItems(currencies) + try: + index = currencies.index(self.config.get('currency', "None")) + except: + index = 0 + cur_combo.setCurrentIndex(index) + grid_ui.addWidget(cur_combo, 9, 1) + grid_ui.addWidget(HelpButton(_('Select which currency is used for quotes.')+' '), 9, 2) + + view_label=QLabel(_('Receive Tab') + ':') + grid_ui.addWidget(view_label , 10, 0) + view_combo = QComboBox() + view_combo.addItems([_('Simple'), _('Advanced'), _('Point of Sale')]) + view_combo.setCurrentIndex(self.receive_tab_mode) + grid_ui.addWidget(view_combo, 10, 1) + hh = _('This selects the interaction mode of the "Receive" tab.')+' ' + '\n\n' \ + + _('Simple') + ': ' + _('Show only addresses and labels.') + '\n\n' \ + + _('Advanced') + ': ' + _('Show address balances and add extra menu items to freeze/prioritize addresses.') + '\n\n' \ + + _('Point of Sale') + ': ' + _('Show QR code window and amounts requested for each address. Add menu item to request amount.') + '\n\n' + + grid_ui.addWidget(HelpButton(hh), 10, 2) + + # wallet tab + tab2 = QWidget() + grid_wallet = QGridLayout(tab2) + grid_wallet.setColumnStretch(0,1) + tabs.addTab(tab2, _('Wallet') ) + + fee_label = QLabel(_('Transaction fee')) + grid_wallet.addWidget(fee_label, 0, 0) + fee_e = QLineEdit() + fee_e.setText("%s"% str( Decimal( self.wallet.fee)/100000000 ) ) + grid_wallet.addWidget(fee_e, 0, 1) + msg = _('Fee per transaction input. Transactions involving multiple inputs tend to require a higher fee.') + ' ' \ + + _('Recommended value') + ': 0.001' + grid_wallet.addWidget(HelpButton(msg), 0, 2) + fee_e.textChanged.connect(lambda: numbify(fee_e,False)) + if not self.config.is_modifiable('fee'): + for w in [fee_e, fee_label]: w.setEnabled(False) + + usechange_label = QLabel(_('Use change addresses')) + grid_wallet.addWidget(usechange_label, 1, 0) + usechange_combo = QComboBox() + usechange_combo.addItems([_('Yes'), _('No')]) + usechange_combo.setCurrentIndex(not self.wallet.use_change) + grid_wallet.addWidget(usechange_combo, 1, 1) + grid_wallet.addWidget(HelpButton(_('Using change addresses makes it more difficult for other people to track your transactions.')+' '), 1, 2) + if not self.config.is_modifiable('use_change'): usechange_combo.setEnabled(False) + + gap_label = QLabel(_('Gap limit')) + grid_wallet.addWidget(gap_label, 2, 0) + gap_e = QLineEdit() + gap_e.setText("%d"% self.wallet.gap_limit) + grid_wallet.addWidget(gap_e, 2, 1) + msg = _('The gap limit is the maximal number of contiguous unused addresses in your sequence of receiving addresses.') + '\n' \ + + _('You may increase it if you need more receiving addresses.') + '\n\n' \ + + _('Your current gap limit is') + ': %d'%self.wallet.gap_limit + '\n' \ + + _('Given the current status of your address sequence, the minimum gap limit you can use is:')+' ' + '%d'%self.wallet.min_acceptable_gap() + '\n\n' \ + + _('Warning') + ': ' \ + + _('The gap limit parameter must be provided in order to recover your wallet from seed.') + ' ' \ + + _('Do not modify it if you do not understand what you are doing, or if you expect to recover your wallet without knowing it!') + '\n\n' + grid_wallet.addWidget(HelpButton(msg), 2, 2) + gap_e.textChanged.connect(lambda: numbify(nz_e,True)) + if not self.config.is_modifiable('gap_limit'): + for w in [gap_e, gap_label]: w.setEnabled(False) + + grid_wallet.setRowStretch(3,1) + + + # import/export tab + tab3 = QWidget() + grid_io = QGridLayout(tab3) + grid_io.setColumnStretch(0,1) + tabs.addTab(tab3, _('Import/Export') ) + + grid_io.addWidget(QLabel(_('Labels')), 1, 0) + grid_io.addWidget(EnterButton(_("Export"), self.do_export_labels), 1, 1) + grid_io.addWidget(EnterButton(_("Import"), self.do_import_labels), 1, 2) + grid_io.addWidget(HelpButton(_('Export your labels as json')), 1, 3) + + grid_io.addWidget(QLabel(_('History')), 2, 0) + grid_io.addWidget(EnterButton(_("Export"), self.do_export_history), 2, 1) + grid_io.addWidget(HelpButton(_('Export your transaction history as csv')), 2, 3) + + grid_io.addWidget(QLabel(_('Private keys')), 3, 0) + + grid_io.addWidget(EnterButton(_("Export"), self.do_export_privkeys), 3, 1) + grid_io.addWidget(EnterButton(_("Import"), self.do_import_privkey), 3, 2) + grid_io.addWidget(HelpButton(_('Import private key')), 3, 3) + + grid_io.addWidget(QLabel(_('Master Public Key')), 4, 0) + grid_io.addWidget(EnterButton(_("Show"), self.show_master_public_key), 4, 1) + grid_io.addWidget(HelpButton(_('Your Master Public Key can be used to create receiving addresses, but not to sign transactions.') + ' ' \ + + _('If you give it to someone, they will be able to see your transactions, but not to spend your money.') + ' ' \ + + _('If you restore your wallet from it, a watching-only (deseeded) wallet will be created.')), 4, 3) + + grid_io.setRowStretch(4,1) + + tab4 = QWidget() + grid_raw = QGridLayout(tab4) + grid_raw.setColumnStretch(0,1) + tabs.addTab(tab4, _('Raw transactions') ) + # + #grid_raw.addWidget(QLabel(_("Read raw transaction")), 3, 0) + #grid_raw.addWidget(EnterButton(_("From file"), self.do_sign_from_file),3,1) + #grid_raw.addWidget(EnterButton(_("From text"), self.do_sign_from_text),3,2) + #grid_raw.addWidget(HelpButton(_("This will show you some useful information about an unsigned transaction")),3,3) + + if self.wallet.seed: + grid_raw.addWidget(QLabel(_("Sign transaction")), 1, 0) + grid_raw.addWidget(EnterButton(_("From file"), self.do_sign_from_file),1,1) + grid_raw.addWidget(EnterButton(_("From text"), self.do_sign_from_text),1,2) + grid_raw.addWidget(HelpButton(_("Sign an unsigned transaction generated by a watching-only wallet")),1,3) + + grid_raw.addWidget(QLabel(_("Send signed transaction")), 2, 0) + grid_raw.addWidget(EnterButton(_("From file"), self.do_send_from_file),2,1) + grid_raw.addWidget(EnterButton(_("From text"), self.do_send_from_text),2,2) + grid_raw.addWidget(HelpButton(_("This will broadcast a transaction to the network.")),2,3) + grid_raw.setRowStretch(3,1) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + # run the dialog + if not d.exec_(): return + + fee = unicode(fee_e.text()) + try: + fee = int( 100000000 * Decimal(fee) ) + except: + QMessageBox.warning(self, _('Error'), _('Invalid value') +': %s'%fee, _('OK')) + return + + if self.wallet.fee != fee: + self.wallet.fee = fee + self.wallet.save() + + nz = unicode(nz_e.text()) + try: + nz = int( nz ) + if nz>8: nz=8 + except: + QMessageBox.warning(self, _('Error'), _('Invalid value')+':%s'%nz, _('OK')) + return + + if self.wallet.num_zeros != nz: + self.wallet.num_zeros = nz + self.config.set_key('num_zeros', nz, True) + self.update_history_tab() + self.update_receive_tab() + + usechange_result = usechange_combo.currentIndex() == 0 + if self.wallet.use_change != usechange_result: + self.wallet.use_change = usechange_result + self.config.set_key('use_change', self.wallet.use_change, True) + + try: + n = int(gap_e.text()) + except: + QMessageBox.warning(self, _('Error'), _('Invalid value'), _('OK')) + return + + if self.wallet.gap_limit != n: + r = self.wallet.change_gap_limit(n) + if r: + self.update_receive_tab() + self.config.set_key('gap_limit', self.wallet.gap_limit, True) + else: + QMessageBox.warning(self, _('Error'), _('Invalid value'), _('OK')) + + need_restart = False + + lang_request = languages.keys()[lang_combo.currentIndex()] + if lang_request != self.config.get('language'): + self.config.set_key("language", lang_request, True) + need_restart = True + + cur_request = str(currencies[cur_combo.currentIndex()]) + if cur_request != self.config.get('currency', "None"): + self.config.set_key('currency', cur_request, True) + self.update_wallet() + + if need_restart: + QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK')) + + self.receive_tab_set_mode(view_combo.currentIndex()) + + + @staticmethod + def network_dialog(wallet, parent=None): + interface = wallet.interface + if parent: + if interface.is_connected: + status = _("Connected to")+" %s\n%d "%(interface.host, wallet.verifier.height)+_("blocks") + else: + status = _("Not connected") + server = interface.server + else: + import random + status = _("Please choose a server.") + "\n" + _("Select 'Cancel' if you are offline.") + server = interface.server + + plist, servers_list = interface.get_servers_list() + + d = QDialog(parent) + d.setModal(1) + d.setWindowTitle(_('Server')) + d.setMinimumSize(375, 20) + + 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) + vbox.addLayout(hbox) + + + # grid layout + grid = QGridLayout() + grid.setSpacing(8) + vbox.addLayout(grid) + + # server + server_protocol = QComboBox() + server_host = QLineEdit() + server_host.setFixedWidth(200) + server_port = QLineEdit() + server_port.setFixedWidth(60) + + protocol_names = ['TCP', 'HTTP', 'TCP/SSL', 'HTTPS'] + protocol_letters = 'thsg' + DEFAULT_PORTS = {'t':'50001', 's':'50002', 'h':'8081', 'g':'8082'} + server_protocol.addItems(protocol_names) + + grid.addWidget(QLabel(_('Server') + ':'), 0, 0) + grid.addWidget(server_protocol, 0, 1) + grid.addWidget(server_host, 0, 2) + grid.addWidget(server_port, 0, 3) + + def change_protocol(p): + protocol = protocol_letters[p] + host = unicode(server_host.text()) + pp = plist.get(host,DEFAULT_PORTS) + if protocol not in pp.keys(): + protocol = pp.keys()[0] + port = pp[protocol] + server_host.setText( host ) + server_port.setText( port ) + + server_protocol.connect(server_protocol, SIGNAL('currentIndexChanged(int)'), change_protocol) + + label = _('Active Servers') if wallet.interface.servers else _('Default Servers') + servers_list_widget = QTreeWidget(parent) + servers_list_widget.setHeaderLabels( [ label, _('Type') ] ) + servers_list_widget.setMaximumHeight(150) + servers_list_widget.setColumnWidth(0, 240) + for _host in servers_list.keys(): + _type = 'P' if servers_list[_host].get('pruning') else 'F' + servers_list_widget.addTopLevelItem(QTreeWidgetItem( [ _host, _type ] )) + + def change_server(host, protocol=None): + pp = plist.get(host,DEFAULT_PORTS) + if protocol: + port = pp.get(protocol) + if not port: protocol = None + + if not protocol: + if 't' in pp.keys(): + protocol = 't' + port = pp.get(protocol) + else: + protocol = pp.keys()[0] + port = pp.get(protocol) + + server_host.setText( host ) + server_port.setText( port ) + server_protocol.setCurrentIndex(protocol_letters.index(protocol)) + + if not plist: return + for p in protocol_letters: + i = protocol_letters.index(p) + j = server_protocol.model().index(i,0) + if p not in pp.keys(): + server_protocol.model().setData(j, QtCore.QVariant(0), QtCore.Qt.UserRole-1) + else: + server_protocol.model().setData(j, QtCore.QVariant(0,False), QtCore.Qt.UserRole-1) + + + if server: + host, port, protocol = server.split(':') + change_server(host,protocol) + + servers_list_widget.connect(servers_list_widget, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), lambda x: change_server(unicode(x.text(0)))) + grid.addWidget(servers_list_widget, 1, 1, 1, 3) + + if not wallet.config.is_modifiable('server'): + for w in [server_host, server_port, server_protocol, servers_list_widget]: w.setEnabled(False) + + # auto cycle + autocycle_cb = QCheckBox(_('Try random servers if disconnected')) + autocycle_cb.setChecked(wallet.config.get('auto_cycle', False)) + grid.addWidget(autocycle_cb, 3, 1, 3, 2) + if not wallet.config.is_modifiable('auto_cycle'): autocycle_cb.setEnabled(False) + + # proxy setting + proxy_mode = QComboBox() + proxy_host = QLineEdit() + proxy_host.setFixedWidth(200) + proxy_port = QLineEdit() + proxy_port.setFixedWidth(60) + proxy_mode.addItems(['NONE', 'SOCKS4', 'SOCKS5', 'HTTP']) + + def check_for_disable(index = False): + if proxy_mode.currentText() != 'NONE': + proxy_host.setEnabled(True) + proxy_port.setEnabled(True) + else: + proxy_host.setEnabled(False) + proxy_port.setEnabled(False) + + check_for_disable() + proxy_mode.connect(proxy_mode, SIGNAL('currentIndexChanged(int)'), check_for_disable) + + if not wallet.config.is_modifiable('proxy'): + for w in [proxy_host, proxy_port, proxy_mode]: w.setEnabled(False) + + proxy_config = interface.proxy if interface.proxy else { "mode":"none", "host":"localhost", "port":"8080"} + proxy_mode.setCurrentIndex(proxy_mode.findText(str(proxy_config.get("mode").upper()))) + proxy_host.setText(proxy_config.get("host")) + proxy_port.setText(proxy_config.get("port")) + + grid.addWidget(QLabel(_('Proxy') + ':'), 2, 0) + grid.addWidget(proxy_mode, 2, 1) + grid.addWidget(proxy_host, 2, 2) + grid.addWidget(proxy_port, 2, 3) + + # buttons + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + server = unicode( server_host.text() ) + ':' + unicode( server_port.text() ) + ':' + (protocol_letters[server_protocol.currentIndex()]) + if proxy_mode.currentText() != 'NONE': + proxy = { u'mode':unicode(proxy_mode.currentText()).lower(), u'host':unicode(proxy_host.text()), u'port':unicode(proxy_port.text()) } + else: + proxy = None + + wallet.config.set_key("proxy", proxy, True) + wallet.config.set_key("server", server, True) + interface.set_server(server, proxy) + wallet.config.set_key('auto_cycle', autocycle_cb.isChecked(), True) + return True + + def closeEvent(self, event): + g = self.geometry() + self.config.set_key("winpos-qt", [g.left(),g.top(),g.width(),g.height()], True) + self.save_column_widths() + self.config.set_key("column-widths", self.column_widths, True) + event.accept() + + +class ElectrumGui: + + def __init__(self, wallet, config, app=None): + self.wallet = wallet + self.config = config + if app is None: + self.app = QApplication(sys.argv) + + + def restore_or_create(self): + msg = _("Wallet file not found.")+"\n"+_("Do you want to create a new wallet, or to restore an existing one?") + r = QMessageBox.question(None, _('Message'), msg, _('Create'), _('Restore'), _('Cancel'), 0, 2) + if r==2: return None + return 'restore' if r==1 else 'create' + + def seed_dialog(self): + return ElectrumWindow.seed_dialog( self.wallet ) + + def network_dialog(self): + return ElectrumWindow.network_dialog( self.wallet, parent=None ) + + + def show_seed(self): + ElectrumWindow.show_seed_dialog(self.wallet) + + + def password_dialog(self): + ElectrumWindow.change_password_dialog(self.wallet) + + + def restore_wallet(self): + wallet = self.wallet + # wait until we are connected, because the user might have selected another server + if not wallet.interface.is_connected: + waiting = lambda: False if wallet.interface.is_connected else "%s \n" % (_("Connecting...")) + waiting_dialog(waiting) + + waiting = lambda: False if wallet.is_up_to_date() else "%s\n%s %d\n%s %.1f"\ + %(_("Please wait..."),_("Addresses generated:"),len(wallet.addresses(True)),_("Kilobytes received:"), wallet.interface.bytes_received/1024.) + + wallet.set_up_to_date(False) + wallet.interface.poke('synchronizer') + waiting_dialog(waiting) + if wallet.is_found(): + print_error( "Recovery successful" ) + else: + QMessageBox.information(None, _('Error'), _("No transactions found for this seed"), _('OK')) + + return True + + def main(self,url): + s = Timer() + s.start() + w = ElectrumWindow(self.wallet, self.config) + if url: w.set_url(url) + w.app = self.app + w.connect_slots(s) + w.update_wallet() + w.show() + + self.app.exec_() diff --git a/gui/gui_text.py b/gui/gui_text.py @@ -0,0 +1,423 @@ +import curses, datetime +from decimal import Decimal +_ = lambda x:x +#from i18n import _ +from electrum.util import format_satoshis, set_verbosity +from electrum.bitcoin import is_valid + +import tty, sys + + +class ElectrumGui: + + def __init__(self, wallet, config, app=None): + self.stdscr = curses.initscr() + curses.noecho() + curses.cbreak() + curses.start_color() + curses.use_default_colors() + curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) + curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN) + self.stdscr.keypad(1) + self.stdscr.border(0) + self.maxy, self.maxx = self.stdscr.getmaxyx() + curses.curs_set(0) + self.w = curses.newwin(10, 50, 5, 5) + + self.wallet = wallet + self.config = config + set_verbosity(False) + self.tab = 0 + self.pos = 0 + self.popup_pos = 0 + + self.str_recipient = "" + self.str_description = "" + self.str_amount = "" + self.str_fee = "" + + self.wallet.interface.register_callback('updated', self.refresh) + self.wallet.interface.register_callback('connected', self.refresh) + self.wallet.interface.register_callback('disconnected', self.refresh) + self.wallet.interface.register_callback('disconnecting', self.refresh) + self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")] + self.num_tabs = len(self.tab_names) + + + def restore_or_create(self): + pass + + + def get_string(self, y, x): + curses.curs_set(1) + curses.echo() + self.stdscr.addstr( y, x, " "*20, curses.A_REVERSE) + s = self.stdscr.getstr(y,x) + curses.noecho() + curses.curs_set(0) + return s + + + def print_history(self): + width = [20, 40, 14, 14] + delta = (self.maxx - sum(width) - 4)/3 + format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%"+"%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s" + + b = 0 + messages = [] + + for item in self.wallet.get_tx_history(): + tx_hash, conf, is_mine, value, fee, balance, timestamp = item + if conf: + try: + time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] + except: + time_str = "------" + else: + time_str = 'pending' + + label, is_default_label = self.wallet.get_label(tx_hash) + messages.append( format_str%( time_str, label, format_satoshis(value), format_satoshis(balance) ) ) + + self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance"))) + + + def print_balance(self): + if self.wallet.interface and self.wallet.interface.is_connected: + if not self.wallet.up_to_date: + msg = _( "Synchronizing..." ) + else: + c, u = self.wallet.get_balance() + msg = _("Balance")+": %f "%(Decimal( c ) / 100000000) + if u: msg += " [%f unconfirmed]"%(Decimal( u ) / 100000000) + else: + msg = _( "Not connected" ) + + self.stdscr.addstr( self.maxy -1, 3, msg) + + for i in range(self.num_tabs): + self.stdscr.addstr( 0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0) + + self.stdscr.addstr( self.maxy -1, self.maxx-30, ' '.join([_("Settings"), _("Network"), _("Quit")])) + + + def print_contacts(self): + messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addressbook) + self.print_list(messages, "%19s %25s "%("Address", "Label")) + + def print_receive(self): + messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addresses()) + self.print_list(messages, "%19s %25s "%("Address", "Label")) + + def print_edit_line(self, y, label, text, index, size): + text += " "*(size - len(text) ) + self.stdscr.addstr( y, 2, label) + self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1)) + + def print_send_tab(self): + self.stdscr.clear() + self.print_edit_line(3, _("Pay to"), self.str_recipient, 0, 40) + self.print_edit_line(5, _("Description"), self.str_description, 1, 40) + self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15) + self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15) + self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2)) + self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2)) + + def print_banner(self): + self.stdscr.addstr( 1, 1, self.wallet.banner ) + + def print_list(self, list, firstline): + self.maxpos = len(list) + if not self.maxpos: return + firstline += " "*(self.maxx -2 - len(firstline)) + self.stdscr.addstr( 1, 1, firstline ) + for i in range(self.maxy-4): + msg = list[i] if i < len(list) else "" + msg += " "*(self.maxx - 2 - len(msg)) + self.stdscr.addstr( i+2, 1, msg[0:self.maxx - 2], curses.A_REVERSE if i == (self.pos % self.maxpos) else 0) + + def refresh(self): + if self.tab == -1: return + self.stdscr.border(0) + self.print_balance() + self.stdscr.refresh() + + def main_command(self): + c = self.stdscr.getch() + print c + if c == curses.KEY_RIGHT: self.tab = (self.tab + 1)%self.num_tabs + elif c == curses.KEY_LEFT: self.tab = (self.tab - 1)%self.num_tabs + elif c == curses.KEY_DOWN: self.pos +=1 + elif c == curses.KEY_UP: self.pos -= 1 + elif c == 9: self.pos +=1 # tab + elif curses.unctrl(c) in ['^W', '^C', '^X', '^Q']: self.tab = -1 + elif curses.unctrl(c) in ['^N']: self.network_dialog() + elif curses.unctrl(c) == '^S': self.settings_dialog() + else: return c + if self.pos<0: self.pos=0 + if self.pos>=self.maxpos: self.pos=self.maxpos - 1 + + def run_tab(self, i, print_func, exec_func): + while self.tab == i: + self.stdscr.clear() + print_func() + self.refresh() + c = self.main_command() + if c: exec_func(c) + + + def run_history_tab(self, c): + if c == 10: + out = self.run_popup('',["blah","foo"]) + + + def edit_str(self, target, c, is_num=False): + if c==263 and target: + target = target[:-1] + elif not is_num or curses.unctrl(c) in '0123456789.': + target += curses.unctrl(c) + return target + + + def run_send_tab(self, c): + if self.pos%6 == 0: + self.str_recipient = self.edit_str(self.str_recipient, c) + if self.pos%6 == 1: + self.str_description = self.edit_str(self.str_description, c) + if self.pos%6 == 2: + self.str_amount = self.edit_str(self.str_amount, c, True) + elif self.pos%6 == 3: + self.str_fee = self.edit_str(self.str_fee, c, True) + elif self.pos%6==4: + if c == 10: self.do_send() + elif self.pos%6==5: + if c == 10: self.do_clear() + + + def run_receive_tab(self, c): + if c == 10: + out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"]) + + def run_contacts_tab(self, c): + if c == 10: + out = self.run_popup('Adress', ["Copy", "Pay to", "Edit label", "Delete"]).get('button') + address = self.wallet.addressbook[self.pos%len(self.wallet.addressbook)] + if out == "Pay to": + self.tab = 1 + self.str_recipient = address + self.pos = 2 + elif out == "Edit label": + s = self.get_string(6 + self.pos, 18) + if s: + self.wallet.labels[address] = s + + def run_banner_tab(self, c): + self.show_message(repr(c)) + pass + + def main(self,url): + + tty.setraw(sys.stdin) + while self.tab != -1: + self.run_tab(0, self.print_history, self.run_history_tab) + self.run_tab(1, self.print_send_tab, self.run_send_tab) + self.run_tab(2, self.print_receive, self.run_receive_tab) + self.run_tab(3, self.print_contacts, self.run_contacts_tab) + self.run_tab(4, self.print_banner, self.run_banner_tab) + + tty.setcbreak(sys.stdin) + curses.nocbreak() + self.stdscr.keypad(0) + curses.echo() + curses.endwin() + + + def do_clear(self): + self.str_amount = '' + self.str_recipient = '' + self.str_fee = '' + self.str_description = '' + + def do_send(self): + if not is_valid(self.str_recipient): + self.show_message(_('Invalid Bitcoin address')) + return + try: + amount = int( Decimal( self.str_amount) * 100000000 ) + except: + self.show_message(_('Invalid Amount')) + return + try: + fee = int( Decimal( self.str_fee) * 100000000 ) + except: + self.show_message(_('Invalid Fee')) + return + + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + tx = self.wallet.mktx( [(self.str_recipient, amount)], password, fee) + except BaseException, e: + self.show_message(str(e)) + return + + if self.str_description: + self.wallet.labels[tx.hash()] = self.str_description + + h = self.wallet.send_tx(tx) + self.show_message(_("Please wait..."), getchar=False) + self.wallet.tx_event.wait() + status, msg = self.wallet.receive_tx( h ) + + if status: + self.show_message(_('Payment sent.')) + self.do_clear() + #self.update_contacts_tab() + else: + self.show_message(_('Error')) + + + def show_message(self, message, getchar = True): + w = self.w + w.clear() + w.border(0) + w.addstr(2,2,message) + w.refresh() + if getchar: c = self.stdscr.getch() + + + def run_popup(self, title, items): + return self.run_dialog(title, map(lambda x: {'type':'button','label':x}, items), interval=1, y_pos = self.pos+3) + + + def network_dialog(self): + out = self.run_dialog('Network', [ + {'label':'server', 'type':'str', 'value':self.wallet.interface.server}, + {'label':'proxy', 'type':'str', 'value':self.config.get('proxy', '')}, + ], buttons = 1) + if out: + if out.get('server'): + server = out.get('server') + if out.get('proxy'): + proxy = self.parse_proxy_options(out.get('proxy')) + else: + proxy = None + + self.wallet.config.set_key("proxy", proxy, True) + self.wallet.config.set_key("server", server, True) + self.wallet.interface.set_server(server, proxy) + + + + def settings_dialog(self): + out = self.run_dialog('Settings', [ + {'label':'Default GUI', 'type':'list', 'choices':['classic','lite','gtk','text'], 'value':self.config.get('gui')}, + {'label':'Default fee', 'type':'satoshis', 'value': format_satoshis(self.config.get('fee')).strip() } + ], buttons = 1) + if out: + if out.get('Default GUI'): + self.config.set_key('gui', out['Default GUI'], True) + if out.get('Default fee'): + fee = int ( Decimal( out['Default fee']) *10000000 ) + self.config.set_key('fee', fee, True) + + + def password_dialog(self): + out = self.run_dialog('Password', [ + {'label':'Password', 'type':'password', 'value':''} + ], buttons = 1) + return out.get('Password') + + + def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3): + self.popup_pos = 0 + + self.w = curses.newwin( 5 + len(items)*interval + (2 if buttons else 0), 50, y_pos, 5) + w = self.w + out = {} + while True: + w.clear() + w.border(0) + w.addstr( 0, 2, title) + + num = len(items) + + numpos = num + if buttons: numpos += 2 + + for i in range(num): + item = items[i] + label = item.get('label') + if item.get('type') == 'list': + value = item.get('value','') + elif item.get('type') == 'satoshis': + value = item.get('value','') + elif item.get('type') == 'str': + value = item.get('value','') + elif item.get('type') == 'password': + value = '*'*len(item.get('value','')) + else: + value = '' + + if len(value)<20: value += ' '*(20-len(value)) + + if item.has_key('value'): + w.addstr( 2+interval*i, 2, label) + w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) ) + else: + w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0) + + if buttons: + w.addstr( 5+interval*i, 10, "[ ok ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2)) + w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2)) + + w.refresh() + + c = self.stdscr.getch() + if c in [ord('q'), 27]: break + elif c == curses.KEY_UP: self.popup_pos -= 1 + elif c == curses.KEY_DOWN: self.popup_pos +=1 + else: + i = self.popup_pos%numpos + if buttons and c==10: + if i == numpos-2: + return out + elif i == numpos -1: + return {} + + item = items[i] + _type = item.get('type') + + if _type == 'str': + item['value'] = self.edit_str(item['value'], c) + out[item.get('label')] = item.get('value') + + elif _type == 'password': + item['value'] = self.edit_str(item['value'], c) + out[item.get('label')] = item ['value'] + + elif _type == 'satoshis': + item['value'] = self.edit_str(item['value'], c, True) + out[item.get('label')] = item.get('value') + + elif _type == 'list': + choices = item.get('choices') + try: + j = choices.index(item.get('value')) + except: + j = 0 + new_choice = choices[(j + 1)% len(choices)] + item['value'] = new_choice + out[item.get('label')] = item.get('value') + + elif _type == 'button': + out['button'] = item.get('label') + break + + return out + diff --git a/lib/history_widget.py b/gui/history_widget.py diff --git a/lib/i18n.py b/gui/i18n.py diff --git a/gui/qrscanner.py b/gui/qrscanner.py @@ -0,0 +1,83 @@ +from electrum.util import print_error + +try: + import zbar +except ImportError: + print_error("Install zbar package to enable QR scans") + zbar = None + +from urlparse import urlparse, parse_qs + +def is_available(): + if not zbar: + return False + + try: + proc = zbar.Processor() + proc.init() + except zbar.SystemError: + # Cannot open video device + return False + + return True + +def scan_qr(): + proc = zbar.Processor() + proc.init() + proc.visible = True + + while True: + try: + proc.process_one() + except: + # User closed the preview window + return {} + + for r in proc.results: + if str(r.type) != 'QRCODE': + continue + + return parse_uri(r.data) + +def parse_uri(uri): + if ':' not in uri: + # It's just an address (not BIP21) + return {'address': uri} + + if '//' not in uri: + # Workaround for urlparse, it don't handle bitcoin: URI properly + uri = uri.replace(':', '://') + + uri = urlparse(uri) + result = {'address': uri.netloc} + + if uri.path.startswith('?'): + params = parse_qs(uri.path[1:]) + else: + params = parse_qs(uri.path) + + for k,v in params.items(): + if k in ('amount', 'label', 'message'): + result[k] = v[0] + + return result + +if __name__ == '__main__': + # Run some tests + + assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') == + {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) + + assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') == + {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) + + assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') == + {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) + + assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') == + {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) + + assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') == + {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) + + diff --git a/gui/qt_console.py b/gui/qt_console.py @@ -0,0 +1,296 @@ +# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget + +import sys, os, re +import traceback +from PyQt4 import QtCore +from PyQt4 import QtGui +from electrum import util + + + +class Console(QtGui.QPlainTextEdit): + def __init__(self, prompt='>> ', startup_message='', parent=None): + QtGui.QPlainTextEdit.__init__(self, parent) + + self.prompt = prompt + self.history = [] + self.namespace = {} + self.construct = [] + + self.setGeometry(50, 75, 600, 400) + self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere) + self.setUndoRedoEnabled(False) + self.document().setDefaultFont(QtGui.QFont("monospace", 10, QtGui.QFont.Normal)) + self.showMessage(startup_message) + + self.updateNamespace({'run':self.run_script}) + self.set_json(False) + + def set_json(self, b): + self.is_json = b + + def run_script(self, filename): + with open(filename) as f: + script = f.read() + result = eval(script, self.namespace, self.namespace) + + + + def updateNamespace(self, namespace): + self.namespace.update(namespace) + + def showMessage(self, message): + self.appendPlainText(message) + self.newPrompt() + + def clear(self): + self.setPlainText('') + self.newPrompt() + + def newPrompt(self): + if self.construct: + prompt = '.' * len(self.prompt) + else: + prompt = self.prompt + + self.completions_pos = self.textCursor().position() + self.completions_visible = False + + self.appendPlainText(prompt) + self.moveCursor(QtGui.QTextCursor.End) + + def getCommand(self): + doc = self.document() + curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text()) + curr_line = curr_line.rstrip() + curr_line = curr_line[len(self.prompt):] + return curr_line + + def setCommand(self, command): + if self.getCommand() == command: + return + self.moveCursor(QtGui.QTextCursor.End) + self.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor) + for i in range(len(self.prompt)): + self.moveCursor(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor) + self.textCursor().removeSelectedText() + self.textCursor().insertText(command) + self.moveCursor(QtGui.QTextCursor.End) + + + def show_completions(self, completions): + if self.completions_visible: + self.hide_completions() + + c = self.textCursor() + c.setPosition(self.completions_pos) + + completions = map(lambda x: x.split('.')[-1], completions) + t = '\n' + ' '.join(completions) + if len(t) > 500: + t = t[:500] + '...' + c.insertText(t) + self.completions_end = c.position() + + self.moveCursor(QtGui.QTextCursor.End) + self.completions_visible = True + + + def hide_completions(self): + if not self.completions_visible: + return + c = self.textCursor() + c.setPosition(self.completions_pos) + l = self.completions_end - self.completions_pos + for x in range(l): c.deleteChar() + + self.moveCursor(QtGui.QTextCursor.End) + self.completions_visible = False + + + def getConstruct(self, command): + if self.construct: + prev_command = self.construct[-1] + self.construct.append(command) + if not prev_command and not command: + ret_val = '\n'.join(self.construct) + self.construct = [] + return ret_val + else: + return '' + else: + if command and command[-1] == (':'): + self.construct.append(command) + return '' + else: + return command + + def getHistory(self): + return self.history + + def setHisory(self, history): + self.history = history + + def addToHistory(self, command): + if command and (not self.history or self.history[-1] != command): + self.history.append(command) + self.history_index = len(self.history) + + def getPrevHistoryEntry(self): + if self.history: + self.history_index = max(0, self.history_index - 1) + return self.history[self.history_index] + return '' + + def getNextHistoryEntry(self): + if self.history: + hist_len = len(self.history) + self.history_index = min(hist_len, self.history_index + 1) + if self.history_index < hist_len: + return self.history[self.history_index] + return '' + + def getCursorPosition(self): + return self.textCursor().columnNumber() - len(self.prompt) + + def setCursorPosition(self, position): + self.moveCursor(QtGui.QTextCursor.StartOfLine) + for i in range(len(self.prompt) + position): + self.moveCursor(QtGui.QTextCursor.Right) + + def runCommand(self): + command = self.getCommand() + self.addToHistory(command) + + command = self.getConstruct(command) + + if command: + tmp_stdout = sys.stdout + + class stdoutProxy(): + def __init__(self, write_func): + self.write_func = write_func + self.skip = False + + def flush(self): + pass + + def write(self, text): + if not self.skip: + stripped_text = text.rstrip('\n') + self.write_func(stripped_text) + QtCore.QCoreApplication.processEvents() + self.skip = not self.skip + + if command == 'help()': + self.appendPlainText("no help here!") + self.newPrompt() + return + + sys.stdout = stdoutProxy(self.appendPlainText) + try: + try: + result = eval(command, self.namespace, self.namespace) + if result != None: + if self.is_json: + util.print_json(result) + else: + self.appendPlainText(repr(result)) + except SyntaxError: + exec command in self.namespace + except SystemExit: + self.close() + except: + traceback_lines = traceback.format_exc().split('\n') + # Remove traceback mentioning this file, and a linebreak + for i in (3,2,1,-1): + traceback_lines.pop(i) + self.appendPlainText('\n'.join(traceback_lines)) + sys.stdout = tmp_stdout + self.newPrompt() + self.set_json(False) + + + def keyPressEvent(self, event): + if event.key() == QtCore.Qt.Key_Tab: + self.completions() + return + + self.hide_completions() + + if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): + self.runCommand() + return + if event.key() == QtCore.Qt.Key_Home: + self.setCursorPosition(0) + return + if event.key() == QtCore.Qt.Key_PageUp: + return + elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace): + if self.getCursorPosition() == 0: + return + elif event.key() == QtCore.Qt.Key_Up: + self.setCommand(self.getPrevHistoryEntry()) + return + elif event.key() == QtCore.Qt.Key_Down: + self.setCommand(self.getNextHistoryEntry()) + return + elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier: + self.clear() + + super(Console, self).keyPressEvent(event) + + + + def completions(self): + cmd = self.getCommand() + lastword = re.split(' |\(|\)',cmd)[-1] + beginning = cmd[0:-len(lastword)] + + path = lastword.split('.') + ns = self.namespace.keys() + + if len(path) == 1: + ns = ns + prefix = '' + else: + obj = self.namespace.get(path[0]) + prefix = path[0] + '.' + ns = dir(obj) + + + completions = [] + for x in ns: + if x[0] == '_':continue + xx = prefix + x + if xx.startswith(lastword): + completions.append(xx) + completions.sort() + + if not completions: + self.hide_completions() + elif len(completions) == 1: + self.hide_completions() + self.setCommand(beginning + completions[0]) + else: + # find common prefix + p = os.path.commonprefix(completions) + if len(p)>len(lastword): + self.hide_completions() + self.setCommand(beginning + p) + else: + self.show_completions(completions) + + +welcome_message = ''' + --------------------------------------------------------------- + Welcome to a primitive Python interpreter. + --------------------------------------------------------------- +''' + +if __name__ == '__main__': + app = QtGui.QApplication(sys.argv) + console = Console(startup_message=welcome_message) + console.updateNamespace({'myVar1' : app, 'myVar2' : 1234}) + console.show(); + sys.exit(app.exec_()) diff --git a/lib/receiving_widget.py b/gui/receiving_widget.py diff --git a/lib/__init__.py b/lib/__init__.py @@ -1,13 +1,12 @@ from version import ELECTRUM_VERSION from util import format_satoshis, print_msg, print_json, print_error, set_verbosity -from i18n import set_language from wallet import WalletSynchronizer from wallet_factory import WalletFactory as Wallet from verifier import WalletVerifier from interface import Interface, pick_random_server, DEFAULT_SERVERS from simple_config import SimpleConfig import bitcoin -from bitcoin import Transaction, EC_KEY +from bitcoin import Transaction, EC_KEY, is_valid from mnemonic import mn_encode as mnemonic_encode from mnemonic import mn_decode as mnemonic_decode from commands import protected_commands, known_commands, offline_commands, Commands diff --git a/lib/exchange_rate.py b/lib/exchange_rate.py @@ -1,59 +0,0 @@ -from PyQt4.QtCore import SIGNAL -import decimal -import httplib -import json -import threading - -class Exchanger(threading.Thread): - - def __init__(self, parent): - threading.Thread.__init__(self) - self.daemon = True - self.parent = parent - self.quote_currencies = None - self.lock = threading.Lock() - # Do price discovery - self.start() - - def exchange(self, btc_amount, quote_currency): - with self.lock: - if self.quote_currencies is None: - return None - quote_currencies = self.quote_currencies.copy() - if quote_currency not in quote_currencies: - return None - return btc_amount * quote_currencies[quote_currency] - - def run(self): - self.discovery() - - def discovery(self): - try: - connection = httplib.HTTPConnection('blockchain.info') - connection.request("GET", "/ticker") - except: - return - response = connection.getresponse() - if response.reason == httplib.responses[httplib.NOT_FOUND]: - return - response = json.loads(response.read()) - quote_currencies = {} - try: - for r in response: - quote_currencies[r] = self._lookup_rate(response, r) - with self.lock: - self.quote_currencies = quote_currencies - self.parent.emit(SIGNAL("refresh_balance()")) - except KeyError: - pass - - def get_currencies(self): - return [] if self.quote_currencies == None else sorted(self.quote_currencies.keys()) - - def _lookup_rate(self, response, quote_id): - return decimal.Decimal(str(response[str(quote_id)]["15m"])) - -if __name__ == "__main__": - exch = Exchanger(("BRL", "CNY", "EUR", "GBP", "RUB", "USD")) - print exch.exchange(1, "EUR") - diff --git a/lib/gui.py b/lib/gui.py @@ -1,1290 +0,0 @@ -#!/usr/bin/env python -# -# Electrum - lightweight Bitcoin client -# Copyright (C) 2011 thomasv@gitorious -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -import datetime -import thread, time, ast, sys, re -import socket, traceback -import pygtk -pygtk.require('2.0') -import gtk, gobject -from decimal import Decimal -from util import print_error -from bitcoin import is_valid - -import pyqrnative, mnemonic - -gtk.gdk.threads_init() -APP_NAME = "Electrum" -import platform -MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' - -from wallet import format_satoshis -from interface import DEFAULT_SERVERS - -def numbify(entry, is_int = False): - text = entry.get_text().strip() - chars = '0123456789' - if not is_int: chars +='.' - s = ''.join([i for i in text if i in chars]) - if not is_int: - if '.' in s: - p = s.find('.') - s = s.replace('.','') - s = s[:p] + '.' + s[p:p+8] - try: - amount = int( Decimal(s) * 100000000 ) - except: - amount = None - else: - try: - amount = int( s ) - except: - amount = None - entry.set_text(s) - return amount - - - - -def show_seed_dialog(wallet, password, parent): - if not wallet.seed: - show_message("No seed") - return - try: - seed = wallet.decode_seed(password) - except: - show_message("Incorrect password") - return - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK, - message_format = "Your wallet generation seed is:\n\n" + seed \ - + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ - + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" + ' '.join(mnemonic.mn_encode(seed)) + "\"" ) - dialog.set_title("Seed") - dialog.show() - dialog.run() - dialog.destroy() - -def restore_create_dialog(wallet): - - # ask if the user wants to create a new wallet, or recover from a seed. - # if he wants to recover, and nothing is found, do not create wallet - dialog = gtk.Dialog("electrum", parent=None, - flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, - buttons= ("create", 0, "restore",1, "cancel",2) ) - - label = gtk.Label("Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" ) - label.show() - dialog.vbox.pack_start(label) - dialog.show() - r = dialog.run() - dialog.destroy() - - if r==2: return False - return 'restore' if r==1 else 'create' - - - -def run_recovery_dialog(wallet): - message = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." - dialog = gtk.MessageDialog( - parent = None, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK_CANCEL, - message_format = message) - - vbox = dialog.vbox - dialog.set_default_response(gtk.RESPONSE_OK) - - # ask seed, server and gap in the same dialog - seed_box = gtk.HBox() - seed_label = gtk.Label('Seed or mnemonic:') - seed_label.set_size_request(150,-1) - seed_box.pack_start(seed_label, False, False, 10) - seed_label.show() - seed_entry = gtk.Entry() - seed_entry.show() - seed_entry.set_size_request(450,-1) - seed_box.pack_start(seed_entry, False, False, 10) - add_help_button(seed_box, '.') - seed_box.show() - vbox.pack_start(seed_box, False, False, 5) - - gap = gtk.HBox() - gap_label = gtk.Label('Gap limit:') - gap_label.set_size_request(150,10) - gap_label.show() - gap.pack_start(gap_label,False, False, 10) - gap_entry = gtk.Entry() - gap_entry.set_text("%d"%wallet.gap_limit) - gap_entry.connect('changed', numbify, True) - gap_entry.show() - gap.pack_start(gap_entry,False,False, 10) - add_help_button(gap, 'The maximum gap that is allowed between unused addresses in your wallet. During wallet recovery, this parameter is used to decide when to stop the recovery process. If you increase this value, you will need to remember it in order to be able to recover your wallet from seed.') - gap.show() - vbox.pack_start(gap, False,False, 5) - - dialog.show() - r = dialog.run() - gap = gap_entry.get_text() - seed = seed_entry.get_text() - dialog.destroy() - - if r==gtk.RESPONSE_CANCEL: - return False - - try: - gap = int(gap) - except: - show_message("error") - return False - - try: - seed.decode('hex') - except: - print_error("Warning: Not hex, trying decode") - seed = mnemonic.mn_decode( seed.split(' ') ) - if not seed: - show_message("no seed") - return False - - return seed, gap - - - -def run_settings_dialog(wallet, parent): - - message = "Here are the settings of your wallet. For more explanations, click on the question mark buttons next to each input field." - - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK_CANCEL, - message_format = message) - - image = gtk.Image() - image.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_DIALOG) - image.show() - dialog.set_image(image) - dialog.set_title("Settings") - - vbox = dialog.vbox - dialog.set_default_response(gtk.RESPONSE_OK) - - fee = gtk.HBox() - fee_entry = gtk.Entry() - fee_label = gtk.Label('Transaction fee:') - fee_label.set_size_request(150,10) - fee_label.show() - fee.pack_start(fee_label,False, False, 10) - fee_entry.set_text( str( Decimal(wallet.fee) /100000000 ) ) - fee_entry.connect('changed', numbify, False) - fee_entry.show() - fee.pack_start(fee_entry,False,False, 10) - add_help_button(fee, 'Fee per transaction input. Transactions involving multiple inputs tend to have a higher fee. Recommended value:0.0005') - fee.show() - vbox.pack_start(fee, False,False, 5) - - nz = gtk.HBox() - nz_entry = gtk.Entry() - nz_label = gtk.Label('Display zeros:') - nz_label.set_size_request(150,10) - nz_label.show() - nz.pack_start(nz_label,False, False, 10) - nz_entry.set_text( str( wallet.num_zeros )) - nz_entry.connect('changed', numbify, True) - nz_entry.show() - nz.pack_start(nz_entry,False,False, 10) - add_help_button(nz, "Number of zeros displayed after the decimal point.\nFor example, if this number is 2, then '5.' is displayed as '5.00'") - nz.show() - vbox.pack_start(nz, False,False, 5) - - # gui setting - gui_box = gtk.HBox() - gui_label = gtk.Label('Default GUI:') - gui_label.set_size_request(150,10) - gui_label.show() - gui_box.pack_start(gui_label,False, False, 10) - gui_combo = gtk.combo_box_new_text() - gui_names = ['lite', 'classic', 'gtk', 'text'] - for name in gui_names: gui_combo.append_text(name.capitalize()) - gui_combo.show() - gui_box.pack_start(gui_combo,False, False, 10) - gui_combo.set_active( gui_names.index( wallet.config.get("gui","lite")) ) - gui_box.show() - add_help_button(gui_box, "Select which GUI mode to use at start up.") - - vbox.pack_start(gui_box, False,False, 5) - - dialog.show() - r = dialog.run() - fee = fee_entry.get_text() - nz = nz_entry.get_text() - gui = gui_names[ gui_combo.get_active()] - - dialog.destroy() - if r==gtk.RESPONSE_CANCEL: - return - - try: - fee = int( 100000000 * Decimal(fee) ) - except: - show_message("error") - return - if wallet.fee != fee: - wallet.fee = fee - wallet.save() - - try: - nz = int( nz ) - if nz>8: nz = 8 - except: - show_message("error") - return - if wallet.num_zeros != nz: - wallet.num_zeros = nz - wallet.save() - - wallet.config.set_key('gui',gui,True) - - - - -def run_network_dialog( wallet, parent ): - image = gtk.Image() - image.set_from_stock(gtk.STOCK_NETWORK, gtk.ICON_SIZE_DIALOG) - interface = wallet.interface - if parent: - if interface.is_connected: - status = "Connected to %s:%d\n%d blocks"%(interface.host, interface.port, wallet.verifier.height) - else: - status = "Not connected" - else: - import random - status = "Please choose a server.\nSelect cancel if you are offline." - - server = interface.server - plist, servers_list = interface.get_servers_list() - - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, - gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status) - dialog.set_title("Server") - dialog.set_image(image) - image.show() - - vbox = dialog.vbox - host_box = gtk.HBox() - host_label = gtk.Label('Connect to:') - host_label.set_size_request(100,-1) - host_label.show() - host_box.pack_start(host_label, False, False, 10) - host_entry = gtk.Entry() - host_entry.set_size_request(200,-1) - host_entry.set_text(server) - host_entry.show() - host_box.pack_start(host_entry, False, False, 10) - add_help_button(host_box, 'The name and port number of your Electrum server, separated by a colon. Example: "ecdsa.org:50000". If no port number is provided, port 50000 will be tried. Some servers allow you to connect through http (port 80) or https (port 443)') - host_box.show() - - - p_box = gtk.HBox(False, 10) - p_box.show() - - p_label = gtk.Label('Protocol:') - p_label.set_size_request(100,-1) - p_label.show() - p_box.pack_start(p_label, False, False, 10) - - radio1 = gtk.RadioButton(None, "tcp") - p_box.pack_start(radio1, True, True, 0) - radio1.show() - radio2 = gtk.RadioButton(radio1, "http") - p_box.pack_start(radio2, True, True, 0) - radio2.show() - - def current_line(): - return unicode(host_entry.get_text()).split(':') - - def set_button(protocol): - if protocol == 't': - radio1.set_active(1) - elif protocol == 'h': - radio2.set_active(1) - - def set_protocol(protocol): - host = current_line()[0] - pp = plist[host] - if protocol not in pp.keys(): - protocol = pp.keys()[0] - set_button(protocol) - port = pp[protocol] - host_entry.set_text( host + ':' + port + ':' + protocol) - - radio1.connect("toggled", lambda x,y:set_protocol('t'), "radio button 1") - radio2.connect("toggled", lambda x,y:set_protocol('h'), "radio button 1") - - server_list = gtk.ListStore(str) - for host in plist.keys(): - server_list.append([host]) - - treeview = gtk.TreeView(model=server_list) - treeview.show() - - if wallet.interface.servers: - label = 'Active Servers' - else: - label = 'Default Servers' - - tvcolumn = gtk.TreeViewColumn(label) - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 0) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - scroll.show() - - vbox.pack_start(host_box, False,False, 5) - vbox.pack_start(p_box, True, True, 0) - vbox.pack_start(scroll) - - def my_treeview_cb(treeview): - path, view_column = treeview.get_cursor() - host = server_list.get_value( server_list.get_iter(path), 0) - - pp = plist[host] - if 't' in pp.keys(): - protocol = 't' - else: - protocol = pp.keys()[0] - port = pp[protocol] - host_entry.set_text( host + ':' + port + ':' + protocol) - set_button(protocol) - - treeview.connect('cursor-changed', my_treeview_cb) - - dialog.show() - r = dialog.run() - server = host_entry.get_text() - dialog.destroy() - - if r==gtk.RESPONSE_CANCEL: - return False - - try: - interface.set_server(server) - except: - show_message("error:" + server) - return False - - if parent: - wallet.config.set_key("server", server, True) - return True - - - -def show_message(message, parent=None): - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_CLOSE, - message_format = message ) - dialog.show() - dialog.run() - dialog.destroy() - -def password_line(label): - password = gtk.HBox() - password_label = gtk.Label(label) - password_label.set_size_request(120,10) - password_label.show() - password.pack_start(password_label,False, False, 10) - password_entry = gtk.Entry() - password_entry.set_size_request(300,-1) - password_entry.set_visibility(False) - password_entry.show() - password.pack_start(password_entry,False,False, 10) - password.show() - return password, password_entry - -def password_dialog(parent): - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, - gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Please enter your password.") - dialog.get_image().set_visible(False) - current_pw, current_pw_entry = password_line('Password:') - current_pw_entry.connect("activate", lambda entry, dialog, response: dialog.response(response), dialog, gtk.RESPONSE_OK) - dialog.vbox.pack_start(current_pw, False, True, 0) - dialog.show() - result = dialog.run() - pw = current_pw_entry.get_text() - dialog.destroy() - if result != gtk.RESPONSE_CANCEL: return pw - -def change_password_dialog(wallet, parent, icon): - if not wallet.seed: - show_message("No seed") - return - - if parent: - msg = 'Your wallet is encrypted. Use this dialog to change the password. To disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' - else: - msg = "Please choose a password to encrypt your wallet keys" - - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) - dialog.set_title("Change password") - image = gtk.Image() - image.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG) - image.show() - dialog.set_image(image) - - if wallet.use_encryption: - current_pw, current_pw_entry = password_line('Current password:') - dialog.vbox.pack_start(current_pw, False, True, 0) - - password, password_entry = password_line('New password:') - dialog.vbox.pack_start(password, False, True, 5) - password2, password2_entry = password_line('Confirm password:') - dialog.vbox.pack_start(password2, False, True, 5) - - dialog.show() - result = dialog.run() - password = current_pw_entry.get_text() if wallet.use_encryption else None - new_password = password_entry.get_text() - new_password2 = password2_entry.get_text() - dialog.destroy() - if result == gtk.RESPONSE_CANCEL: - return - - try: - seed = wallet.decode_seed(password) - except: - show_message("Incorrect password") - return - - if new_password != new_password2: - show_message("passwords do not match") - return - - wallet.update_password(seed, password, new_password) - - if icon: - if wallet.use_encryption: - icon.set_tooltip_text('wallet is encrypted') - else: - icon.set_tooltip_text('wallet is unencrypted') - - -def add_help_button(hbox, message): - button = gtk.Button('?') - button.connect("clicked", lambda x: show_message(message)) - button.show() - hbox.pack_start(button,False, False) - - -class MyWindow(gtk.Window): __gsignals__ = dict( mykeypress = (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_ACTION, None, (str,)) ) - -gobject.type_register(MyWindow) -gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.W, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+W') -gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.Q, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+Q') - - -class ElectrumWindow: - - def show_message(self, msg): - show_message(msg, self.window) - - def __init__(self, wallet, config): - self.config = config - self.wallet = wallet - self.funds_error = False # True if not enough funds - - self.window = MyWindow(gtk.WINDOW_TOPLEVEL) - title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.config.path - if not self.wallet.seed: title += ' [seedless]' - self.window.set_title(title) - self.window.connect("destroy", gtk.main_quit) - self.window.set_border_width(0) - self.window.connect('mykeypress', gtk.main_quit) - self.window.set_default_size(720, 350) - self.wallet_updated = False - - vbox = gtk.VBox() - - self.notebook = gtk.Notebook() - self.create_history_tab() - if self.wallet.seed: - self.create_send_tab() - self.create_recv_tab() - self.create_book_tab() - self.create_about_tab() - self.notebook.show() - vbox.pack_start(self.notebook, True, True, 2) - - self.status_bar = gtk.Statusbar() - vbox.pack_start(self.status_bar, False, False, 0) - - self.status_image = gtk.Image() - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - self.status_image.set_alignment(True, 0.5 ) - self.status_image.show() - - self.network_button = gtk.Button() - self.network_button.connect("clicked", lambda x: run_network_dialog(self.wallet, self.window) ) - self.network_button.add(self.status_image) - self.network_button.set_relief(gtk.RELIEF_NONE) - self.network_button.show() - self.status_bar.pack_end(self.network_button, False, False) - - if self.wallet.seed: - def seedb(w, wallet): - if wallet.use_encryption: - password = password_dialog(self.window) - if not password: return - else: password = None - show_seed_dialog(wallet, password, self.window) - button = gtk.Button('S') - button.connect("clicked", seedb, wallet ) - button.set_relief(gtk.RELIEF_NONE) - button.show() - self.status_bar.pack_end(button,False, False) - - settings_icon = gtk.Image() - settings_icon.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU) - settings_icon.set_alignment(0.5, 0.5) - settings_icon.set_size_request(16,16 ) - settings_icon.show() - - prefs_button = gtk.Button() - prefs_button.connect("clicked", lambda x: run_settings_dialog(self.wallet, self.window) ) - prefs_button.add(settings_icon) - prefs_button.set_tooltip_text("Settings") - prefs_button.set_relief(gtk.RELIEF_NONE) - prefs_button.show() - self.status_bar.pack_end(prefs_button,False,False) - - pw_icon = gtk.Image() - pw_icon.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU) - pw_icon.set_alignment(0.5, 0.5) - pw_icon.set_size_request(16,16 ) - pw_icon.show() - - if self.wallet.seed: - password_button = gtk.Button() - password_button.connect("clicked", lambda x: change_password_dialog(self.wallet, self.window, pw_icon)) - password_button.add(pw_icon) - password_button.set_relief(gtk.RELIEF_NONE) - password_button.show() - self.status_bar.pack_end(password_button,False,False) - - self.window.add(vbox) - self.window.show_all() - #self.fee_box.hide() - - self.context_id = self.status_bar.get_context_id("statusbar") - self.update_status_bar() - - self.wallet.interface.register_callback('updated', self.update_callback) - - - def update_status_bar_thread(): - while True: - gobject.idle_add( self.update_status_bar ) - time.sleep(0.5) - - - def check_recipient_thread(): - old_r = '' - while True: - time.sleep(0.5) - if self.payto_entry.is_focus(): - continue - r = self.payto_entry.get_text() - if r != old_r: - old_r = r - r = r.strip() - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): - try: - to_address = self.wallet.get_alias(r, interactive=False) - except: - continue - if to_address: - s = r + ' <' + to_address + '>' - gobject.idle_add( lambda: self.payto_entry.set_text(s) ) - - - thread.start_new_thread(update_status_bar_thread, ()) - if self.wallet.seed: - thread.start_new_thread(check_recipient_thread, ()) - self.notebook.set_current_page(0) - - def update_callback(self): - self.wallet_updated = True - - - def add_tab(self, page, name): - tab_label = gtk.Label(name) - tab_label.show() - self.notebook.append_page(page, tab_label) - - - def create_send_tab(self): - - page = vbox = gtk.VBox() - page.show() - - payto = gtk.HBox() - payto_label = gtk.Label('Pay to:') - payto_label.set_size_request(100,-1) - payto.pack_start(payto_label, False) - payto_entry = gtk.Entry() - payto_entry.set_size_request(450, 26) - payto.pack_start(payto_entry, False) - vbox.pack_start(payto, False, False, 5) - - message = gtk.HBox() - message_label = gtk.Label('Description:') - message_label.set_size_request(100,-1) - message.pack_start(message_label, False) - message_entry = gtk.Entry() - message_entry.set_size_request(450, 26) - message.pack_start(message_entry, False) - vbox.pack_start(message, False, False, 5) - - amount_box = gtk.HBox() - amount_label = gtk.Label('Amount:') - amount_label.set_size_request(100,-1) - amount_box.pack_start(amount_label, False) - amount_entry = gtk.Entry() - amount_entry.set_size_request(120, -1) - amount_box.pack_start(amount_entry, False) - vbox.pack_start(amount_box, False, False, 5) - - self.fee_box = fee_box = gtk.HBox() - fee_label = gtk.Label('Fee:') - fee_label.set_size_request(100,-1) - fee_box.pack_start(fee_label, False) - fee_entry = gtk.Entry() - fee_entry.set_size_request(60, 26) - fee_box.pack_start(fee_entry, False) - vbox.pack_start(fee_box, False, False, 5) - - end_box = gtk.HBox() - empty_label = gtk.Label('') - empty_label.set_size_request(100,-1) - end_box.pack_start(empty_label, False) - send_button = gtk.Button("Send") - send_button.show() - end_box.pack_start(send_button, False, False, 0) - clear_button = gtk.Button("Clear") - clear_button.show() - end_box.pack_start(clear_button, False, False, 15) - send_button.connect("clicked", self.do_send, (payto_entry, message_entry, amount_entry, fee_entry)) - clear_button.connect("clicked", self.do_clear, (payto_entry, message_entry, amount_entry, fee_entry)) - - vbox.pack_start(end_box, False, False, 5) - - # display this line only if there is a signature - payto_sig = gtk.HBox() - payto_sig_id = gtk.Label('') - payto_sig.pack_start(payto_sig_id, False) - vbox.pack_start(payto_sig, True, True, 5) - - - self.user_fee = False - - def entry_changed( entry, is_fee ): - self.funds_error = False - amount = numbify(amount_entry) - fee = numbify(fee_entry) - if not is_fee: fee = None - if amount is None: - return - inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) - if not is_fee: - fee_entry.set_text( str( Decimal( fee ) / 100000000 ) ) - self.fee_box.show() - if inputs: - amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) - fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) - send_button.set_sensitive(True) - else: - send_button.set_sensitive(False) - amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) - fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) - self.funds_error = True - - amount_entry.connect('changed', entry_changed, False) - fee_entry.connect('changed', entry_changed, True) - - self.payto_entry = payto_entry - self.payto_fee_entry = fee_entry - self.payto_sig_id = payto_sig_id - self.payto_sig = payto_sig - self.amount_entry = amount_entry - self.message_entry = message_entry - self.add_tab(page, 'Send') - - def set_frozen(self,entry,frozen): - if frozen: - entry.set_editable(False) - entry.set_has_frame(False) - entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#eeeeee")) - else: - entry.set_editable(True) - entry.set_has_frame(True) - entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#ffffff")) - - def set_url(self, url): - payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) - self.notebook.set_current_page(1) - self.payto_entry.set_text(payto) - self.message_entry.set_text(message) - self.amount_entry.set_text(amount) - if identity: - self.set_frozen(self.payto_entry,True) - self.set_frozen(self.amount_entry,True) - self.set_frozen(self.message_entry,True) - self.payto_sig_id.set_text( ' The bitcoin URI was signed by ' + identity ) - else: - self.payto_sig.set_visible(False) - - def create_about_tab(self): - import pango - page = gtk.VBox() - page.show() - tv = gtk.TextView() - tv.set_editable(False) - tv.set_cursor_visible(False) - tv.modify_font(pango.FontDescription(MONOSPACE_FONT)) - scroll = gtk.ScrolledWindow() - scroll.add(tv) - page.pack_start(scroll) - self.info = tv.get_buffer() - self.add_tab(page, 'Wall') - - def do_clear(self, w, data): - self.payto_sig.set_visible(False) - self.payto_fee_entry.set_text('') - for entry in [self.payto_entry,self.amount_entry,self.message_entry]: - self.set_frozen(entry,False) - entry.set_text('') - - def question(self,msg): - dialog = gtk.MessageDialog( self.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) - dialog.show() - result = dialog.run() - dialog.destroy() - return result == gtk.RESPONSE_OK - - def do_send(self, w, data): - payto_entry, label_entry, amount_entry, fee_entry = data - label = label_entry.get_text() - r = payto_entry.get_text() - r = r.strip() - - m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) - m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) - - if m1: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - if not to_address: - return - else: - self.update_sending_tab() - - elif m2: - to_address = m2.group(5) - else: - to_address = r - - if not is_valid(to_address): - self.show_message( "invalid bitcoin address:\n"+to_address) - return - - try: - amount = int( Decimal(amount_entry.get_text()) * 100000000 ) - except: - self.show_message( "invalid amount") - return - try: - fee = int( Decimal(fee_entry.get_text()) * 100000000 ) - except: - self.show_message( "invalid fee") - return - - if self.wallet.use_encryption: - password = password_dialog(self.window) - if not password: - return - else: - password = None - - try: - tx = self.wallet.mktx( [(to_address, amount)], password, fee ) - except BaseException, e: - self.show_message(str(e)) - return - - if label: - self.wallet.labels[tx.hash()] = label - - status, msg = self.wallet.sendtx( tx ) - if status: - self.show_message( "payment sent.\n" + msg ) - payto_entry.set_text("") - label_entry.set_text("") - amount_entry.set_text("") - fee_entry.set_text("") - #self.fee_box.hide() - self.update_sending_tab() - else: - self.show_message( msg ) - - - def treeview_button_press(self, treeview, event): - if event.type == gtk.gdk._2BUTTON_PRESS: - c = treeview.get_cursor()[0] - if treeview == self.history_treeview: - tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) - self.show_message(tx_details) - elif treeview == self.contacts_treeview: - m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self-signed" - msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] - self.show_message(msg) - - - def treeview_key_press(self, treeview, event): - c = treeview.get_cursor()[0] - if event.keyval == gtk.keysyms.Up: - if c and c[0] == 0: - treeview.parent.grab_focus() - treeview.set_cursor((0,)) - elif event.keyval == gtk.keysyms.Return: - if treeview == self.history_treeview: - tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) - self.show_message(tx_details) - elif treeview == self.contacts_treeview: - m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self" - msg = 'Alias:'+ m + '\n\nTarget: '+ a[1] + '\nSigned by: ' + s + '\nSigning address:' + a[0] - self.show_message(msg) - - return False - - def create_history_tab(self): - - self.history_list = gtk.ListStore(str, str, str, str, 'gboolean', str, str, str, str) - treeview = gtk.TreeView(model=self.history_list) - self.history_treeview = treeview - treeview.set_tooltip_column(7) - treeview.show() - treeview.connect('key-press-event', self.treeview_key_press) - treeview.connect('button-press-event', self.treeview_button_press) - - tvcolumn = gtk.TreeViewColumn('') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererPixbuf() - tvcolumn.pack_start(cell, False) - tvcolumn.set_attributes(cell, stock_id=1) - - tvcolumn = gtk.TreeViewColumn('Date') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 2) - - tvcolumn = gtk.TreeViewColumn('Description') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('foreground', 'grey') - cell.set_property('family', MONOSPACE_FONT) - cell.set_property('editable', True) - def edited_cb(cell, path, new_text, h_list): - tx = h_list.get_value( h_list.get_iter(path), 0) - self.wallet.labels[tx] = new_text - self.wallet.save() - self.update_history_tab() - cell.connect('edited', edited_cb, self.history_list) - def editing_started(cell, entry, path, h_list): - tx = h_list.get_value( h_list.get_iter(path), 0) - if not self.wallet.labels.get(tx): entry.set_text('') - cell.connect('editing-started', editing_started, self.history_list) - tvcolumn.set_expand(True) - tvcolumn.pack_start(cell, True) - tvcolumn.set_attributes(cell, text=3, foreground_set = 4) - - tvcolumn = gtk.TreeViewColumn('Amount') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_alignment(1, 0.5) - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 5) - - tvcolumn = gtk.TreeViewColumn('Balance') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_alignment(1, 0.5) - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 6) - - tvcolumn = gtk.TreeViewColumn('Tooltip') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 7) - tvcolumn.set_visible(False) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - - self.add_tab(scroll, 'History') - self.update_history_tab() - - - def create_recv_tab(self): - self.recv_list = gtk.ListStore(str, str, str) - self.add_tab( self.make_address_list(True), 'Receive') - self.update_receiving_tab() - - def create_book_tab(self): - self.addressbook_list = gtk.ListStore(str, str, str) - self.add_tab( self.make_address_list(False), 'Contacts') - self.update_sending_tab() - - def make_address_list(self, is_recv): - liststore = self.recv_list if is_recv else self.addressbook_list - treeview = gtk.TreeView(model= liststore) - treeview.connect('key-press-event', self.treeview_key_press) - treeview.connect('button-press-event', self.treeview_button_press) - treeview.show() - if not is_recv: - self.contacts_treeview = treeview - - tvcolumn = gtk.TreeViewColumn('Address') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 0) - - tvcolumn = gtk.TreeViewColumn('Label') - tvcolumn.set_expand(True) - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('editable', True) - def edited_cb2(cell, path, new_text, liststore): - address = liststore.get_value( liststore.get_iter(path), 0) - self.wallet.labels[address] = new_text - self.wallet.save() - self.update_receiving_tab() - self.update_sending_tab() - self.update_history_tab() - cell.connect('edited', edited_cb2, liststore) - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 1) - - tvcolumn = gtk.TreeViewColumn('Tx') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 2) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - - hbox = gtk.HBox() - if not is_recv: - button = gtk.Button("New") - button.connect("clicked", self.newaddress_dialog) - button.show() - hbox.pack_start(button,False) - - def showqrcode(w, treeview, liststore): - path, col = treeview.get_cursor() - if not path: return - address = liststore.get_value(liststore.get_iter(path), 0) - qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) - qr.addData(address) - qr.make() - boxsize = 7 - size = qr.getModuleCount()*boxsize - def area_expose_cb(area, event): - style = area.get_style() - k = qr.getModuleCount() - for r in range(k): - for c in range(k): - gc = style.black_gc if qr.isDark(r, c) else style.white_gc - area.window.draw_rectangle(gc, True, c*boxsize, r*boxsize, boxsize, boxsize) - area = gtk.DrawingArea() - area.set_size_request(size, size) - area.connect("expose-event", area_expose_cb) - area.show() - dialog = gtk.Dialog(address, parent=self.window, flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, buttons = ("ok",1)) - dialog.vbox.add(area) - dialog.run() - dialog.destroy() - - button = gtk.Button("QR") - button.connect("clicked", showqrcode, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - button = gtk.Button("Copy to clipboard") - def copy2clipboard(w, treeview, liststore): - import platform - path, col = treeview.get_cursor() - if path: - address = liststore.get_value( liststore.get_iter(path), 0) - if platform.system() == 'Windows': - from Tkinter import Tk - r = Tk() - r.withdraw() - r.clipboard_clear() - r.clipboard_append( address ) - r.destroy() - else: - c = gtk.clipboard_get() - c.set_text( address ) - button.connect("clicked", copy2clipboard, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - if not is_recv: - button = gtk.Button("Pay to") - def payto(w, treeview, liststore): - path, col = treeview.get_cursor() - if path: - address = liststore.get_value( liststore.get_iter(path), 0) - self.payto_entry.set_text( address ) - self.notebook.set_current_page(1) - self.amount_entry.grab_focus() - - button.connect("clicked", payto, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - vbox = gtk.VBox() - vbox.pack_start(scroll,True) - vbox.pack_start(hbox, False) - return vbox - - def update_status_bar(self): - interface = self.wallet.interface - if self.funds_error: - text = "Not enough funds" - elif interface and interface.is_connected: - self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks"%(interface.host, interface.port, self.wallet.verifier.height)) - if not self.wallet.up_to_date: - self.status_image.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) - text = "Synchronizing..." - else: - self.status_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_MENU) - self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks"%(interface.host, interface.port, self.wallet.verifier.height)) - c, u = self.wallet.get_balance() - text = "Balance: %s "%( format_satoshis(c,False,self.wallet.num_zeros) ) - if u: text += "[%s unconfirmed]"%( format_satoshis(u,True,self.wallet.num_zeros).strip() ) - else: - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - self.network_button.set_tooltip_text("Not connected.") - text = "Not connected" - - self.status_bar.pop(self.context_id) - self.status_bar.push(self.context_id, text) - - if self.wallet.up_to_date and self.wallet_updated: - self.update_history_tab() - self.update_receiving_tab() - # addressbook too... - self.info.set_text( self.wallet.banner ) - self.wallet_updated = False - - def update_receiving_tab(self): - self.recv_list.clear() - for address in self.wallet.addresses(True): - if self.wallet.is_change(address):continue - label = self.wallet.labels.get(address) - h = self.wallet.history.get(address,[]) - n = len(h) - tx = "None" if n==0 else "%d"%n - self.recv_list.append((address, label, tx )) - - def update_sending_tab(self): - # detect addresses that are not mine in history, add them here... - self.addressbook_list.clear() - for alias, v in self.wallet.aliases.items(): - s, target = v - label = self.wallet.labels.get(alias) - self.addressbook_list.append((alias, label, '-')) - - for address in self.wallet.addressbook: - label = self.wallet.labels.get(address) - n = 0 - for tx in self.wallet.transactions.values(): - if address in map(lambda x:x[0], tx.outputs): n += 1 - - self.addressbook_list.append((address, label, "%d"%n)) - - def update_history_tab(self): - cursor = self.history_treeview.get_cursor()[0] - self.history_list.clear() - - for item in self.wallet.get_tx_history(): - tx_hash, conf, is_mine, value, fee, balance, timestamp = item - if conf: - try: - time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] - except: - time_str = "------" - conf_icon = gtk.STOCK_APPLY - else: - time_str = 'pending' - conf_icon = gtk.STOCK_EXECUTE - - label, is_default_label = self.wallet.get_label(tx_hash) - tooltip = tx_hash + "\n%d confirmations"%conf if tx_hash else '' - details = self.wallet.get_tx_details(tx_hash) - - self.history_list.prepend( [tx_hash, conf_icon, time_str, label, is_default_label, - format_satoshis(value,True,self.wallet.num_zeros), - format_satoshis(balance,False,self.wallet.num_zeros), tooltip, details] ) - if cursor: self.history_treeview.set_cursor( cursor ) - - - - def newaddress_dialog(self, w): - - title = "New Contact" - dialog = gtk.Dialog(title, parent=self.window, - flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, - buttons= ("cancel", 0, "ok",1) ) - dialog.show() - - label = gtk.HBox() - label_label = gtk.Label('Label:') - label_label.set_size_request(120,10) - label_label.show() - label.pack_start(label_label) - label_entry = gtk.Entry() - label_entry.show() - label.pack_start(label_entry) - label.show() - dialog.vbox.pack_start(label, False, True, 5) - - address = gtk.HBox() - address_label = gtk.Label('Address:') - address_label.set_size_request(120,10) - address_label.show() - address.pack_start(address_label) - address_entry = gtk.Entry() - address_entry.show() - address.pack_start(address_entry) - address.show() - dialog.vbox.pack_start(address, False, True, 5) - - result = dialog.run() - address = address_entry.get_text() - label = label_entry.get_text() - dialog.destroy() - - if result == 1: - if is_valid(address): - self.wallet.addressbook.append(address) - if label: self.wallet.labels[address] = label - self.wallet.save() - self.update_sending_tab() - else: - errorDialog = gtk.MessageDialog( - parent=self.window, - flags=gtk.DIALOG_MODAL, - buttons= gtk.BUTTONS_CLOSE, - message_format = "Invalid address") - errorDialog.show() - errorDialog.run() - errorDialog.destroy() - - - -class ElectrumGui(): - - def __init__(self, wallet, config): - self.wallet = wallet - self.config = config - - def main(self, url=None): - ew = ElectrumWindow(self.wallet, self.config) - if url: ew.set_url(url) - gtk.main() - - def restore_or_create(self): - return restore_create_dialog(self.wallet) - - def seed_dialog(self): - return run_recovery_dialog( self.wallet ) - - def network_dialog(self): - return run_network_dialog( self.wallet, parent=None ) - - def show_seed(self): - show_seed_dialog(self.wallet, None, None) - - def password_dialog(self): - change_password_dialog(self.wallet, None, None) - - def restore_wallet(self): - wallet = self.wallet - - dialog = gtk.MessageDialog( - parent = None, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_CANCEL, - message_format = "Please wait..." ) - dialog.show() - - def recover_thread( wallet, dialog ): - while not wallet.is_up_to_date(): - time.sleep(0.1) - gobject.idle_add( dialog.destroy ) - - thread.start_new_thread( recover_thread, ( wallet, dialog ) ) - r = dialog.run() - dialog.destroy() - if r==gtk.RESPONSE_CANCEL: return False - if not wallet.is_found(): - show_message("No transactions found for this seed") - - wallet.save() - return True diff --git a/lib/gui_android.py b/lib/gui_android.py @@ -1,1003 +0,0 @@ -#!/usr/bin/env python -# -# Electrum - lightweight Bitcoin client -# Copyright (C) 2011 thomasv@gitorious -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - - - - -import android - -from electrum import SimpleConfig, Interface, WalletSynchronizer, Wallet, format_satoshis, mnemonic_encode, mnemonic_decode -from decimal import Decimal -import datetime, re -from bitcoin import is_valid - - - -def modal_dialog(title, msg = None): - droid.dialogCreateAlert(title,msg) - droid.dialogSetPositiveButtonText('OK') - droid.dialogShow() - droid.dialogGetResponse() - droid.dialogDismiss() - -def modal_input(title, msg, value = None, etype=None): - droid.dialogCreateInput(title, msg, value, etype) - droid.dialogSetPositiveButtonText('OK') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse() - result = response.result - if result is None: - print "modal input: result is none" - return False - droid.dialogDismiss() - if result.get('which') == 'positive': - return result.get('value') - -def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'): - droid.dialogCreateAlert(q, msg) - droid.dialogSetPositiveButtonText(pos_text) - droid.dialogSetNegativeButtonText(neg_text) - droid.dialogShow() - response = droid.dialogGetResponse() - result = response.result - if result is None: - print "modal question: result is none" - return False - droid.dialogDismiss() - return result.get('which') == 'positive' - -def edit_label(addr): - v = modal_input('Edit label',None,wallet.labels.get(addr)) - if v is not None: - if v: - wallet.labels[addr] = v - else: - if addr in wallet.labels.keys(): - wallet.labels.pop(addr) - wallet.update_tx_history() - wallet.save() - droid.fullSetProperty("labelTextView", "text", v) - -def select_from_contacts(): - title = 'Contacts:' - droid.dialogCreateAlert(title) - l = [] - for i in range(len(wallet.addressbook)): - addr = wallet.addressbook[i] - label = wallet.labels.get(addr,addr) - l.append( label ) - droid.dialogSetItems(l) - droid.dialogSetPositiveButtonText('New contact') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - - if response.get('which') == 'positive': - return 'newcontact' - - result = response.get('item') - print result - if result is not None: - addr = wallet.addressbook[result] - return addr - - -def select_from_addresses(): - droid.dialogCreateAlert("Addresses:") - l = [] - addresses = wallet.addresses() - for i in range(len(addresses)): - addr = addresses[i] - label = wallet.labels.get(addr,addr) - l.append( label ) - droid.dialogSetItems(l) - droid.dialogShow() - response = droid.dialogGetResponse() - result = response.result.get('item') - droid.dialogDismiss() - if result is not None: - addr = addresses[result] - return addr - - -def protocol_name(p): - if p == 't': return 'TCP' - if p == 'h': return 'HTTP' - if p == 's': return 'TCP/SSL' - if p == 'g': return 'HTTPS' - - -def protocol_dialog(host, protocol, z): - droid.dialogCreateAlert('Protocol',host) - if z: - protocols = z.keys() - else: - protocols = 'thsg' - l = [] - current = protocols.index(protocol) - for p in protocols: - l.append(protocol_name(p)) - droid.dialogSetSingleChoiceItems(l, current) - droid.dialogSetPositiveButtonText('OK') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse().result - selected_item = droid.dialogGetSelectedItems().result - droid.dialogDismiss() - - if not response: return - if not selected_item: return - if response.get('which') == 'positive': - p = protocols[selected_item[0]] - port = z[p] - return host + ':' + port + ':' + p - - - - -def make_layout(s, scrollable = False): - content = """ - - <LinearLayout - android:id="@+id/zz" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:background="#ff222222"> - - <TextView - android:id="@+id/textElectrum" - android:text="Electrum" - android:textSize="7pt" - android:textColor="#ff4444ff" - android:gravity="left" - android:layout_height="wrap_content" - android:layout_width="match_parent" - /> - </LinearLayout> - - %s """%s - - if scrollable: - content = """ - <ScrollView - android:id="@+id/scrollview" - android:layout_width="match_parent" - android:layout_height="match_parent" > - - <LinearLayout - android:orientation="vertical" - android:layout_width="match_parent" - android:layout_height="wrap_content" > - - %s - - </LinearLayout> - </ScrollView> - """%content - - - return """<?xml version="1.0" encoding="utf-8"?> - <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/background" - android:orientation="vertical" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:background="#ff000022"> - - %s - </LinearLayout>"""%content - - - - -def main_layout(): - return make_layout(""" - <TextView android:id="@+id/balanceTextView" - android:layout_width="match_parent" - android:text="" - android:textColor="#ffffffff" - android:textAppearance="?android:attr/textAppearanceLarge" - android:padding="7dip" - android:textSize="8pt" - android:gravity="center_vertical|center_horizontal|left"> - </TextView> - - <TextView android:id="@+id/historyTextView" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="Recent transactions" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="center_vertical|center_horizontal|center"> - </TextView> - - %s """%get_history_layout(15),True) - - - -def qr_layout(addr): - return make_layout(""" - - <TextView android:id="@+id/addrTextView" - android:layout_width="match_parent" - android:layout_height="50" - android:text="%s" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="center_vertical|center_horizontal|center"> - </TextView> - - <ImageView - android:id="@+id/qrView" - android:gravity="center" - android:layout_width="match_parent" - android:layout_height="350" - android:antialias="false" - android:src="file:///sdcard/sl4a/qrcode.bmp" /> - - <TextView android:id="@+id/labelTextView" - android:layout_width="match_parent" - android:layout_height="50" - android:text="%s" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="center_vertical|center_horizontal|center"> - </TextView> - - """%(addr,wallet.labels.get(addr,'')), True) - -payto_layout = make_layout(""" - - <TextView android:id="@+id/recipientTextView" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="Pay to:" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="left"> - </TextView> - - - <EditText android:id="@+id/recipient" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:tag="Tag Me" android:inputType="text"> - </EditText> - - <LinearLayout android:id="@+id/linearLayout1" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - <Button android:id="@+id/buttonQR" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:text="From QR code"></Button> - <Button android:id="@+id/buttonContacts" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:text="From Contacts"></Button> - </LinearLayout> - - - <TextView android:id="@+id/labelTextView" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="Description:" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="left"> - </TextView> - - <EditText android:id="@+id/label" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:tag="Tag Me" android:inputType="text"> - </EditText> - - <TextView android:id="@+id/amountLabelTextView" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="Amount:" - android:textAppearance="?android:attr/textAppearanceLarge" - android:gravity="left"> - </TextView> - - <EditText android:id="@+id/amount" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:tag="Tag Me" android:inputType="numberDecimal"> - </EditText> - - <LinearLayout android:layout_width="match_parent" - android:layout_height="wrap_content" android:id="@+id/linearLayout1"> - <Button android:id="@+id/buttonPay" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:text="Send"></Button> - </LinearLayout>""",False) - - - -settings_layout = make_layout(""" <ListView - android:id="@+id/myListView" - android:layout_width="match_parent" - android:layout_height="wrap_content" />""") - - - -def get_history_values(n): - values = [] - h = wallet.get_tx_history() - length = min(n, len(h)) - for i in range(length): - tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1] - try: - dt = datetime.datetime.fromtimestamp( timestamp ) - if dt.date() == dt.today().date(): - time_str = str( dt.time() ) - else: - time_str = str( dt.date() ) - except: - time_str = 'pending' - - conf_str = 'v' if conf else 'o' - label, is_default_label = wallet.get_label(tx_hash) - values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label )) - - return values - - -def get_history_layout(n): - rows = "" - i = 0 - values = get_history_values(n) - for v in values: - a,b,c,d = v - color = "#ff00ff00" if a == 'v' else "#ffff0000" - rows += """ - <TableRow> - <TextView - android:id="@+id/hl_%d_col1" - android:layout_column="0" - android:text="%s" - android:textColor="%s" - android:padding="3" /> - <TextView - android:id="@+id/hl_%d_col2" - android:layout_column="1" - android:text="%s" - android:padding="3" /> - <TextView - android:id="@+id/hl_%d_col3" - android:layout_column="2" - android:text="%s" - android:padding="3" /> - <TextView - android:id="@+id/hl_%d_col4" - android:layout_column="3" - android:text="%s" - android:padding="4" /> - </TableRow>"""%(i,a,color,i,b,i,c,i,d) - i += 1 - - output = """ -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:stretchColumns="0,1,2,3"> - %s -</TableLayout>"""% rows - return output - - -def set_history_layout(n): - values = get_history_values(n) - i = 0 - for v in values: - a,b,c,d = v - droid.fullSetProperty("hl_%d_col1"%i,"text", a) - - if a == 'v': - droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00") - else: - droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000") - - droid.fullSetProperty("hl_%d_col2"%i,"text", b) - droid.fullSetProperty("hl_%d_col3"%i,"text", c) - droid.fullSetProperty("hl_%d_col4"%i,"text", d) - i += 1 - - - - -status_text = '' -def update_layout(): - global status_text - if not wallet.interface.is_connected: - text = "Not connected..." - elif not wallet.up_to_date: - text = "Synchronizing..." - else: - c, u = wallet.get_balance() - text = "Balance:"+format_satoshis(c) - if u : text += ' [' + format_satoshis(u,True).strip() + ']' - - - # vibrate if status changed - if text != status_text: - if status_text and wallet.interface.is_connected and wallet.up_to_date: - droid.vibrate() - status_text = text - - droid.fullSetProperty("balanceTextView", "text", status_text) - - if wallet.up_to_date: - set_history_layout(15) - - - - -def pay_to(recipient, amount, fee, label): - - if wallet.use_encryption: - password = droid.dialogGetPassword('Password').result - if not password: return - else: - password = None - - droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...") - droid.dialogShow() - - try: - tx = wallet.mktx( [(recipient, amount)], password, fee) - except BaseException, e: - modal_dialog('error', e.message) - droid.dialogDismiss() - return - - if label: - self.wallet.labels[tx.hash()] = label - - droid.dialogDismiss() - - r, h = wallet.sendtx( tx ) - if r: - modal_dialog('Payment sent', h) - return True - else: - modal_dialog('Error', h) - - - - - - - -def make_new_contact(): - code = droid.scanBarcode() - r = code.result - if r: - data = r['extras']['SCAN_RESULT'] - if data: - if re.match('^bitcoin:', data): - address, _, _, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question',x)) - elif is_valid(data): - address = data - else: - address = None - if address: - if modal_question('Add to contacts?', address): - wallet.addressbook.append(address) - wallet.save() - else: - modal_dialog('Invalid address', data) - - -do_refresh = False - -def update_callback(): - global do_refresh - print "gui callback", wallet.interface.is_connected, wallet.up_to_date - do_refresh = True - droid.eventPost("refresh",'z') - -def main_loop(): - global do_refresh - - update_layout() - out = None - quitting = False - while out is None: - - event = droid.eventWait(1000).result - if event is None: - if do_refresh: - update_layout() - do_refresh = False - continue - - print "got event in main loop", repr(event) - if event == 'OK': continue - if event is None: continue - if not event.get("name"): continue - - # request 2 taps before we exit - if event["name"]=="key": - if event["data"]["key"] == '4': - if quitting: - out = 'quit' - else: - quitting = True - else: quitting = False - - if event["name"]=="click": - id=event["data"]["id"] - - elif event["name"]=="settings": - out = 'settings' - - elif event["name"] in menu_commands: - out = event["name"] - - if out == 'contacts': - global contact_addr - contact_addr = select_from_contacts() - if contact_addr == 'newcontact': - make_new_contact() - contact_addr = None - if not contact_addr: - out = None - - elif out == "receive": - global receive_addr - receive_addr = select_from_addresses() - if receive_addr: - amount = modal_input('Amount', 'Amount you want receive. ', '', "numberDecimal") - if amount: - receive_addr = 'bitcoin:%s?amount=%s'%(receive_addr, amount) - - if not receive_addr: - out = None - - - return out - - -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') - label = droid.fullQueryDetail("label").result.get('text') - amount = droid.fullQueryDetail('amount').result.get('text') - - if not is_valid(recipient): - modal_dialog('Error','Invalid Bitcoin address') - continue - - try: - amount = int( 100000000 * Decimal(amount) ) - except: - modal_dialog('Error','Invalid amount') - continue - - result = pay_to(recipient, amount, wallet.fee, label) - 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 = r['extras']['SCAN_RESULT'] - if data: - if re.match('^bitcoin:', data): - payto, amount, label, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question', x)) - droid.fullSetProperty("recipient", "text",payto) - droid.fullSetProperty("amount", "text", amount) - droid.fullSetProperty("label", "text", label) - else: - droid.fullSetProperty("recipient", "text", 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 - - -receive_addr = '' -contact_addr = '' -recipient = '' - -def receive_loop(): - out = None - while out is None: - event = droid.eventWait().result - print "got event", event - if event["name"]=="key": - if event["data"]["key"] == '4': - out = 'main' - - elif event["name"]=="clipboard": - droid.setClipboard(receive_addr) - modal_dialog('Address copied to clipboard',receive_addr) - - elif event["name"]=="edit": - edit_label(receive_addr) - - return out - -def contacts_loop(): - global recipient - out = None - while out is None: - event = droid.eventWait().result - print "got event", event - if event["name"]=="key": - if event["data"]["key"] == '4': - out = 'main' - - elif event["name"]=="clipboard": - droid.setClipboard(contact_addr) - modal_dialog('Address copied to clipboard',contact_addr) - - elif event["name"]=="edit": - edit_label(contact_addr) - - elif event["name"]=="paytocontact": - recipient = contact_addr - out = 'send' - - elif event["name"]=="deletecontact": - if modal_question('delete contact', contact_addr): - out = 'main' - - return out - - -def server_dialog(plist): - droid.dialogCreateAlert("Public servers") - droid.dialogSetItems( plist.keys() ) - droid.dialogSetPositiveButtonText('Private server') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - if not response: return - - if response.get('which') == 'positive': - return modal_input('Private server', None) - - i = response.get('item') - if i is not None: - response = plist.keys()[i] - return response - - -def seed_dialog(): - if wallet.use_encryption: - password = droid.dialogGetPassword('Seed').result - if not password: return - else: - password = None - - try: - seed = wallet.decode_seed(password) - except: - modal_dialog('error','incorrect password') - return - - modal_dialog('Your seed is',seed) - modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) ) - -def change_password_dialog(): - if wallet.use_encryption: - password = droid.dialogGetPassword('Your wallet is encrypted').result - if password is None: return - else: - password = None - - try: - seed = wallet.decode_seed(password) - except: - modal_dialog('error','incorrect password') - return - - new_password = droid.dialogGetPassword('Choose a password').result - if new_password == None: - return - - if new_password != '': - password2 = droid.dialogGetPassword('Confirm new password').result - if new_password != password2: - modal_dialog('error','passwords do not match') - return - - wallet.update_password(seed, password, new_password) - if new_password: - modal_dialog('Password updated','your wallet is encrypted') - else: - modal_dialog('No password','your wallet is not encrypted') - return True - - -def settings_loop(): - - - def set_listview(): - server, port, p = interface.server.split(':') - fee = str( Decimal( wallet.fee)/100000000 ) - is_encrypted = 'yes' if wallet.use_encryption else 'no' - protocol = protocol_name(p) - droid.fullShow(settings_layout) - droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed']) - - set_listview() - - out = None - while out is None: - event = droid.eventWait() - event = event.result - print "got event", event - if event == 'OK': continue - if not event: continue - - plist, servers_list = interface.get_servers_list() - name = event.get("name") - if not name: continue - - if name == "itemclick": - pos = event["data"]["position"] - host, port, protocol = interface.server.split(':') - - if pos == "0": #server - host = server_dialog(plist) - if host: - p = plist[host] - port = p['t'] - srv = host + ':' + port + ':t' - wallet.config.set_key("server", srv, True) - try: - wallet.interface.set_server(srv) - except: - modal_dialog('error','invalid server') - set_listview() - - elif pos == "1": #protocol - if host in plist: - srv = protocol_dialog(host, protocol, plist[host]) - if srv: - wallet.config.set_key("server", srv, True) - try: - wallet.interface.set_server(srv) - except: - modal_dialog('error','invalid server') - set_listview() - - elif pos == "2": #port - a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number") - if a_port: - if a_port != port: - srv = host + ':' + a_port + ':'+ protocol - wallet.config.set_key("server", srv, True) - try: - wallet.interface.set_server(srv) - except: - modal_dialog('error','invalid port number') - set_listview() - - elif pos == "3": #fee - fee = modal_input('Transaction fee', 'The fee will be this amount multiplied by the number of inputs in your transaction. ', str( Decimal( wallet.fee)/100000000 ), "numberDecimal") - if fee: - try: - fee = int( 100000000 * Decimal(fee) ) - except: - modal_dialog('error','invalid fee value') - if wallet.fee != fee: - wallet.fee = fee - wallet.save() - set_listview() - - elif pos == "4": - if change_password_dialog(): - set_listview() - - elif pos == "5": - seed_dialog() - - - elif name in menu_commands: - out = event["name"] - - elif name == 'cancel': - out = 'main' - - elif name == "key": - if event["data"]["key"] == '4': - out = 'main' - - return out - -def add_menu(s): - droid.clearOptionsMenu() - if s == 'main': - droid.addOptionsMenuItem("Send","send",None,"") - droid.addOptionsMenuItem("Receive","receive",None,"") - droid.addOptionsMenuItem("Contacts","contacts",None,"") - droid.addOptionsMenuItem("Settings","settings",None,"") - elif s == 'receive': - droid.addOptionsMenuItem("Copy","clipboard",None,"") - droid.addOptionsMenuItem("Label","edit",None,"") - elif s == 'contacts': - droid.addOptionsMenuItem("Copy","clipboard",None,"") - droid.addOptionsMenuItem("Label","edit",None,"") - droid.addOptionsMenuItem("Pay to","paytocontact",None,"") - #droid.addOptionsMenuItem("Delete","deletecontact",None,"") - - -def make_bitmap(addr): - # fixme: this is highly inefficient - droid.dialogCreateSpinnerProgress("please wait") - droid.dialogShow() - try: - import pyqrnative, bmp - qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.L) - qr.addData(addr) - qr.make() - k = qr.getModuleCount() - assert k == 33 - bmp.save_qrcode(qr,"/sdcard/sl4a/qrcode.bmp") - finally: - droid.dialogDismiss() - - - - -droid = android.Android() -menu_commands = ["send", "receive", "settings", "contacts", "main"] -wallet = None -interface = None - -class ElectrumGui: - - def __init__(self, w, config, app=None): - global wallet, interface - wallet = w - interface = wallet.interface - interface.register_callback('updated',update_callback) - interface.register_callback('connected', update_callback) - interface.register_callback('disconnected', update_callback) - interface.register_callback('disconnecting', update_callback) - - - def main(self, url): - s = 'main' - while True: - add_menu(s) - if s == 'main': - droid.fullShow(main_layout()) - s = main_loop() - - elif s == 'send': - droid.fullShow(payto_layout) - s = payto_loop() - - elif s == 'receive': - make_bitmap(receive_addr) - droid.fullShow(qr_layout(receive_addr)) - s = receive_loop() - - elif s == 'contacts': - make_bitmap(contact_addr) - droid.fullShow(qr_layout(contact_addr)) - s = contacts_loop() - - elif s == 'settings': - s = settings_loop() - - else: - break - - droid.makeToast("Bye!") - - def restore_or_create(self): - droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?") - droid.dialogSetPositiveButtonText('Create') - droid.dialogSetNeutralButtonText('Restore') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - if not response: return - if response.get('which') == 'negative': - return - - return 'restore' if response.get('which') == 'neutral' else 'create' - - def seed_dialog(self): - if modal_question("Input method",None,'QR Code', 'mnemonic'): - code = droid.scanBarcode() - r = code.result - if r: - seed = r['extras']['SCAN_RESULT'] - else: - return - else: - m = modal_input('Mnemonic','please enter your code') - try: - seed = mnemonic_decode(m.split(' ')) - except: - modal_dialog('error: could not decode this seed') - return - - gap = 5 # default - - return str(seed), gap - - - def network_dialog(self): - return True - - - def show_seed(self): - modal_dialog('Your seed is:', wallet.seed) - modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) ) - - - def password_dialog(self): - change_password_dialog() - - - def restore_wallet(self): - - msg = "recovering wallet..." - droid.dialogCreateSpinnerProgress("Electrum", msg) - droid.dialogShow() - - wallet.update() - - droid.dialogDismiss() - droid.vibrate() - - if wallet.is_found(): - wallet.fill_addressbook() - modal_dialog("recovery successful") - else: - if not modal_question("no transactions found for this seed","do you want to keep this wallet?"): - return False - - wallet.save() - return True - diff --git a/lib/gui_lite.py b/lib/gui_lite.py @@ -1,1008 +0,0 @@ -import sys - -# Let's do some dep checking and handle missing ones gracefully -try: - from PyQt4.QtCore import * - from PyQt4.QtGui import * - import PyQt4.QtCore as QtCore - -except ImportError: - print "You need to have PyQT installed to run Electrum in graphical mode." - print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'." - sys.exit(0) - -from decimal import Decimal as D -from util import get_resource_path as rsrc -from bitcoin import is_valid -from i18n import _ -import decimal -import exchange_rate -import os.path -import random -import re -import time -import wallet -import webbrowser -import history_widget -import receiving_widget -import util -import csv -import datetime - -from version import ELECTRUM_VERSION as electrum_version -from wallet import format_satoshis -import gui_qt -import shutil - -bitcoin = lambda v: v * 100000000 - -def IconButton(filename, parent=None): - pixmap = QPixmap(filename) - icon = QIcon(pixmap) - return QPushButton(icon, "", parent) - -class Timer(QThread): - def run(self): - while True: - self.emit(SIGNAL('timersignal')) - time.sleep(0.5) - -def resize_line_edit_width(line_edit, text_input): - metrics = QFontMetrics(qApp.font()) - # Create an extra character to add some space on the end - text_input += "A" - line_edit.setMinimumWidth(metrics.width(text_input)) - -def load_theme_name(theme_path): - try: - with open(os.path.join(theme_path, "name.cfg")) as name_cfg_file: - return name_cfg_file.read().rstrip("\n").strip() - except IOError: - return None - - -def theme_dirs_from_prefix(prefix): - if not os.path.exists(prefix): - return [] - theme_paths = {} - for potential_theme in os.listdir(prefix): - theme_full_path = os.path.join(prefix, potential_theme) - theme_css = os.path.join(theme_full_path, "style.css") - if not os.path.exists(theme_css): - continue - theme_name = load_theme_name(theme_full_path) - if theme_name is None: - continue - theme_paths[theme_name] = prefix, potential_theme - return theme_paths - -def load_theme_paths(): - theme_paths = {} - prefixes = (util.local_data_dir(), util.appdata_dir()) - for prefix in prefixes: - theme_paths.update(theme_dirs_from_prefix(prefix)) - return theme_paths - - -def csv_transaction(wallet): - try: - select_export = _('Select file to export your wallet transactions to') - fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-history.csv'), "*.csv") - if fileName: - with open(fileName, "w+") as csvfile: - transaction = csv.writer(csvfile) - transaction.writerow(["transaction_hash","label", "confirmations", "value", "fee", "balance", "timestamp"]) - for item in wallet.get_tx_history(): - tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item - if confirmations: - if timestamp is not None: - try: - time_string = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] - except [RuntimeError, TypeError, NameError] as reason: - time_string = "unknown" - pass - else: - time_string = "unknown" - else: - time_string = "pending" - - if value is not None: - value_string = format_satoshis(value, True, wallet.num_zeros) - else: - value_string = '--' - - if fee is not None: - fee_string = format_satoshis(fee, True, wallet.num_zeros) - else: - fee_string = '0' - - if tx_hash: - label, is_default_label = wallet.get_label(tx_hash) - else: - label = "" - - balance_string = format_satoshis(balance, False, wallet.num_zeros) - transaction.writerow([tx_hash, label, confirmations, value_string, fee_string, balance_string, time_string]) - QMessageBox.information(None,"CSV Export created", "Your CSV export has been successfully created.") - except (IOError, os.error), reason: - export_error_label = _("Electrum was unable to produce a transaction export.") - QMessageBox.critical(None,"Unable to create csv", export_error_label + "\n" + str(reason)) - - -class ElectrumGui(QObject): - - def __init__(self, wallet, config, expert=None): - super(QObject, self).__init__() - - self.wallet = wallet - self.config = config - self.check_qt_version() - self.expert = expert - if self.expert != None: - self.app = self.expert.app - else: - self.app = QApplication(sys.argv) - - def check_qt_version(self): - qtVersion = qVersion() - if not(int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7): - app = QApplication(sys.argv) - QMessageBox.warning(None,"Could not start Lite GUI.", "Electrum was unable to load the 'Lite GUI' because it needs Qt version >= 4.7.\nChanging your config to use the 'Classic' GUI") - self.config.set_key('gui','classic',True) - sys.exit(0) - - - def main(self, url): - actuator = MiniActuator(self.wallet) - # Should probably not modify the current path but instead - # change the behaviour of rsrc(...) - old_path = QDir.currentPath() - actuator.load_theme() - - self.mini = MiniWindow(actuator, self.expand, self.config) - driver = MiniDriver(self.wallet, self.mini) - - # Reset path back to original value now that loading the GUI - # is completed. - QDir.setCurrent(old_path) - - if url: - self.set_url(url) - - if self.expert == None: - timer = Timer() - timer.start() - self.expert = gui_qt.ElectrumWindow(self.wallet, self.config) - self.expert.app = self.app - self.expert.connect_slots(timer) - self.expert.update_wallet() - self.app.exec_() - - def expand(self): - """Hide the lite mode window and show pro-mode.""" - self.config.set_key('gui', 'classic', True) - self.mini.hide() - self.expert.show() - - def set_url(self, url): - payto, amount, label, message, signature, identity, url = \ - self.wallet.parse_url(url, self.show_message, self.show_question) - self.mini.set_payment_fields(payto, amount) - - def show_message(self, message): - QMessageBox.information(self.mini, _("Message"), message, _("OK")) - - def show_question(self, message): - choice = QMessageBox.question(self.mini, _("Message"), message, - QMessageBox.Yes|QMessageBox.No, - QMessageBox.No) - return choice == QMessageBox.Yes - - def restore_or_create(self): - qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app) - return qt_gui_object.restore_or_create() - -class TransactionWindow(QDialog): - - def set_label(self): - label = unicode(self.label_edit.text()) - self.parent.wallet.labels[self.tx_id] = label - - super(TransactionWindow, self).accept() - - 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_() - -class MiniWindow(QDialog): - - def __init__(self, actuator, expand_callback, config): - super(MiniWindow, self).__init__() - tx = "e08115d0f7819aee65b9d24f81ef9d46eb62bb67ddef5318156cbc3ceb7b703e" - - self.actuator = actuator - self.config = config - self.btc_balance = None - self.quote_currencies = ["BRL", "CNY", "EUR", "GBP", "RUB", "USD"] - self.actuator.set_configured_currency(self.set_quote_currency) - self.exchanger = exchange_rate.Exchanger(self) - # Needed because price discovery is done in a different thread - # which needs to be sent back to this main one to update the GUI - self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance) - - self.balance_label = BalanceLabel(self.change_quote_currency) - self.balance_label.setObjectName("balance_label") - - - # Bitcoin address code - self.address_input = QLineEdit() - self.address_input.setPlaceholderText(_("Enter a Bitcoin address or contact")) - self.address_input.setObjectName("address_input") - - self.address_input.setFocusPolicy(Qt.ClickFocus) - - self.address_input.textChanged.connect(self.address_field_changed) - resize_line_edit_width(self.address_input, - "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy") - - self.address_completions = QStringListModel() - address_completer = QCompleter(self.address_input) - address_completer.setCaseSensitivity(False) - address_completer.setModel(self.address_completions) - self.address_input.setCompleter(address_completer) - - address_layout = QHBoxLayout() - address_layout.addWidget(self.address_input) - - self.amount_input = QLineEdit() - self.amount_input.setPlaceholderText(_("... and amount")) - self.amount_input.setObjectName("amount_input") - - self.amount_input.setFocusPolicy(Qt.ClickFocus) - # This is changed according to the user's displayed balance - self.amount_validator = QDoubleValidator(self.amount_input) - self.amount_validator.setNotation(QDoubleValidator.StandardNotation) - self.amount_validator.setDecimals(8) - self.amount_input.setValidator(self.amount_validator) - - # This removes the very ugly OSX highlighting, please leave this in :D - self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0) - self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0) - self.amount_input.textChanged.connect(self.amount_input_changed) - - self.send_button = QPushButton(_("&Send")) - self.send_button.setObjectName("send_button") - self.send_button.setDisabled(True); - self.send_button.clicked.connect(self.send) - - # Creating the receive button - self.switch_button = QPushButton( QIcon(":icons/switchgui.png"),'' ) - self.switch_button.setMaximumWidth(25) - self.switch_button.setFlat(True) - self.switch_button.clicked.connect(expand_callback) - - main_layout = QGridLayout(self) - - main_layout.addWidget(self.balance_label, 0, 0, 1, 3) - main_layout.addWidget(self.switch_button, 0, 3) - - main_layout.addWidget(self.address_input, 1, 0, 1, 4) - main_layout.addWidget(self.amount_input, 2, 0, 1, 2) - main_layout.addWidget(self.send_button, 2, 2, 1, 2) - - self.send_button.setMaximumWidth(125) - - self.history_list = history_widget.HistoryWidget() - self.history_list.setObjectName("history") - self.history_list.hide() - self.history_list.setAlternatingRowColors(True) - - main_layout.addWidget(self.history_list, 3, 0, 1, 4) - - self.receiving = receiving_widget.ReceivingWidget(self) - self.receiving.setObjectName("receiving") - - # Add to the right side - self.receiving_box = QGroupBox(_("Select a receiving address")) - extra_layout = QGridLayout() - - # Checkbox to filter used addresses - hide_used = QCheckBox(_('Hide used addresses')) - hide_used.setChecked(True) - hide_used.stateChanged.connect(self.receiving.toggle_used) - - # Events for receiving addresses - self.receiving.clicked.connect(self.receiving.copy_address) - self.receiving.itemDoubleClicked.connect(self.receiving.edit_label) - self.receiving.itemChanged.connect(self.receiving.update_label) - - - # Label - extra_layout.addWidget( QLabel(_('Selecting an address will copy it to the clipboard.') + '\n' + _('Double clicking the label will allow you to edit it.') ),0,0) - - extra_layout.addWidget(self.receiving, 1,0) - extra_layout.addWidget(hide_used, 2,0) - extra_layout.setColumnMinimumWidth(0,200) - - self.receiving_box.setLayout(extra_layout) - main_layout.addWidget(self.receiving_box,0,4,-1,3) - self.receiving_box.hide() - - # Creating the menu bar - menubar = QMenuBar() - electrum_menu = menubar.addMenu(_("&Electrum")) - - quit_option = electrum_menu.addAction(_("&Close")) - - quit_option.triggered.connect(self.close) - - view_menu = menubar.addMenu(_("&View")) - extra_menu = menubar.addMenu(_("&Extra")) - - backup_wallet = extra_menu.addAction( _("&Create wallet backup")) - backup_wallet.triggered.connect(self.backup_wallet) - - export_csv = extra_menu.addAction( _("&Export transactions to CSV") ) - export_csv.triggered.connect(lambda: csv_transaction(self.actuator.wallet)) - - master_key = extra_menu.addAction( _("Copy master public key to clipboard") ) - master_key.triggered.connect(self.actuator.copy_master_public_key) - - expert_gui = view_menu.addAction(_("&Classic GUI")) - expert_gui.triggered.connect(expand_callback) - 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_toggle = self.config.get("gui_show_receiving",False) - show_receiving.setChecked(show_receiving_toggle) - self.show_receiving = show_receiving - - self.toggle_receiving_layout(show_receiving_toggle) - - - show_history = view_menu.addAction(_("Show History")) - show_history.setCheckable(True) - show_history.toggled.connect(self.show_history) - - help_menu = menubar.addMenu(_("&Help")) - the_website = help_menu.addAction(_("&Website")) - the_website.triggered.connect(self.the_website) - help_menu.addSeparator() - report_bug = help_menu.addAction(_("&Report Bug")) - report_bug.triggered.connect(self.show_report_bug) - show_about = help_menu.addAction(_("&About")) - show_about.triggered.connect(self.show_about) - main_layout.setMenuBar(menubar) - self.main_layout = main_layout - - quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) - quit_shortcut.activated.connect(self.close) - close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self) - close_shortcut.activated.connect(self.close) - - g = self.config.get("winpos-lite",[4, 25, 351, 149]) - self.setGeometry(g[0], g[1], g[2], g[3]) - - show_hist = self.config.get("gui_show_history",False) - show_history.setChecked(show_hist) - self.show_history(show_hist) - - self.setWindowIcon(QIcon(":electrum.png")) - self.setWindowTitle("Electrum") - self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint) - self.layout().setSizeConstraint(QLayout.SetFixedSize) - self.setObjectName("main_window") - self.show() - - - def toggle_theme(self, theme_name): - old_path = QDir.currentPath() - self.actuator.change_theme(theme_name) - # Recompute style globally - qApp.style().unpolish(self) - qApp.style().polish(self) - QDir.setCurrent(old_path) - - def closeEvent(self, event): - g = self.geometry() - self.config.set_key("winpos-lite", [g.left(),g.top(),g.width(),g.height()],True) - self.config.set_key("gui_show_history", self.history_list.isVisible(),True) - self.config.set_key("gui_show_receiving", self.receiving_box.isVisible(),True) - - super(MiniWindow, self).closeEvent(event) - qApp.quit() - - def set_payment_fields(self, dest_address, amount): - self.address_input.setText(dest_address) - self.address_field_changed(dest_address) - self.amount_input.setText(amount) - - def activate(self): - pass - - def deactivate(self): - pass - - def set_quote_currency(self, currency): - """Set and display the fiat currency country.""" - assert currency in self.quote_currencies - self.quote_currencies.remove(currency) - self.quote_currencies.insert(0, currency) - self.refresh_balance() - - def change_quote_currency(self): - self.quote_currencies = \ - self.quote_currencies[1:] + self.quote_currencies[0:1] - self.actuator.set_config_currency(self.quote_currencies[0]) - self.refresh_balance() - - def refresh_balance(self): - if self.btc_balance is None: - # Price has been discovered before wallet has been loaded - # and server connect... so bail. - return - self.set_balances(self.btc_balance) - self.amount_input_changed(self.amount_input.text()) - - def set_balances(self, btc_balance): - """Set the bitcoin balance and update the amount label accordingly.""" - self.btc_balance = btc_balance - quote_text = self.create_quote_text(btc_balance) - if quote_text: - quote_text = "(%s)" % quote_text - btc_balance = "%.2f" % (btc_balance / bitcoin(1)) - self.balance_label.set_balance_text(btc_balance, quote_text) - self.setWindowTitle("Electrum %s - %s BTC" % (electrum_version, btc_balance)) - - def amount_input_changed(self, amount_text): - """Update the number of bitcoins displayed.""" - self.check_button_status() - - try: - amount = D(str(amount_text)) - except decimal.InvalidOperation: - self.balance_label.show_balance() - else: - quote_text = self.create_quote_text(amount * bitcoin(1)) - if quote_text: - self.balance_label.set_amount_text(quote_text) - self.balance_label.show_amount() - else: - self.balance_label.show_balance() - - def create_quote_text(self, btc_balance): - """Return a string copy of the amount fiat currency the - user has in bitcoins.""" - quote_currency = self.quote_currencies[0] - quote_balance = self.exchanger.exchange(btc_balance, quote_currency) - if quote_balance is None: - quote_text = "" - else: - quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)), - quote_currency) - return quote_text - - def send(self): - if self.actuator.send(self.address_input.text(), - self.amount_input.text(), self): - self.address_input.setText("") - self.amount_input.setText("") - - def check_button_status(self): - """Check that the bitcoin address is valid and that something - is entered in the amount before making the send button clickable.""" - try: - value = D(str(self.amount_input.text())) * 10**8 - except decimal.InvalidOperation: - value = None - # self.address_input.property(...) returns a qVariant, not a bool. - # The == is needed to properly invoke a comparison. - if (self.address_input.property("isValid") == True and - value is not None and 0 < value <= self.btc_balance): - self.send_button.setDisabled(False) - else: - self.send_button.setDisabled(True) - - def address_field_changed(self, address): - # label or alias, with address in brackets - match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", - address) - if match2: - address = match2.group(2) - self.address_input.setText(address) - - if is_valid(address): - self.check_button_status() - self.address_input.setProperty("isValid", True) - self.recompute_style(self.address_input) - else: - self.send_button.setDisabled(True) - self.address_input.setProperty("isValid", False) - self.recompute_style(self.address_input) - - if len(address) == 0: - self.address_input.setProperty("isValid", None) - self.recompute_style(self.address_input) - - def recompute_style(self, element): - self.style().unpolish(element) - self.style().polish(element) - - def copy_address(self): - receive_popup = ReceivePopup(self.receive_button) - self.actuator.copy_address(receive_popup) - - def update_completions(self, completions): - self.address_completions.setStringList(completions) - - - def update_history(self, tx_history): - from util import format_satoshis, age - - self.history_list.empty() - - for item in tx_history[-10:]: - tx_hash, conf, is_mine, value, fee, balance, timestamp = item - label = self.actuator.wallet.get_label(tx_hash)[0] - #amount = D(value) / 10**8 - v_str = format_satoshis(value, True) - self.history_list.append(label, v_str, age(timestamp)) - - def acceptbit(self): - self.actuator.acceptbit(self.quote_currencies[0]) - - def the_website(self): - webbrowser.open("http://electrum.org") - - def show_about(self): - QMessageBox.about(self, "Electrum", - _("Version")+" %s" % (electrum_version) + "\n\n" + _("Electrum's focus is speed, with low resource usage and simplifying Bitcoin. You do not need to perform regular backups, because your wallet can be recovered from a secret phrase that you can memorize or write on paper. Startup times are instant because it operates in conjunction with high-performance servers that handle the most complicated parts of the Bitcoin system.")) - - def show_report_bug(self): - QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"), - _("Please report any bugs as issues on github:")+" <a href=\"https://github.com/spesmilo/electrum/issues\">https://github.com/spesmilo/electrum/issues</a>") - - def toggle_receiving_layout(self, toggle_state): - if toggle_state: - self.receiving_box.show() - else: - self.receiving_box.hide() - - def show_history(self, toggle_state): - if toggle_state: - self.main_layout.setRowMinimumHeight(3,200) - self.history_list.show() - else: - self.main_layout.setRowMinimumHeight(3,0) - self.history_list.hide() - - def backup_wallet(self): - try: - folderName = QFileDialog.getExistingDirectory(QWidget(), _('Select folder to save a copy of your wallet to'), os.path.expanduser('~/')) - if folderName: - sourceFile = util.user_dir() + '/electrum.dat' - shutil.copy2(sourceFile, str(folderName)) - QMessageBox.information(None,"Wallet backup created", _("A copy of your wallet file was created in")+" '%s'" % str(folderName)) - except (IOError, os.error), reason: - QMessageBox.critical(None,"Unable to create backup", _("Electrum was unable to copy your wallet file to the specified location.")+"\n" + str(reason)) - - - - -class BalanceLabel(QLabel): - - SHOW_CONNECTING = 1 - SHOW_BALANCE = 2 - SHOW_AMOUNT = 3 - - 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 = "" - - def mousePressEvent(self, event): - """Change the fiat currency selection if window background is clicked.""" - if self.state != self.SHOW_CONNECTING: - self.change_quote_currency() - - def set_balance_text(self, btc_balance, quote_text): - """Set the amount of bitcoins in the gui.""" - if self.state == self.SHOW_CONNECTING: - self.state = self.SHOW_BALANCE - self.balance_text = "<span style='font-size: 18pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text) - if self.state == self.SHOW_BALANCE: - self.setText(self.balance_text) - - def set_amount_text(self, quote_text): - self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text - if self.state == self.SHOW_AMOUNT: - self.setText(self.amount_text) - - def show_balance(self): - if self.state == self.SHOW_AMOUNT: - self.state = self.SHOW_BALANCE - self.setText(self.balance_text) - - def show_amount(self): - if self.state == self.SHOW_BALANCE: - self.state = self.SHOW_AMOUNT - self.setText(self.amount_text) - -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 - -class PasswordDialog(QDialog): - - def __init__(self, parent): - super(QDialog, self).__init__(parent) - - self.setModal(True) - - self.password_input = QLineEdit() - self.password_input.setEchoMode(QLineEdit.Password) - - main_layout = QVBoxLayout(self) - message = _('Please enter your password') - main_layout.addWidget(QLabel(message)) - - grid = QGridLayout() - grid.setSpacing(8) - grid.addWidget(QLabel(_('Password')), 1, 0) - grid.addWidget(self.password_input, 1, 1) - main_layout.addLayout(grid) - - main_layout.addLayout(ok_cancel_buttons(self)) - self.setLayout(main_layout) - - def run(self): - if not self.exec_(): - return - return unicode(self.password_input.text()) - -class ReceivePopup(QDialog): - - def leaveEvent(self, event): - self.close() - - def setup(self, address): - label = QLabel(_("Copied your Bitcoin 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 - " + _("Receive Bitcoin payment")) - self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint| - Qt.MSWindowsFixedSizeDialogHint) - self.layout().setSizeConstraint(QLayout.SetFixedSize) - #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised) - #self.setAlignment(Qt.AlignCenter) - - def popup(self): - parent = self.parent() - top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft()) - self.move(top_left_pos) - center_mouse_pos = self.mapToGlobal(self.rect().center()) - QCursor.setPos(center_mouse_pos) - self.show() - -class MiniActuator: - """Initialize the definitions relating to themes and - sending/receiving bitcoins.""" - - - def __init__(self, wallet): - """Retrieve the gui theme used in previous session.""" - self.wallet = wallet - self.theme_name = self.wallet.config.get('litegui_theme','Cleanlook') - self.themes = load_theme_paths() - - def load_theme(self): - """Load theme retrieved from wallet file.""" - try: - theme_prefix, theme_path = self.themes[self.theme_name] - except KeyError: - util.print_error("Theme not found!", self.theme_name) - return - QDir.setCurrent(os.path.join(theme_prefix, theme_path)) - with open(rsrc("style.css")) as style_file: - qApp.setStyleSheet(style_file.read()) - - def theme_names(self): - """Sort themes.""" - return sorted(self.themes.keys()) - - def selected_theme(self): - """Select theme.""" - return self.theme_name - - def change_theme(self, theme_name): - """Change theme.""" - self.theme_name = theme_name - self.wallet.config.set_key('litegui_theme',theme_name) - self.load_theme() - - def set_configured_currency(self, set_quote_currency): - """Set the inital fiat currency conversion country (USD/EUR/GBP) in - the GUI to what it was set to in the wallet.""" - currency = self.wallet.config.get('conversion_currency') - # currency can be none when Electrum is used for the first - # time and no setting has been created yet. - if currency is not None: - set_quote_currency(currency) - - def set_config_currency(self, conversion_currency): - """Change the wallet fiat currency country.""" - self.wallet.config.set_key('conversion_currency',conversion_currency,True) - - def copy_address(self, receive_popup): - """Copy the wallet addresses into the client.""" - addrs = [addr for addr in self.wallet.addresses(True) - if not self.wallet.is_change(addr)] - # Select most recent addresses from gap limit - addrs = addrs[-self.wallet.gap_limit:] - copied_address = random.choice(addrs) - qApp.clipboard().setText(copied_address) - receive_popup.setup(copied_address) - receive_popup.popup() - - def waiting_dialog(self, f): - s = Timer() - s.start() - w = QDialog() - w.resize(200, 70) - w.setWindowTitle('Electrum') - l = QLabel('Sending transaction, please wait.') - vbox = QVBoxLayout() - vbox.addWidget(l) - w.setLayout(vbox) - w.show() - def ff(): - s = f() - if s: l.setText(s) - else: w.close() - w.connect(s, QtCore.SIGNAL('timersignal'), ff) - w.exec_() - w.destroy() - - - def send(self, address, amount, parent_window): - """Send bitcoins to the target address.""" - dest_address = self.fetch_destination(address) - - if dest_address is None or not is_valid(dest_address): - QMessageBox.warning(parent_window, _('Error'), - _('Invalid Bitcoin Address') + ':\n' + address, _('OK')) - return False - - convert_amount = lambda amount: \ - int(D(unicode(amount)) * bitcoin(1)) - amount = convert_amount(amount) - - if self.wallet.use_encryption: - password_dialog = PasswordDialog(parent_window) - password = password_dialog.run() - if not password: - return - else: - password = None - - fee = 0 - # 0.1 BTC = 10000000 - if amount < bitcoin(1) / 10: - # 0.001 BTC - fee = bitcoin(1) / 1000 - - try: - tx = self.wallet.mktx([(dest_address, amount)], password, fee) - except BaseException as error: - QMessageBox.warning(parent_window, _('Error'), str(error), _('OK')) - return False - - h = self.wallet.send_tx(tx) - - self.waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Sending transaction, please wait...")) - - status, message = self.wallet.receive_tx(h) - - if not status: - import tempfile - dumpf = tempfile.NamedTemporaryFile(delete=False) - dumpf.write(tx) - dumpf.close() - print "Dumped error tx to", dumpf.name - QMessageBox.warning(parent_window, _('Error'), message, _('OK')) - return False - - TransactionWindow(message, self) -# QMessageBox.information(parent_window, '', -# _('Your transaction has been sent.') + '\n' + message, _('OK')) - return True - - def fetch_destination(self, address): - recipient = unicode(address).strip() - - # alias - match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$", - recipient) - - # label or alias, with address in brackets - match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>", - recipient) - - if match1: - dest_address = \ - self.wallet.get_alias(recipient, True, - self.show_message, self.question) - return dest_address - elif match2: - return match2.group(2) - else: - return recipient - - - def copy_master_public_key(self): - master_pubkey = self.wallet.master_public_key - qApp.clipboard().setText(master_pubkey) - QMessageBox.information(None, _("Copy successful"), _("Your master public key has been copied to your clipboard.")) - - - def acceptbit(self, currency): - master_pubkey = self.wallet.master_public_key - url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency) - webbrowser.open(url) - - def show_seed_dialog(self): - gui_qt.ElectrumWindow.show_seed_dialog(self.wallet) - -class MiniDriver(QObject): - - INITIALIZING = 0 - CONNECTING = 1 - SYNCHRONIZING = 2 - READY = 3 - - def __init__(self, wallet, window): - super(QObject, self).__init__() - - self.wallet = wallet - self.window = window - - self.wallet.interface.register_callback('updated',self.update_callback) - self.wallet.interface.register_callback('connected', self.update_callback) - self.wallet.interface.register_callback('disconnected', self.update_callback) - - self.state = None - - self.initializing() - self.connect(self, SIGNAL("updatesignal()"), self.update) - self.update_callback() - - # This is a hack to workaround that Qt does not like changing the - # window properties from this other thread before the runloop has - # been called from. - def update_callback(self): - self.emit(SIGNAL("updatesignal()")) - - def update(self): - if not self.wallet.interface: - self.initializing() - elif not self.wallet.interface.is_connected: - self.connecting() - elif not self.wallet.up_to_date: - self.synchronizing() - else: - self.ready() - - if self.wallet.up_to_date: - self.update_balance() - self.update_completions() - self.update_history() - - def initializing(self): - if self.state == self.INITIALIZING: - return - self.state = self.INITIALIZING - self.window.deactivate() - - def connecting(self): - if self.state == self.CONNECTING: - return - self.state = self.CONNECTING - self.window.deactivate() - - def synchronizing(self): - if self.state == self.SYNCHRONIZING: - return - self.state = self.SYNCHRONIZING - self.window.deactivate() - - def ready(self): - if self.state == self.READY: - return - self.state = self.READY - self.window.activate() - - def update_balance(self): - conf_balance, unconf_balance = self.wallet.get_balance() - balance = D(conf_balance + unconf_balance) - self.window.set_balances(balance) - - def update_completions(self): - completions = [] - for addr, label in self.wallet.labels.items(): - if addr in self.wallet.addressbook: - completions.append("%s <%s>" % (label, addr)) - completions = completions + self.wallet.aliases.keys() - self.window.update_completions(completions) - - def update_history(self): - tx_history = self.wallet.get_tx_history() - self.window.update_history(tx_history) - - -if __name__ == "__main__": - app = QApplication(sys.argv) - with open(rsrc("style.css")) as style_file: - app.setStyleSheet(style_file.read()) - mini = MiniWindow() - sys.exit(app.exec_()) - diff --git a/lib/gui_qt.py b/lib/gui_qt.py @@ -1,2535 +0,0 @@ -#!/usr/bin/env python -# -# Electrum - lightweight Bitcoin client -# Copyright (C) 2012 thomasv@gitorious -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -import sys, time, datetime, re -from i18n import _ -from util import print_error -import os.path, json, util, ast - -try: - import PyQt4 -except: - sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") - -from PyQt4.QtGui import * -from PyQt4.QtCore import * -import PyQt4.QtCore as QtCore -import PyQt4.QtGui as QtGui -from interface import DEFAULT_SERVERS - -try: - import icons_rc -except: - sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o lib/icons_rc.py'") - -from wallet import format_satoshis -from bitcoin import Transaction, is_valid -import bmp, mnemonic, pyqrnative, qrscanner -import exchange_rate - -from decimal import Decimal - -import platform -import httplib -import socket -import webbrowser -import csv - -if platform.system() == 'Windows': - MONOSPACE_FONT = 'Lucida Console' -elif platform.system() == 'Darwin': - MONOSPACE_FONT = 'Monaco' -else: - MONOSPACE_FONT = 'monospace' - -ALIAS_REGEXP = '^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$' - -from version import ELECTRUM_VERSION -import re - -class UpdateLabel(QtGui.QLabel): - def __init__(self, config, parent=None): - QtGui.QLabel.__init__(self, parent) - self.new_version = False - - try: - con = httplib.HTTPConnection('electrum.org', 80, timeout=5) - con.request("GET", "/version") - res = con.getresponse() - except socket.error as msg: - print_error("Could not retrieve version information") - return - - if res.status == 200: - self.latest_version = res.read() - self.latest_version = self.latest_version.replace("\n","") - if(re.match('^\d+(\.\d+)*$', self.latest_version)): - self.config = config - self.current_version = ELECTRUM_VERSION - if(self.compare_versions(self.latest_version, self.current_version) == 1): - latest_seen = self.config.get("last_seen_version",ELECTRUM_VERSION) - if(self.compare_versions(self.latest_version, latest_seen) == 1): - self.new_version = True - self.setText(_("New version available") + ": " + self.latest_version) - - - def compare_versions(self, version1, version2): - def normalize(v): - return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] - return cmp(normalize(version1), normalize(version2)) - - def ignore_this_version(self): - self.setText("") - self.config.set_key("last_seen_version", self.latest_version, True) - QMessageBox.information(self, _("Preference saved"), _("Notifications about this update will not be shown again.")) - self.dialog.done(0) - - def ignore_all_version(self): - self.setText("") - self.config.set_key("last_seen_version", "9.9.9", True) - QMessageBox.information(self, _("Preference saved"), _("No more notifications about version updates will be shown.")) - self.dialog.done(0) - - def open_website(self): - webbrowser.open("http://electrum.org/download.html") - self.dialog.done(0) - - 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 numbify(entry, is_int = False): - text = unicode(entry.text()).strip() - pos = entry.cursorPosition() - chars = '0123456789' - if not is_int: chars +='.' - s = ''.join([i for i in text if i in chars]) - if not is_int: - if '.' in s: - p = s.find('.') - s = s.replace('.','') - s = s[:p] + '.' + s[p:p+8] - try: - amount = int( Decimal(s) * 100000000 ) - except: - amount = None - else: - try: - amount = int( s ) - except: - amount = None - entry.setText(s) - entry.setCursorPosition(pos) - return amount - - -class Timer(QtCore.QThread): - def run(self): - while True: - self.emit(QtCore.SIGNAL('timersignal')) - time.sleep(0.5) - -class HelpButton(QPushButton): - def __init__(self, text): - QPushButton.__init__(self, '?') - self.setFocusPolicy(Qt.NoFocus) - self.setFixedWidth(20) - self.clicked.connect(lambda: QMessageBox.information(self, 'Help', text, 'OK') ) - - -class EnterButton(QPushButton): - def __init__(self, text, func): - QPushButton.__init__(self, text) - self.func = func - self.clicked.connect(func) - - def keyPressEvent(self, e): - if e.key() == QtCore.Qt.Key_Return: - apply(self.func,()) - -class MyTreeWidget(QTreeWidget): - def __init__(self, parent): - QTreeWidget.__init__(self, parent) - def ddfr(item): - if not item: return - for i in range(0,self.viewport().height()/5): - if self.itemAt(QPoint(0,i*5)) == item: - break - else: - return - for j in range(0,30): - if self.itemAt(QPoint(0,i*5 + j)) != item: - break - self.emit(SIGNAL('customContextMenuRequested(const QPoint&)'), QPoint(50, i*5 + j - 1)) - - self.connect(self, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), ddfr) - - - - -class StatusBarButton(QPushButton): - def __init__(self, icon, tooltip, func): - QPushButton.__init__(self, icon, '') - self.setToolTip(tooltip) - self.setFlat(True) - self.setMaximumWidth(25) - self.clicked.connect(func) - self.func = func - - def keyPressEvent(self, e): - if e.key() == QtCore.Qt.Key_Return: - apply(self.func,()) - - -class QRCodeWidget(QWidget): - - def __init__(self, data = None, size=4): - QWidget.__init__(self) - self.setMinimumSize(210, 210) - self.addr = None - self.qr = None - self.size = size - if data: - self.set_addr(data) - self.update_qr() - - def set_addr(self, addr): - if self.addr != addr: - self.addr = addr - self.qr = None - self.update() - - def update_qr(self): - if self.addr and not self.qr: - self.qr = pyqrnative.QRCode(self.size, pyqrnative.QRErrorCorrectLevel.L) - self.qr.addData(self.addr) - self.qr.make() - self.update() - - def paintEvent(self, e): - - if not self.addr: - return - - black = QColor(0, 0, 0, 255) - white = QColor(255, 255, 255, 255) - - if not self.qr: - qp = QtGui.QPainter() - qp.begin(self) - qp.setBrush(white) - qp.setPen(white) - qp.drawRect(0, 0, 198, 198) - qp.end() - return - - k = self.qr.getModuleCount() - qp = QtGui.QPainter() - qp.begin(self) - r = qp.viewport() - boxsize = min(r.width(), r.height())*0.8/k - size = k*boxsize - left = (r.width() - size)/2 - top = (r.height() - size)/2 - - for r in range(k): - for c in range(k): - if self.qr.isDark(r, c): - qp.setBrush(black) - qp.setPen(black) - else: - qp.setBrush(white) - qp.setPen(white) - qp.drawRect(left+c*boxsize, top+r*boxsize, boxsize, boxsize) - qp.end() - - - -class QR_Window(QWidget): - - def __init__(self, exchanger): - QWidget.__init__(self) - self.exchanger = exchanger - self.setWindowTitle('Electrum - '+_('Invoice')) - self.setMinimumSize(800, 250) - self.address = '' - self.labe = '' - 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 set_content(self, addr, label, amount, currency): - self.address = addr - address_text = "<span style='font-size: 18pt'>%s</span>" % addr if addr else "" - self.address_label.setText(address_text) - - if currency == 'BTC': currency = None - amount_text = '' - if amount: - if currency: - self.amount = Decimal(amount) / self.exchanger.exchange(1, currency) if currency else amount - else: - self.amount = Decimal(amount) - self.amount = self.amount.quantize(Decimal('1.0000')) - - if currency: - amount_text += "<span style='font-size: 18pt'>%s %s</span><br/>" % (amount, currency) - amount_text += "<span style='font-size: 21pt'>%s</span> <span style='font-size: 16pt'>BTC</span> " % str(self.amount) - self.amount_label.setText(amount_text) - - self.label = label - label_text = "<span style='font-size: 21pt'>%s</span>" % label if label else "" - self.label_label.setText(label_text) - - msg = 'bitcoin:'+self.address - if self.amount is not None: - msg += '?amount=%s'%(str( self.amount)) - if self.label is not None: - msg += '&label=%s'%(self.label) - elif self.label is not None: - msg += '?label=%s'%(self.label) - - self.qrw.set_addr( msg ) - - - - -def waiting_dialog(f): - - s = Timer() - s.start() - w = QDialog() - w.resize(200, 70) - w.setWindowTitle('Electrum') - l = QLabel('') - vbox = QVBoxLayout() - vbox.addWidget(l) - w.setLayout(vbox) - w.show() - def ff(): - s = f() - if s: l.setText(s) - else: w.close() - w.connect(s, QtCore.SIGNAL('timersignal'), ff) - w.exec_() - w.destroy() - - -def ok_cancel_buttons(dialog): - hbox = QHBoxLayout() - hbox.addStretch(1) - b = QPushButton("OK") - hbox.addWidget(b) - b.clicked.connect(dialog.accept) - b = QPushButton("Cancel") - hbox.addWidget(b) - b.clicked.connect(dialog.reject) - return hbox - - -default_column_widths = { "history":[40,140,350,140], "contacts":[350,330], - "receive":[[310],[310,200,130,130],[310,200,130,130]] } - -class ElectrumWindow(QMainWindow): - - def __init__(self, wallet, config): - QMainWindow.__init__(self) - self.lite = None - self.wallet = wallet - self.config = config - self.wallet.interface.register_callback('updated', self.update_callback) - self.wallet.interface.register_callback('banner', lambda: self.emit(QtCore.SIGNAL('banner_signal')) ) - self.wallet.interface.register_callback('disconnected', self.update_callback) - self.wallet.interface.register_callback('disconnecting', self.update_callback) - - self.receive_tab_mode = config.get('qt_receive_tab_mode', 0) - self.merchant_name = config.get('merchant_name', 'Invoice') - - self.qr_window = None - self.funds_error = False - self.completions = QStringListModel() - - self.tabs = tabs = QTabWidget(self) - self.column_widths = self.config.get("column-widths", default_column_widths ) - tabs.addTab(self.create_history_tab(), _('History') ) - tabs.addTab(self.create_send_tab(), _('Send') ) - tabs.addTab(self.create_receive_tab(), _('Receive') ) - tabs.addTab(self.create_contacts_tab(), _('Contacts') ) - tabs.addTab(self.create_console_tab(), _('Console') ) - tabs.setMinimumSize(600, 400) - tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - self.setCentralWidget(tabs) - self.create_status_bar() - - g = self.config.get("winpos-qt",[100, 100, 840, 400]) - self.setGeometry(g[0], g[1], g[2], g[3]) - title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.config.path - if not self.wallet.seed: title += ' [%s]' % (_('seedless')) - self.setWindowTitle( title ) - - QShortcut(QKeySequence("Ctrl+W"), self, self.close) - QShortcut(QKeySequence("Ctrl+Q"), self, self.close) - QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() )) - QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() )) - - self.connect(self, QtCore.SIGNAL('updatesignal'), self.update_wallet) - self.connect(self, QtCore.SIGNAL('banner_signal'), lambda: self.console.showMessage(self.wallet.banner) ) - self.history_list.setFocus(True) - - self.exchanger = exchange_rate.Exchanger(self) - self.toggle_QR_window(self.receive_tab_mode == 2) - self.connect(self, SIGNAL("refresh_balance()"), self.update_wallet) - - # dark magic fix by flatfly; https://bitcointalk.org/index.php?topic=73651.msg959913#msg959913 - if platform.system() == 'Windows': - n = 3 if self.wallet.seed else 2 - tabs.setCurrentIndex (n) - tabs.setCurrentIndex (0) - - # set initial message - self.console.showMessage(self.wallet.banner) - - def close(self): - QMainWindow.close(self) - if self.qr_window: - self.qr_window.close() - self.qr_window = None - - def connect_slots(self, sender): - self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions) - self.previous_payto_e='' - - def timer_actions(self): - if self.qr_window: - self.qr_window.qrw.update_qr() - - if self.payto_e.hasFocus(): - return - r = unicode( self.payto_e.text() ) - if r != self.previous_payto_e: - self.previous_payto_e = r - r = r.strip() - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): - try: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - except: - return - if to_address: - s = r + ' <' + to_address + '>' - self.payto_e.setText(s) - - - def update_callback(self): - self.emit(QtCore.SIGNAL('updatesignal')) - - def update_wallet(self): - if self.wallet.interface and self.wallet.interface.is_connected: - if not self.wallet.up_to_date: - text = _("Synchronizing...") - icon = QIcon(":icons/status_waiting.png") - else: - c, u = self.wallet.get_balance() - text = _( "Balance" ) + ": %s "%( format_satoshis(c,False,self.wallet.num_zeros) ) - if u: text += "[%s unconfirmed]"%( format_satoshis(u,True,self.wallet.num_zeros).strip() ) - text += self.create_quote_text(Decimal(c+u)/100000000) - icon = QIcon(":icons/status_connected.png") - else: - text = _("Not connected") - icon = QIcon(":icons/status_disconnected.png") - - self.status_text = text - self.statusBar().showMessage(text) - self.status_button.setIcon( icon ) - - if self.wallet.up_to_date or not self.wallet.interface.is_connected: - self.update_history_tab() - self.update_receive_tab() - self.update_contacts_tab() - self.update_completions() - - - def create_quote_text(self, btc_balance): - quote_currency = self.config.get("currency", "None") - quote_balance = self.exchanger.exchange(btc_balance, quote_currency) - if quote_balance is None: - quote_text = "" - else: - quote_text = " (%.2f %s)" % (quote_balance, quote_currency) - return quote_text - - def create_history_tab(self): - self.history_list = l = MyTreeWidget(self) - l.setColumnCount(5) - for i,width in enumerate(self.column_widths['history']): - l.setColumnWidth(i, width) - l.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] ) - self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked) - self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed) - - l.setContextMenuPolicy(Qt.CustomContextMenu) - l.customContextMenuRequested.connect(self.create_history_menu) - return l - - - def create_history_menu(self, position): - self.history_list.selectedIndexes() - item = self.history_list.currentItem() - if not item: return - tx_hash = str(item.data(0, Qt.UserRole).toString()) - if not tx_hash: return - menu = QMenu() - #menu.addAction(_("Copy ID to Clipboard"), lambda: self.app.clipboard().setText(tx_hash)) - menu.addAction(_("Details"), lambda: self.show_tx_details(self.wallet.transactions.get(tx_hash))) - menu.addAction(_("Edit description"), lambda: self.tx_label_clicked(item,2)) - menu.exec_(self.contacts_list.viewport().mapToGlobal(position)) - - - def show_tx_details(self, tx): - dialog = QDialog(None) - dialog.setModal(1) - dialog.setWindowTitle(_("Transaction Details")) - vbox = QVBoxLayout() - dialog.setLayout(vbox) - dialog.setMinimumSize(600,300) - - tx_hash = tx.hash() - if tx_hash in self.wallet.transactions.keys(): - is_mine, v, fee = self.wallet.get_tx_value(tx) - conf, timestamp = self.wallet.verifier.get_confirmations(tx_hash) - if timestamp: - time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] - else: - time_str = 'pending' - else: - is_mine = False - - vbox.addWidget(QLabel("Transaction ID:")) - e = QLineEdit(tx_hash) - e.setReadOnly(True) - vbox.addWidget(e) - - vbox.addWidget(QLabel("Date: %s"%time_str)) - vbox.addWidget(QLabel("Status: %d confirmations"%conf)) - if is_mine: - if fee: - vbox.addWidget(QLabel("Amount sent: %s"% format_satoshis(v-fee, False))) - vbox.addWidget(QLabel("Transaction fee: %s"% format_satoshis(fee, False))) - else: - vbox.addWidget(QLabel("Amount sent: %s"% format_satoshis(v, False))) - vbox.addWidget(QLabel("Transaction fee: unknown")) - else: - vbox.addWidget(QLabel("Amount received: %s"% format_satoshis(v, False))) - - vbox.addWidget( self.generate_transaction_information_widget(tx) ) - - ok_button = QPushButton(_("Close")) - ok_button.setDefault(True) - ok_button.clicked.connect(dialog.accept) - - hbox = QHBoxLayout() - hbox.addStretch(1) - hbox.addWidget(ok_button) - vbox.addLayout(hbox) - dialog.exec_() - - def tx_label_clicked(self, item, column): - if column==2 and item.isSelected(): - self.is_edit=True - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - self.history_list.editItem( item, column ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - self.is_edit=False - - def tx_label_changed(self, item, column): - if self.is_edit: - return - self.is_edit=True - tx_hash = str(item.data(0, Qt.UserRole).toString()) - tx = self.wallet.transactions.get(tx_hash) - s = self.wallet.labels.get(tx_hash) - text = unicode( item.text(2) ) - if text: - self.wallet.labels[tx_hash] = text - item.setForeground(2, QBrush(QColor('black'))) - else: - if s: self.wallet.labels.pop(tx_hash) - text = self.wallet.get_default_label(tx_hash) - item.setText(2, text) - item.setForeground(2, QBrush(QColor('gray'))) - self.is_edit=False - - - def edit_label(self, is_recv): - l = self.receive_list if is_recv else self.contacts_list - c = 2 if is_recv else 1 - item = l.currentItem() - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - l.editItem( item, c ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - - def edit_amount(self): - l = self.receive_list - item = l.currentItem() - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - l.editItem( item, 3 ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - - - def address_label_clicked(self, item, column, l, column_addr, column_label): - if column == column_label and item.isSelected(): - addr = unicode( item.text(column_addr) ) - label = unicode( item.text(column_label) ) - if label in self.wallet.aliases.keys(): - return - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - l.editItem( item, column ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - - - def address_label_changed(self, item, column, l, column_addr, column_label): - - if column == column_label: - addr = unicode( item.text(column_addr) ) - text = unicode( item.text(column_label) ) - changed = False - - if text: - if text not in self.wallet.aliases.keys(): - old_addr = self.wallet.labels.get(text) - if old_addr != addr: - self.wallet.labels[addr] = text - changed = True - else: - print_error("Error: This is one of your aliases") - label = self.wallet.labels.get(addr,'') - item.setText(column_label, QString(label)) - else: - s = self.wallet.labels.get(addr) - if s: - self.wallet.labels.pop(addr) - changed = True - - if changed: - self.update_history_tab() - self.update_completions() - - self.recv_changed(item) - - if column == 2: - address = str( item.text(column_addr) ) - text = str( item.text(3) ) - try: - index = self.wallet.addresses.index(address) - except: - return - - text = text.strip().upper() - m = re.match('^(\d+(|\.\d*))\s*(|BTC|EUR|USD|GBP|CNY|JPY|RUB|BRL)$', text) - if m: - amount = m.group(1) - currency = m.group(3) - if not currency: - currency = 'BTC' - else: - currency = currency.upper() - self.wallet.requested_amounts[address] = (amount, currency) - - label = self.wallet.labels.get(address) - if label is None: - label = self.merchant_name + ' - %04d'%(index+1) - self.wallet.labels[address] = label - - if self.qr_window: - self.qr_window.set_content( address, label, amount, currency ) - - else: - item.setText(3,'') - if address in self.wallet.requested_amounts: - self.wallet.requested_amounts.pop(address) - - self.update_receive_item(self.receive_list.currentItem()) - - - def recv_changed(self, a): - "current item changed" - if a is not None and self.qr_window and self.qr_window.isVisible(): - address = str(a.text(1)) - label = self.wallet.labels.get(address) - try: - amount, currency = self.wallet.requested_amounts.get(address, (None, None)) - except: - amount, currency = None, None - self.qr_window.set_content( address, label, amount, currency ) - - - def update_history_tab(self): - - self.history_list.clear() - for item in self.wallet.get_tx_history(): - tx_hash, conf, is_mine, value, fee, balance, timestamp = item - if conf: - try: - time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] - except: - time_str = "unknown" - if conf == -1: - icon = None - if conf == 0: - icon = QIcon(":icons/unconfirmed.png") - elif conf < 6: - icon = QIcon(":icons/clock%d.png"%conf) - else: - icon = QIcon(":icons/confirmed.png") - else: - time_str = 'pending' - icon = QIcon(":icons/unconfirmed.png") - - if value is not None: - v_str = format_satoshis(value, True, self.wallet.num_zeros) - else: - v_str = '--' - - balance_str = format_satoshis(balance, False, self.wallet.num_zeros) - - if tx_hash: - label, is_default_label = self.wallet.get_label(tx_hash) - else: - label = _('Pruned transaction outputs') - is_default_label = False - - item = QTreeWidgetItem( [ '', time_str, label, v_str, balance_str] ) - item.setFont(2, QFont(MONOSPACE_FONT)) - item.setFont(3, QFont(MONOSPACE_FONT)) - item.setFont(4, QFont(MONOSPACE_FONT)) - if value < 0: - item.setForeground(3, QBrush(QColor("#BC1E1E"))) - if tx_hash: - item.setData(0, Qt.UserRole, tx_hash) - item.setToolTip(0, "%d %s\nTxId:%s" % (conf, _('Confirmations'), tx_hash) ) - if is_default_label: - item.setForeground(2, QBrush(QColor('grey'))) - - item.setIcon(0, icon) - self.history_list.insertTopLevelItem(0,item) - - - self.history_list.setCurrentItem(self.history_list.topLevelItem(0)) - - - def create_send_tab(self): - w = QWidget() - - grid = QGridLayout() - grid.setSpacing(8) - grid.setColumnMinimumWidth(3,300) - grid.setColumnStretch(5,1) - - self.payto_e = QLineEdit() - grid.addWidget(QLabel(_('Pay to')), 1, 0) - grid.addWidget(self.payto_e, 1, 1, 1, 3) - - def fill_from_qr(): - qrcode = qrscanner.scan_qr() - if 'address' in qrcode: - self.payto_e.setText(qrcode['address']) - if 'amount' in qrcode: - self.amount_e.setText(str(qrcode['amount'])) - if 'label' in qrcode: - self.message_e.setText(qrcode['label']) - if 'message' in qrcode: - self.message_e.setText("%s (%s)" % (self.message_e.text(), qrcode['message'])) - - - if qrscanner.is_available(): - b = QPushButton(_("Scan QR code")) - b.clicked.connect(fill_from_qr) - grid.addWidget(b, 1, 5) - - grid.addWidget(HelpButton(_('Recipient of the funds.') + '\n\n' + _('You may enter a Bitcoin address, a label from your list of contacts (a list of completions will be proposed), or an alias (email-like address that forwards to a Bitcoin address)')), 1, 4) - - completer = QCompleter() - completer.setCaseSensitivity(False) - self.payto_e.setCompleter(completer) - completer.setModel(self.completions) - - self.message_e = QLineEdit() - grid.addWidget(QLabel(_('Description')), 2, 0) - grid.addWidget(self.message_e, 2, 1, 1, 3) - grid.addWidget(HelpButton(_('Description of the transaction (not mandatory).') + '\n\n' + _('The description is not sent to the recipient of the funds. It is stored in your wallet file, and displayed in the \'History\' tab.')), 2, 4) - - self.amount_e = QLineEdit() - grid.addWidget(QLabel(_('Amount')), 3, 0) - grid.addWidget(self.amount_e, 3, 1, 1, 2) - grid.addWidget(HelpButton( - _('Amount to be sent.') + '\n\n' \ - + _('The amount will be displayed in red if you do not have enough funds in your wallet. Note that if you have frozen some of your addresses, the available funds will be lower than your total balance.')), 3, 3) - - self.fee_e = QLineEdit() - grid.addWidget(QLabel(_('Fee')), 4, 0) - grid.addWidget(self.fee_e, 4, 1, 1, 2) - grid.addWidget(HelpButton( - _('Bitcoin transactions are in general not free. A transaction fee is paid by the sender of the funds.') + '\n\n'\ - + _('The amount of fee can be decided freely by the sender. However, transactions with low fees take more time to be processed.') + '\n\n'\ - + _('A suggested fee is automatically added to this field. You may override it. The suggested fee increases with the size of the transaction.')), 4, 3) - b = '' - if self.wallet.seed: - b = EnterButton(_("Send"), self.do_send) - else: - b = EnterButton(_("Create unsigned transaction"), self.do_send) - grid.addWidget(b, 6, 1) - - b = EnterButton(_("Clear"),self.do_clear) - grid.addWidget(b, 6, 2) - - self.payto_sig = QLabel('') - grid.addWidget(self.payto_sig, 7, 0, 1, 4) - - QShortcut(QKeySequence("Up"), w, w.focusPreviousChild) - QShortcut(QKeySequence("Down"), w, w.focusNextChild) - w.setLayout(grid) - - w2 = QWidget() - vbox = QVBoxLayout() - vbox.addWidget(w) - vbox.addStretch(1) - w2.setLayout(vbox) - - def entry_changed( is_fee ): - self.funds_error = False - amount = numbify(self.amount_e) - fee = numbify(self.fee_e) - if not is_fee: fee = None - if amount is None: - return - inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) - if not is_fee: - self.fee_e.setText( str( Decimal( fee ) / 100000000 ) ) - if inputs: - palette = QPalette() - palette.setColor(self.amount_e.foregroundRole(), QColor('black')) - text = self.status_text - else: - palette = QPalette() - palette.setColor(self.amount_e.foregroundRole(), QColor('red')) - self.funds_error = True - text = _( "Not enough funds" ) - - self.statusBar().showMessage(text) - self.amount_e.setPalette(palette) - self.fee_e.setPalette(palette) - - self.amount_e.textChanged.connect(lambda: entry_changed(False) ) - self.fee_e.textChanged.connect(lambda: entry_changed(True) ) - - return w2 - - - def update_completions(self): - l = [] - for addr,label in self.wallet.labels.items(): - if addr in self.wallet.addressbook: - l.append( label + ' <' + addr + '>') - l = l + self.wallet.aliases.keys() - - self.completions.setStringList(l) - - - - def do_send(self): - - label = unicode( self.message_e.text() ) - r = unicode( self.payto_e.text() ) - r = r.strip() - - # alias - m1 = re.match(ALIAS_REGEXP, r) - # label or alias, with address in brackets - m2 = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) - - if m1: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - if not to_address: - return - elif m2: - to_address = m2.group(2) - else: - to_address = r - - if not is_valid(to_address): - QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK')) - return - - try: - amount = int( Decimal( unicode( self.amount_e.text())) * 100000000 ) - except: - QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK')) - return - try: - fee = int( Decimal( unicode( self.fee_e.text())) * 100000000 ) - except: - QMessageBox.warning(self, _('Error'), _('Invalid Fee'), _('OK')) - return - - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - tx = self.wallet.mktx( [(to_address, amount)], password, fee) - except BaseException, e: - self.show_message(str(e)) - return - - if label: - self.wallet.labels[tx.hash()] = label - - if tx.is_complete: - h = self.wallet.send_tx(tx) - waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Please wait...")) - status, msg = self.wallet.receive_tx( h ) - if status: - QMessageBox.information(self, '', _('Payment sent.')+'\n'+msg, _('OK')) - self.do_clear() - self.update_contacts_tab() - else: - QMessageBox.warning(self, _('Error'), msg, _('OK')) - else: - filename = 'unsigned_tx_%s' % (time.mktime(time.gmtime())) - try: - fileName = QFileDialog.getSaveFileName(QWidget(), _("Select a transaction filename"), os.path.expanduser('~/%s' % (filename))) - with open(fileName,'w') as f: - f.write(json.dumps(tx.as_dict(),indent=4) + '\n') - QMessageBox.information(self, _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK')) - except: - QMessageBox.warning(self, _('Error'), _('Could not write transaction to file'), _('OK')) - - - - - def set_url(self, url): - payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) - self.tabs.setCurrentIndex(1) - label = self.wallet.labels.get(payto) - m_addr = label + ' <'+ payto+'>' if label else payto - self.payto_e.setText(m_addr) - - self.message_e.setText(message) - self.amount_e.setText(amount) - if identity: - self.set_frozen(self.payto_e,True) - self.set_frozen(self.amount_e,True) - self.set_frozen(self.message_e,True) - self.payto_sig.setText( ' The bitcoin URI was signed by ' + identity ) - else: - self.payto_sig.setVisible(False) - - def do_clear(self): - self.payto_sig.setVisible(False) - for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]: - e.setText('') - self.set_frozen(e,False) - - def set_frozen(self,entry,frozen): - if frozen: - entry.setReadOnly(True) - entry.setFrame(False) - palette = QPalette() - palette.setColor(entry.backgroundRole(), QColor('lightgray')) - entry.setPalette(palette) - else: - entry.setReadOnly(False) - entry.setFrame(True) - palette = QPalette() - palette.setColor(entry.backgroundRole(), QColor('white')) - entry.setPalette(palette) - - - def toggle_freeze(self,addr): - if not addr: return - if addr in self.wallet.frozen_addresses: - self.wallet.unfreeze(addr) - else: - self.wallet.freeze(addr) - self.update_receive_tab() - - def toggle_priority(self,addr): - if not addr: return - if addr in self.wallet.prioritized_addresses: - self.wallet.unprioritize(addr) - else: - self.wallet.prioritize(addr) - self.update_receive_tab() - - - def create_list_tab(self, headers): - "generic tab creation method" - l = MyTreeWidget(self) - l.setColumnCount( len(headers) ) - l.setHeaderLabels( headers ) - - w = QWidget() - vbox = QVBoxLayout() - w.setLayout(vbox) - - vbox.setMargin(0) - vbox.setSpacing(0) - vbox.addWidget(l) - buttons = QWidget() - vbox.addWidget(buttons) - - hbox = QHBoxLayout() - hbox.setMargin(0) - hbox.setSpacing(0) - buttons.setLayout(hbox) - - return l,w,hbox - - - def create_receive_tab(self): - l,w,hbox = self.create_list_tab([ _('Address'), _('Label'), _('Requested'), _('Balance'), _('Tx')]) - l.setContextMenuPolicy(Qt.CustomContextMenu) - l.customContextMenuRequested.connect(self.create_receive_menu) - self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1)) - self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1)) - self.connect(l, SIGNAL('currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)'), lambda a,b: self.recv_changed(a)) - self.receive_list = l - self.receive_buttons_hbox = hbox - hbox.addStretch(1) - return w - - - def receive_tab_set_mode(self, i): - self.save_column_widths() - self.receive_tab_mode = i - self.config.set_key('qt_receive_tab_mode', self.receive_tab_mode, True) - self.wallet.save() - self.update_receive_tab() - self.toggle_QR_window(self.receive_tab_mode == 2) - - - def save_column_widths(self): - if self.receive_tab_mode == 0: - widths = [ self.receive_list.columnWidth(0) ] - else: - widths = [] - for i in range(self.receive_list.columnCount() -1): - widths.append(self.receive_list.columnWidth(i)) - self.column_widths["receive"][self.receive_tab_mode] = widths - - self.column_widths["history"] = [] - for i in range(self.history_list.columnCount() - 1): - self.column_widths["history"].append(self.history_list.columnWidth(i)) - - self.column_widths["contacts"] = [] - for i in range(self.contacts_list.columnCount() - 1): - self.column_widths["contacts"].append(self.contacts_list.columnWidth(i)) - - - def create_contacts_tab(self): - l,w,hbox = self.create_list_tab([_('Address'), _('Label'), _('Tx')]) - l.setContextMenuPolicy(Qt.CustomContextMenu) - l.customContextMenuRequested.connect(self.create_contact_menu) - for i,width in enumerate(self.column_widths['contacts']): - l.setColumnWidth(i, width) - - self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1)) - self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1)) - self.contacts_list = l - self.contacts_buttons_hbox = hbox - hbox.addWidget(EnterButton(_("New"), self.new_contact_dialog)) - hbox.addStretch(1) - return w - - - def delete_imported_key(self, addr): - if self.question(_("Do you want to remove")+" %s "%addr +_("from your wallet?")): - self.wallet.imported_keys.pop(addr) - self.update_receive_tab() - self.update_history_tab() - self.wallet.save() - - - def create_receive_menu(self, position): - # fixme: this function apparently has a side effect. - # if it is not called the menu pops up several times - #self.receive_list.selectedIndexes() - - item = self.receive_list.itemAt(position) - if not item: return - addr = unicode(item.text(0)) - menu = QMenu() - menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(addr)) - if self.receive_tab_mode == 2: - menu.addAction(_("Request amount"), lambda: self.edit_amount()) - menu.addAction(_("View QR"), lambda: ElectrumWindow.show_qrcode(_("Address"),"bitcoin:"+addr) ) - menu.addAction(_("Edit label"), lambda: self.edit_label(True)) - menu.addAction(_("Private key"), lambda: self.view_private_key(addr)) - menu.addAction(_("Sign message"), lambda: self.sign_message(addr)) - if addr in self.wallet.imported_keys: - menu.addAction(_("Remove from wallet"), lambda: self.delete_imported_key(addr)) - - if self.receive_tab_mode == 1: - t = _("Unfreeze") if addr in self.wallet.frozen_addresses else _("Freeze") - menu.addAction(t, lambda: self.toggle_freeze(addr)) - t = _("Unprioritize") if addr in self.wallet.prioritized_addresses else _("Prioritize") - menu.addAction(t, lambda: self.toggle_priority(addr)) - - menu.exec_(self.receive_list.viewport().mapToGlobal(position)) - - - def payto(self, x, is_alias): - if not x: return - if is_alias: - label = x - m_addr = label - else: - addr = x - label = self.wallet.labels.get(addr) - m_addr = label + ' <' + addr + '>' if label else addr - self.tabs.setCurrentIndex(1) - self.payto_e.setText(m_addr) - self.amount_e.setFocus() - - def delete_contact(self, x, is_alias): - if self.question(_("Do you want to remove")+" %s "%x +_("from your list of contacts?")): - if not is_alias and x in self.wallet.addressbook: - self.wallet.addressbook.remove(x) - if x in self.wallet.labels.keys(): - self.wallet.labels.pop(x) - elif is_alias and x in self.wallet.aliases: - self.wallet.aliases.pop(x) - self.update_history_tab() - self.update_contacts_tab() - self.update_completions() - - def create_contact_menu(self, position): - # fixme: this function apparently has a side effect. - # if it is not called the menu pops up several times - #self.contacts_list.selectedIndexes() - - item = self.contacts_list.itemAt(position) - if not item: return - addr = unicode(item.text(0)) - label = unicode(item.text(1)) - is_alias = label in self.wallet.aliases.keys() - x = label if is_alias else addr - menu = QMenu() - menu.addAction(_("Copy to Clipboard"), lambda: self.app.clipboard().setText(addr)) - menu.addAction(_("Pay to"), lambda: self.payto(x, is_alias)) - menu.addAction(_("View QR code"),lambda: self.show_qrcode(_("Address"),"bitcoin:"+addr)) - if not is_alias: - menu.addAction(_("Edit label"), lambda: self.edit_label(False)) - else: - menu.addAction(_("View alias details"), lambda: self.show_contact_details(label)) - menu.addAction(_("Delete"), lambda: self.delete_contact(x,is_alias)) - menu.exec_(self.contacts_list.viewport().mapToGlobal(position)) - - - def update_receive_item(self, item): - address = str(item.data(0,0).toString()) - label = self.wallet.labels.get(address,'') - item.setData(1,0,label) - - try: - amount, currency = self.wallet.requested_amounts.get(address, (None, None)) - except: - amount, currency = None, None - - amount_str = amount + (' ' + currency if currency else '') if amount is not None else '' - item.setData(2,0,amount_str) - - c, u = self.wallet.get_addr_balance(address) - balance = format_satoshis( c + u, False, self.wallet.num_zeros ) - item.setData(3,0,balance) - - if self.receive_tab_mode == 1: - if address in self.wallet.frozen_addresses: - item.setBackgroundColor(0, QColor('lightblue')) - elif address in self.wallet.prioritized_addresses: - item.setBackgroundColor(0, QColor('lightgreen')) - - - def update_receive_tab(self): - l = self.receive_list - - l.clear() - l.setColumnHidden(2, not self.receive_tab_mode == 2) - l.setColumnHidden(3, self.receive_tab_mode == 0) - l.setColumnHidden(4, not self.receive_tab_mode == 1) - if self.receive_tab_mode == 0: - width = self.column_widths['receive'][0][0] - l.setColumnWidth(0, width) - else: - for i,width in enumerate(self.column_widths['receive'][self.receive_tab_mode]): - l.setColumnWidth(i, width) - - - for k, account in self.wallet.accounts.items(): - name = account.get('name',str(k)) - account_item = QTreeWidgetItem( [ name, '', '', '', ''] ) - l.addTopLevelItem(account_item) - account_item.setExpanded(True) - - for is_change in [0,1]: - name = "Receiving" if not is_change else "Change" - seq_item = QTreeWidgetItem( [ name, '', '', '', ''] ) - account_item.addChild(seq_item) - if not is_change: seq_item.setExpanded(True) - is_red = False - gap = 0 - - for address in account[is_change]: - h = self.wallet.history.get(address,[]) - - if not is_change: - if h == []: - gap += 1 - if gap > self.wallet.gap_limit: - is_red = True - else: - gap = 0 - - num_tx = '*' if h == ['*'] else "%d"%len(h) - item = QTreeWidgetItem( [ address, '', '', '', num_tx] ) - item.setFont(0, QFont(MONOSPACE_FONT)) - item.setFont(2, QFont(MONOSPACE_FONT)) - self.update_receive_item(item) - if is_red and not is_change: - item.setBackgroundColor(1, QColor('red')) - seq_item.addChild(item) - - if self.wallet.imported_keys: - account_item = QTreeWidgetItem( [ "Imported", '', '', '', ''] ) - l.addTopLevelItem(account_item) - account_item.setExpanded(True) - for address in self.wallet.imported_keys.keys(): - item = QTreeWidgetItem( [ address, '', '', '', ''] ) - item.setFont(0, QFont(MONOSPACE_FONT)) - item.setFont(2, QFont(MONOSPACE_FONT)) - self.update_receive_item(item) - if is_red and not is_change: - item.setBackgroundColor(1, QColor('red')) - account_item.addChild(item) - - - # we use column 1 because column 0 may be hidden - l.setCurrentItem(l.topLevelItem(0),1) - - def show_contact_details(self, m): - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self-signed" - msg = _('Alias:')+' '+ m + '\n'+_('Target address:')+' '+ a[1] + '\n\n'+_('Signed by:')+' ' + s + '\n'+_('Signing address:')+' ' + a[0] - QMessageBox.information(self, 'Alias', msg, 'OK') - - def update_contacts_tab(self): - - l = self.contacts_list - l.clear() - - alias_targets = [] - for alias, v in self.wallet.aliases.items(): - s, target = v - alias_targets.append(target) - item = QTreeWidgetItem( [ target, alias, '-'] ) - item.setBackgroundColor(0, QColor('lightgray')) - l.addTopLevelItem(item) - - for address in self.wallet.addressbook: - if address in alias_targets: continue - label = self.wallet.labels.get(address,'') - n = 0 - for tx in self.wallet.transactions.values(): - if address in map(lambda x: x[0], tx.outputs): n += 1 - - item = QTreeWidgetItem( [ address, label, "%d"%n] ) - item.setFont(0, QFont(MONOSPACE_FONT)) - l.addTopLevelItem(item) - - l.setCurrentItem(l.topLevelItem(0)) - - - def create_console_tab(self): - from qt_console import Console - import util, bitcoin, commands - self.console = console = Console() - console.updateNamespace({'wallet' : self.wallet, 'interface' : self.wallet.interface, 'gui':self}) - console.updateNamespace({'util' : util, 'bitcoin':bitcoin}) - - c = commands.Commands(self.wallet, self.wallet.interface, lambda: self.console.set_json(True)) - methods = {} - def mkfunc(f, method): - return lambda *args: apply( f, (method, args, self.password_dialog )) - for m in dir(c): - if m[0]=='_' or m=='wallet' or m == 'interface': continue - methods[m] = mkfunc(c._run, m) - - console.updateNamespace(methods) - return console - - - def create_status_bar(self): - self.status_text = "" - sb = QStatusBar() - sb.setFixedHeight(35) - qtVersion = qVersion() - - update_notification = UpdateLabel(self.config) - if(update_notification.new_version): - sb.addPermanentWidget(update_notification) - - if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7): - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) ) - if self.wallet.seed: - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/lock.png"), _("Password"), lambda: self.change_password_dialog(self.wallet, self) ) ) - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), _("Preferences"), self.settings_dialog ) ) - if self.wallet.seed: - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/seed.png"), _("Seed"), lambda: self.show_seed_dialog(self.wallet, self) ) ) - self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), _("Network"), lambda: self.network_dialog(self.wallet, self) ) - sb.addPermanentWidget( self.status_button ) - - self.setStatusBar(sb) - - def go_lite(self): - import gui_lite - self.config.set_key('gui', 'lite', True) - self.hide() - if self.lite: - self.lite.mini.show() - else: - self.lite = gui_lite.ElectrumGui(self.wallet, self.config, self) - self.lite.main(None) - - def new_contact_dialog(self): - text, ok = QInputDialog.getText(self, _('New Contact'), _('Address') + ':') - address = unicode(text) - if ok: - if is_valid(address): - self.wallet.addressbook.append(address) - self.wallet.save() - self.update_contacts_tab() - self.update_history_tab() - self.update_completions() - else: - QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK')) - - def show_master_public_key(self): - dialog = QDialog(None) - dialog.setModal(1) - dialog.setWindowTitle(_("Master Public Key")) - - main_text = QTextEdit() - main_text.setText(self.wallet.get_master_public_key()) - main_text.setReadOnly(True) - main_text.setMaximumHeight(170) - qrw = QRCodeWidget(self.wallet.get_master_public_key(), 6) - - ok_button = QPushButton(_("OK")) - ok_button.setDefault(True) - ok_button.clicked.connect(dialog.accept) - - main_layout = QGridLayout() - main_layout.addWidget(QLabel(_('Your Master Public Key is:')), 0, 0, 1, 2) - - main_layout.addWidget(main_text, 1, 0) - main_layout.addWidget(qrw, 1, 1 ) - - vbox = QVBoxLayout() - vbox.addLayout(main_layout) - hbox = QHBoxLayout() - hbox.addStretch(1) - hbox.addWidget(ok_button) - vbox.addLayout(hbox) - - dialog.setLayout(vbox) - dialog.exec_() - - - @classmethod - def show_seed_dialog(self, wallet, parent=None): - if not wallet.seed: - QMessageBox.information(parent, _('Message'), _('No seed'), _('OK')) - return - - if wallet.use_encryption: - password = parent.password_dialog() - if not password: - return - else: - password = None - - try: - seed = wallet.decode_seed(password) - except: - QMessageBox.warning(parent, _('Error'), _('Incorrect Password'), _('OK')) - return - - self.show_seed(seed) - - @classmethod - def show_seed(self, seed): - dialog = QDialog(None) - dialog.setModal(1) - dialog.setWindowTitle('Electrum' + ' - ' + _('Seed')) - - brainwallet = ' '.join(mnemonic.mn_encode(seed)) - - label1 = QLabel(_("Your wallet generation seed is")+ ":") - - seed_text = QTextEdit(brainwallet) - seed_text.setReadOnly(True) - seed_text.setMaximumHeight(130) - - msg2 = _("Please write down or memorize these 12 words (order is important).") + " " \ - + _("This seed will allow you to recover your wallet in case of computer failure.") + " " \ - + _("Your seed is also displayed as QR code, in case you want to transfer it to a mobile phone.") + "<p>" \ - + "<b>"+_("WARNING")+":</b> " + _("Never disclose your seed. Never type it on a website.") + "</b><p>" - label2 = QLabel(msg2) - label2.setWordWrap(True) - - logo = QLabel() - logo.setPixmap(QPixmap(":icons/seed.png").scaledToWidth(56)) - logo.setMaximumWidth(60) - - qrw = QRCodeWidget(seed, 4) - - ok_button = QPushButton(_("OK")) - ok_button.setDefault(True) - ok_button.clicked.connect(dialog.accept) - - grid = QGridLayout() - #main_layout.addWidget(logo, 0, 0) - - grid.addWidget(logo, 0, 0) - grid.addWidget(label1, 0, 1) - - grid.addWidget(seed_text, 1, 0, 1, 2) - - grid.addWidget(qrw, 0, 2, 2, 1) - - vbox = QVBoxLayout() - vbox.addLayout(grid) - vbox.addWidget(label2) - - hbox = QHBoxLayout() - hbox.addStretch(1) - hbox.addWidget(ok_button) - vbox.addLayout(hbox) - - dialog.setLayout(vbox) - dialog.exec_() - - @staticmethod - def show_qrcode(title, data): - if not data: return - d = QDialog(None) - d.setModal(1) - d.setWindowTitle(title) - d.setMinimumSize(270, 300) - vbox = QVBoxLayout() - qrw = QRCodeWidget(data) - vbox.addWidget(qrw, 1) - vbox.addWidget(QLabel(data), 0, Qt.AlignHCenter) - hbox = QHBoxLayout() - hbox.addStretch(1) - - def print_qr(self): - filename = "qrcode.bmp" - bmp.save_qrcode(qrw.qr, filename) - QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK')) - - b = QPushButton(_("Print")) - hbox.addWidget(b) - b.clicked.connect(print_qr) - - b = QPushButton(_("Close")) - hbox.addWidget(b) - b.clicked.connect(d.accept) - - vbox.addLayout(hbox) - d.setLayout(vbox) - d.exec_() - - def view_private_key(self,address): - if not address: return - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - pk = self.wallet.get_private_key(address, password) - except BaseException, e: - self.show_message(str(e)) - return - - QMessageBox.information(self, _('Private key'), 'Address'+ ': ' + address + '\n\n' + _('Private key') + ': ' + pk, _('OK')) - - - def sign_message(self,address): - if not address: return - d = QDialog(self) - d.setModal(1) - d.setWindowTitle(_('Sign Message')) - d.setMinimumSize(410, 290) - - tab_widget = QTabWidget() - tab = QWidget() - layout = QGridLayout(tab) - - sign_address = QLineEdit() - - sign_address.setText(address) - layout.addWidget(QLabel(_('Address')), 1, 0) - layout.addWidget(sign_address, 1, 1) - - sign_message = QTextEdit() - layout.addWidget(QLabel(_('Message')), 2, 0) - layout.addWidget(sign_message, 2, 1) - layout.setRowStretch(2,3) - - sign_signature = QTextEdit() - layout.addWidget(QLabel(_('Signature')), 3, 0) - layout.addWidget(sign_signature, 3, 1) - layout.setRowStretch(3,1) - - def do_sign(): - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - signature = self.wallet.sign_message(str(sign_address.text()), str(sign_message.toPlainText()), password) - sign_signature.setText(signature) - except BaseException, e: - self.show_message(str(e)) - return - - hbox = QHBoxLayout() - b = QPushButton(_("Sign")) - hbox.addWidget(b) - b.clicked.connect(do_sign) - b = QPushButton(_("Close")) - b.clicked.connect(d.accept) - hbox.addWidget(b) - layout.addLayout(hbox, 4, 1) - tab_widget.addTab(tab, _("Sign")) - - - tab = QWidget() - layout = QGridLayout(tab) - - verify_address = QLineEdit() - layout.addWidget(QLabel(_('Address')), 1, 0) - layout.addWidget(verify_address, 1, 1) - - verify_message = QTextEdit() - layout.addWidget(QLabel(_('Message')), 2, 0) - layout.addWidget(verify_message, 2, 1) - layout.setRowStretch(2,3) - - verify_signature = QTextEdit() - layout.addWidget(QLabel(_('Signature')), 3, 0) - layout.addWidget(verify_signature, 3, 1) - layout.setRowStretch(3,1) - - def do_verify(): - try: - self.wallet.verify_message(verify_address.text(), str(verify_signature.toPlainText()), str(verify_message.toPlainText())) - self.show_message(_("Signature verified")) - except BaseException, e: - self.show_message(str(e)) - return - - hbox = QHBoxLayout() - b = QPushButton(_("Verify")) - b.clicked.connect(do_verify) - hbox.addWidget(b) - b = QPushButton(_("Close")) - b.clicked.connect(d.accept) - hbox.addWidget(b) - layout.addLayout(hbox, 4, 1) - tab_widget.addTab(tab, _("Verify")) - - vbox = QVBoxLayout() - vbox.addWidget(tab_widget) - d.setLayout(vbox) - d.exec_() - - - def toggle_QR_window(self, show): - if show and not self.qr_window: - self.qr_window = QR_Window(self.exchanger) - self.qr_window.setVisible(True) - self.qr_window_geometry = self.qr_window.geometry() - item = self.receive_list.currentItem() - if item: - address = str(item.text(1)) - label = self.wallet.labels.get(address) - amount, currency = self.wallet.requested_amounts.get(address, (None, None)) - self.qr_window.set_content( address, label, amount, currency ) - - elif show and self.qr_window and not self.qr_window.isVisible(): - self.qr_window.setVisible(True) - self.qr_window.setGeometry(self.qr_window_geometry) - - elif not show and self.qr_window and self.qr_window.isVisible(): - self.qr_window_geometry = self.qr_window.geometry() - self.qr_window.setVisible(False) - - #self.print_button.setHidden(self.qr_window is None or not self.qr_window.isVisible()) - self.receive_list.setColumnHidden(2, self.qr_window is None or not self.qr_window.isVisible()) - self.receive_list.setColumnWidth(1, 200) - - - def question(self, msg): - return QMessageBox.question(self, _('Message'), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes - - def show_message(self, msg): - QMessageBox.information(self, _('Message'), msg, _('OK')) - - def password_dialog(self ): - d = QDialog(self) - d.setModal(1) - - pw = QLineEdit() - pw.setEchoMode(2) - - vbox = QVBoxLayout() - msg = _('Please enter your password') - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - grid.addWidget(QLabel(_('Password')), 1, 0) - grid.addWidget(pw, 1, 1) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - return unicode(pw.text()) - - - - - - @staticmethod - def change_password_dialog( wallet, parent=None ): - - if not wallet.seed: - QMessageBox.information(parent, _('Error'), _('No seed'), _('OK')) - return - - d = QDialog(parent) - d.setModal(1) - - pw = QLineEdit() - pw.setEchoMode(2) - new_pw = QLineEdit() - new_pw.setEchoMode(2) - conf_pw = QLineEdit() - conf_pw.setEchoMode(2) - - vbox = QVBoxLayout() - if parent: - msg = (_('Your wallet is encrypted. Use this dialog to change your password.')+'\n'\ - +_('To disable wallet encryption, enter an empty new password.')) \ - if wallet.use_encryption else _('Your wallet keys are not encrypted') - else: - msg = _("Please choose a password to encrypt your wallet keys.")+'\n'\ - +_("Leave these fields empty if you want to disable encryption.") - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - - if wallet.use_encryption: - grid.addWidget(QLabel(_('Password')), 1, 0) - grid.addWidget(pw, 1, 1) - - grid.addWidget(QLabel(_('New Password')), 2, 0) - grid.addWidget(new_pw, 2, 1) - - grid.addWidget(QLabel(_('Confirm Password')), 3, 0) - grid.addWidget(conf_pw, 3, 1) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - password = unicode(pw.text()) if wallet.use_encryption else None - new_password = unicode(new_pw.text()) - new_password2 = unicode(conf_pw.text()) - - try: - seed = wallet.decode_seed(password) - except: - QMessageBox.warning(parent, _('Error'), _('Incorrect Password'), _('OK')) - return - - if new_password != new_password2: - QMessageBox.warning(parent, _('Error'), _('Passwords do not match'), _('OK')) - return ElectrumWindow.change_password_dialog(wallet, parent) # Retry - - wallet.update_password(seed, password, new_password) - - @staticmethod - def seed_dialog(wallet, parent=None): - d = QDialog(parent) - d.setModal(1) - - vbox = QVBoxLayout() - msg = _("Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet.") - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - - seed_e = QLineEdit() - grid.addWidget(QLabel(_('Seed or mnemonic')), 1, 0) - grid.addWidget(seed_e, 1, 1) - - gap_e = QLineEdit() - gap_e.setText("5") - grid.addWidget(QLabel(_('Gap limit')), 2, 0) - grid.addWidget(gap_e, 2, 1) - gap_e.textChanged.connect(lambda: numbify(gap_e,True)) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - try: - gap = int(unicode(gap_e.text())) - except: - QMessageBox.warning(None, _('Error'), 'error', 'OK') - return - - try: - seed = str(seed_e.text()) - seed.decode('hex') - except: - print_error("Warning: Not hex, trying decode") - try: - seed = mnemonic.mn_decode( seed.split(' ') ) - except: - QMessageBox.warning(None, _('Error'), _('I cannot decode this'), _('OK')) - return - - if not seed: - QMessageBox.warning(None, _('Error'), _('No seed'), _('OK')) - return - - return seed, gap - - def generate_transaction_information_widget(self, tx): - tabs = QTabWidget(self) - - tab1 = QWidget() - grid_ui = QGridLayout(tab1) - grid_ui.setColumnStretch(0,1) - tabs.addTab(tab1, _('Outputs') ) - - tree_widget = MyTreeWidget(self) - tree_widget.setColumnCount(2) - tree_widget.setHeaderLabels( [_('Address'), _('Amount')] ) - tree_widget.setColumnWidth(0, 300) - tree_widget.setColumnWidth(1, 50) - - for output in tx.d["outputs"]: - item = QTreeWidgetItem( ["%s" %(output["address"]), "%s" % ( format_satoshis(output["value"]))] ) - tree_widget.addTopLevelItem(item) - - tree_widget.setMaximumHeight(100) - - grid_ui.addWidget(tree_widget) - - tab2 = QWidget() - grid_ui = QGridLayout(tab2) - grid_ui.setColumnStretch(0,1) - tabs.addTab(tab2, _('Inputs') ) - - tree_widget = MyTreeWidget(self) - tree_widget.setColumnCount(2) - tree_widget.setHeaderLabels( [ _('Address'), _('Previous output')] ) - - for input_line in tx.inputs: - item = QTreeWidgetItem( [ str(input_line["address"]), str(input_line["prevout_hash"])] ) - tree_widget.addTopLevelItem(item) - - tree_widget.setMaximumHeight(100) - - grid_ui.addWidget(tree_widget) - return tabs - - - def tx_dict_from_text(self, txt): - try: - tx_dict = json.loads(str(txt)) - assert "hex" in tx_dict.keys() - assert "complete" in tx_dict.keys() - if not tx_dict["complete"]: - assert "input_info" in tx_dict.keys() - except: - QMessageBox.critical(None, "Unable to parse transaction", _("Electrum was unable to parse your transaction:")) - return None - return tx_dict - - - def read_tx_from_file(self): - fileName = QFileDialog.getOpenFileName(QWidget(), _("Select your transaction file"), os.path.expanduser('~')) - if not fileName: - return - try: - with open(fileName, "r") as f: - file_content = f.read() - except (ValueError, IOError, os.error), reason: - QMessageBox.critical(None,"Unable to read file or no transaction found", _("Electrum was unable to open your transaction file") + "\n" + str(reason)) - - return self.tx_dict_from_text(file_content) - - - def sign_raw_transaction(self, tx, input_info): - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - self.wallet.signrawtransaction(tx, input_info, [], password) - - fileName = QFileDialog.getSaveFileName(QWidget(), _("Select where to save your signed transaction"), os.path.expanduser('~/signed_tx_%s' % (tx.hash()[0:8]))) - if fileName: - with open(fileName, "w+") as f: - f.write(json.dumps(tx.as_dict(),indent=4) + '\n') - self.show_message(_("Transaction saved succesfully")) - except BaseException, e: - self.show_message(str(e)) - - - def create_sign_transaction_window(self, tx_dict): - tx = Transaction(tx_dict["hex"]) - - dialog = QDialog(self) - dialog.setMinimumWidth(500) - dialog.setWindowTitle(_('Sign unsigned transaction')) - dialog.setModal(1) - - vbox = QVBoxLayout() - dialog.setLayout(vbox) - vbox.addWidget( self.generate_transaction_information_widget(tx) ) - - if tx_dict["complete"] == True: - vbox.addWidget(QLabel(_("This transaction is already signed."))) - else: - vbox.addWidget(QLabel(_("Create a signed transaction."))) - vbox.addLayout(ok_cancel_buttons(dialog)) - input_info = json.loads(tx_dict["input_info"]) - - if dialog.exec_(): - self.sign_raw_transaction(tx, input_info) - - - - def do_sign_from_text(self): - txt, ok = QInputDialog.getText(QTextEdit(), _('Sign raw transaction'), _('Transaction data in JSON') + ':') - if not ok: - return - tx_dict = self.tx_dict_from_text(unicode(txt)) - if tx_dict: - self.create_sign_transaction_window(tx_dict) - - - def do_sign_from_file(self): - tx_dict = self.read_tx_from_file() - if tx_dict: - self.create_sign_transaction_window(tx_dict) - - - def send_raw_transaction(self, raw_tx): - result, result_message = self.wallet.sendtx( raw_tx ) - if result: - self.show_message("Transaction succesfully sent: %s" % (result_message)) - else: - self.show_message("There was a problem sending your transaction:\n %s" % (result_message)) - - - def create_send_transaction_window(self, tx_dict): - tx = Transaction(tx_dict["hex"]) - - dialog = QDialog(self) - dialog.setMinimumWidth(500) - dialog.setWindowTitle(_('Send raw transaction')) - dialog.setModal(1) - - vbox = QVBoxLayout() - dialog.setLayout(vbox) - vbox.addWidget( self.generate_transaction_information_widget(tx)) - - if tx_dict["complete"] == False: - vbox.addWidget(QLabel(_("This transaction is not signed yet."))) - else: - vbox.addWidget(QLabel(_("Broadcast this transaction"))) - vbox.addLayout(ok_cancel_buttons(dialog)) - - if dialog.exec_(): - self.send_raw_transaction(tx_dict["hex"]) - - - def do_send_from_file(self): - tx_dict = self.read_tx_from_file() - if tx_dict: - self.create_send_transaction_window(tx_dict) - - - def do_send_from_text(self): - txt, ok = QInputDialog.getText(QTextEdit(), _('Send raw transaction'), _('Transaction data in JSON') + ':') - if not ok: - return - tx_dict = self.tx_dict_from_text(unicode(txt)) - if tx_dict: - self.create_send_transaction_window(tx_dict) - - - def do_export_privkeys(self): - self.show_message("%s\n%s\n%s" % (_("WARNING: ALL your private keys are secret."), _("Exposing a single private key can compromise your entire wallet!"), _("In particular, DO NOT use 'redeem private key' services proposed by third parties."))) - - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - try: - select_export = _('Select file to export your private keys to') - fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-private-keys.csv'), "*.csv") - if fileName: - with open(fileName, "w+") as csvfile: - transaction = csv.writer(csvfile) - transaction.writerow(["address", "private_key"]) - - - for addr, pk in self.wallet.get_private_keys(self.wallet.addresses(True), password).items(): - transaction.writerow(["%34s"%addr,pk]) - - self.show_message(_("Private keys exported.")) - - except (IOError, os.error), reason: - export_error_label = _("Electrum was unable to produce a private key-export.") - QMessageBox.critical(None,"Unable to create csv", export_error_label + "\n" + str(reason)) - - except BaseException, e: - self.show_message(str(e)) - return - - - def do_import_labels(self): - labelsFile = QFileDialog.getOpenFileName(QWidget(), _("Open text file"), util.user_dir(), self.tr("Text Files (labels.dat)")) - if not labelsFile: return - try: - f = open(labelsFile, 'r') - data = f.read() - f.close() - for key, value in json.loads(data).items(): - self.wallet.labels[key] = value - self.wallet.save() - QMessageBox.information(None, _("Labels imported"), _("Your labels where imported from")+" '%s'" % str(labelsFile)) - except (IOError, os.error), reason: - QMessageBox.critical(None, _("Unable to import labels"), _("Electrum was unable to import your labels.")+"\n" + str(reason)) - - - - def do_export_labels(self): - labels = self.wallet.labels - try: - labelsFile = util.user_dir() + '/labels.dat' - f = open(labelsFile, 'w+') - json.dump(labels, f) - f.close() - QMessageBox.information(None, "Labels exported", _("Your labels where exported to")+" '%s'" % str(labelsFile)) - except (IOError, os.error), reason: - QMessageBox.critical(None, "Unable to export labels", _("Electrum was unable to export your labels.")+"\n" + str(reason)) - - def do_export_history(self): - from gui_lite import csv_transaction - csv_transaction(self.wallet) - - def do_import_privkey(self): - if not self.wallet.imported_keys: - r = QMessageBox.question(None, _('Warning'), _('Warning: Imported keys are not recoverable from seed.') + ' ' \ - + _('If you ever need to restore your wallet from its seed, these keys will be lost.') + '\n\n' \ - + _('Are you sure you understand what you are doing?'), 3, 4) - if r == 4: return - - text, ok = QInputDialog.getText(self, _('Import private key'), _('Private Key') + ':') - if not ok: return - sec = str(text).strip() - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - try: - addr = self.wallet.import_key(sec, password) - if not addr: - QMessageBox.critical(None, _("Unable to import key"), "error") - else: - QMessageBox.information(None, _("Key imported"), addr) - self.update_receive_tab() - self.update_history_tab() - except BaseException as e: - QMessageBox.critical(None, _("Unable to import key"), str(e)) - - def settings_dialog(self): - d = QDialog(self) - d.setWindowTitle(_('Electrum Settings')) - d.setModal(1) - vbox = QVBoxLayout() - - tabs = QTabWidget(self) - vbox.addWidget(tabs) - - tab1 = QWidget() - grid_ui = QGridLayout(tab1) - grid_ui.setColumnStretch(0,1) - tabs.addTab(tab1, _('Display') ) - - nz_label = QLabel(_('Display zeros')) - grid_ui.addWidget(nz_label, 3, 0) - nz_e = QLineEdit() - nz_e.setText("%d"% self.wallet.num_zeros) - grid_ui.addWidget(nz_e, 3, 1) - msg = _('Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"') - grid_ui.addWidget(HelpButton(msg), 3, 2) - nz_e.textChanged.connect(lambda: numbify(nz_e,True)) - if not self.config.is_modifiable('num_zeros'): - for w in [nz_e, nz_label]: w.setEnabled(False) - - lang_label=QLabel(_('Language') + ':') - grid_ui.addWidget(lang_label , 8, 0) - lang_combo = QComboBox() - from i18n import languages - lang_combo.addItems(languages.values()) - try: - index = languages.keys().index(self.config.get("language",'')) - except: - index = 0 - lang_combo.setCurrentIndex(index) - grid_ui.addWidget(lang_combo, 8, 1) - grid_ui.addWidget(HelpButton(_('Select which language is used in the GUI (after restart).')+' '), 8, 2) - if not self.config.is_modifiable('language'): - for w in [lang_combo, lang_label]: w.setEnabled(False) - - currencies = self.exchanger.get_currencies() - currencies.insert(0, "None") - - cur_label=QLabel(_('Currency') + ':') - grid_ui.addWidget(cur_label , 9, 0) - cur_combo = QComboBox() - cur_combo.addItems(currencies) - try: - index = currencies.index(self.config.get('currency', "None")) - except: - index = 0 - cur_combo.setCurrentIndex(index) - grid_ui.addWidget(cur_combo, 9, 1) - grid_ui.addWidget(HelpButton(_('Select which currency is used for quotes.')+' '), 9, 2) - - view_label=QLabel(_('Receive Tab') + ':') - grid_ui.addWidget(view_label , 10, 0) - view_combo = QComboBox() - view_combo.addItems([_('Simple'), _('Advanced'), _('Point of Sale')]) - view_combo.setCurrentIndex(self.receive_tab_mode) - grid_ui.addWidget(view_combo, 10, 1) - hh = _('This selects the interaction mode of the "Receive" tab.')+' ' + '\n\n' \ - + _('Simple') + ': ' + _('Show only addresses and labels.') + '\n\n' \ - + _('Advanced') + ': ' + _('Show address balances and add extra menu items to freeze/prioritize addresses.') + '\n\n' \ - + _('Point of Sale') + ': ' + _('Show QR code window and amounts requested for each address. Add menu item to request amount.') + '\n\n' - - grid_ui.addWidget(HelpButton(hh), 10, 2) - - # wallet tab - tab2 = QWidget() - grid_wallet = QGridLayout(tab2) - grid_wallet.setColumnStretch(0,1) - tabs.addTab(tab2, _('Wallet') ) - - fee_label = QLabel(_('Transaction fee')) - grid_wallet.addWidget(fee_label, 0, 0) - fee_e = QLineEdit() - fee_e.setText("%s"% str( Decimal( self.wallet.fee)/100000000 ) ) - grid_wallet.addWidget(fee_e, 0, 1) - msg = _('Fee per transaction input. Transactions involving multiple inputs tend to require a higher fee.') + ' ' \ - + _('Recommended value') + ': 0.001' - grid_wallet.addWidget(HelpButton(msg), 0, 2) - fee_e.textChanged.connect(lambda: numbify(fee_e,False)) - if not self.config.is_modifiable('fee'): - for w in [fee_e, fee_label]: w.setEnabled(False) - - usechange_label = QLabel(_('Use change addresses')) - grid_wallet.addWidget(usechange_label, 1, 0) - usechange_combo = QComboBox() - usechange_combo.addItems([_('Yes'), _('No')]) - usechange_combo.setCurrentIndex(not self.wallet.use_change) - grid_wallet.addWidget(usechange_combo, 1, 1) - grid_wallet.addWidget(HelpButton(_('Using change addresses makes it more difficult for other people to track your transactions.')+' '), 1, 2) - if not self.config.is_modifiable('use_change'): usechange_combo.setEnabled(False) - - gap_label = QLabel(_('Gap limit')) - grid_wallet.addWidget(gap_label, 2, 0) - gap_e = QLineEdit() - gap_e.setText("%d"% self.wallet.gap_limit) - grid_wallet.addWidget(gap_e, 2, 1) - msg = _('The gap limit is the maximal number of contiguous unused addresses in your sequence of receiving addresses.') + '\n' \ - + _('You may increase it if you need more receiving addresses.') + '\n\n' \ - + _('Your current gap limit is') + ': %d'%self.wallet.gap_limit + '\n' \ - + _('Given the current status of your address sequence, the minimum gap limit you can use is:')+' ' + '%d'%self.wallet.min_acceptable_gap() + '\n\n' \ - + _('Warning') + ': ' \ - + _('The gap limit parameter must be provided in order to recover your wallet from seed.') + ' ' \ - + _('Do not modify it if you do not understand what you are doing, or if you expect to recover your wallet without knowing it!') + '\n\n' - grid_wallet.addWidget(HelpButton(msg), 2, 2) - gap_e.textChanged.connect(lambda: numbify(nz_e,True)) - if not self.config.is_modifiable('gap_limit'): - for w in [gap_e, gap_label]: w.setEnabled(False) - - grid_wallet.setRowStretch(3,1) - - - # import/export tab - tab3 = QWidget() - grid_io = QGridLayout(tab3) - grid_io.setColumnStretch(0,1) - tabs.addTab(tab3, _('Import/Export') ) - - grid_io.addWidget(QLabel(_('Labels')), 1, 0) - grid_io.addWidget(EnterButton(_("Export"), self.do_export_labels), 1, 1) - grid_io.addWidget(EnterButton(_("Import"), self.do_import_labels), 1, 2) - grid_io.addWidget(HelpButton(_('Export your labels as json')), 1, 3) - - grid_io.addWidget(QLabel(_('History')), 2, 0) - grid_io.addWidget(EnterButton(_("Export"), self.do_export_history), 2, 1) - grid_io.addWidget(HelpButton(_('Export your transaction history as csv')), 2, 3) - - grid_io.addWidget(QLabel(_('Private keys')), 3, 0) - - grid_io.addWidget(EnterButton(_("Export"), self.do_export_privkeys), 3, 1) - grid_io.addWidget(EnterButton(_("Import"), self.do_import_privkey), 3, 2) - grid_io.addWidget(HelpButton(_('Import private key')), 3, 3) - - grid_io.addWidget(QLabel(_('Master Public Key')), 4, 0) - grid_io.addWidget(EnterButton(_("Show"), self.show_master_public_key), 4, 1) - grid_io.addWidget(HelpButton(_('Your Master Public Key can be used to create receiving addresses, but not to sign transactions.') + ' ' \ - + _('If you give it to someone, they will be able to see your transactions, but not to spend your money.') + ' ' \ - + _('If you restore your wallet from it, a watching-only (deseeded) wallet will be created.')), 4, 3) - - grid_io.setRowStretch(4,1) - - tab4 = QWidget() - grid_raw = QGridLayout(tab4) - grid_raw.setColumnStretch(0,1) - tabs.addTab(tab4, _('Raw transactions') ) - # - #grid_raw.addWidget(QLabel(_("Read raw transaction")), 3, 0) - #grid_raw.addWidget(EnterButton(_("From file"), self.do_sign_from_file),3,1) - #grid_raw.addWidget(EnterButton(_("From text"), self.do_sign_from_text),3,2) - #grid_raw.addWidget(HelpButton(_("This will show you some useful information about an unsigned transaction")),3,3) - - if self.wallet.seed: - grid_raw.addWidget(QLabel(_("Sign transaction")), 1, 0) - grid_raw.addWidget(EnterButton(_("From file"), self.do_sign_from_file),1,1) - grid_raw.addWidget(EnterButton(_("From text"), self.do_sign_from_text),1,2) - grid_raw.addWidget(HelpButton(_("Sign an unsigned transaction generated by a watching-only wallet")),1,3) - - grid_raw.addWidget(QLabel(_("Send signed transaction")), 2, 0) - grid_raw.addWidget(EnterButton(_("From file"), self.do_send_from_file),2,1) - grid_raw.addWidget(EnterButton(_("From text"), self.do_send_from_text),2,2) - grid_raw.addWidget(HelpButton(_("This will broadcast a transaction to the network.")),2,3) - grid_raw.setRowStretch(3,1) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - # run the dialog - if not d.exec_(): return - - fee = unicode(fee_e.text()) - try: - fee = int( 100000000 * Decimal(fee) ) - except: - QMessageBox.warning(self, _('Error'), _('Invalid value') +': %s'%fee, _('OK')) - return - - if self.wallet.fee != fee: - self.wallet.fee = fee - self.wallet.save() - - nz = unicode(nz_e.text()) - try: - nz = int( nz ) - if nz>8: nz=8 - except: - QMessageBox.warning(self, _('Error'), _('Invalid value')+':%s'%nz, _('OK')) - return - - if self.wallet.num_zeros != nz: - self.wallet.num_zeros = nz - self.config.set_key('num_zeros', nz, True) - self.update_history_tab() - self.update_receive_tab() - - usechange_result = usechange_combo.currentIndex() == 0 - if self.wallet.use_change != usechange_result: - self.wallet.use_change = usechange_result - self.config.set_key('use_change', self.wallet.use_change, True) - - try: - n = int(gap_e.text()) - except: - QMessageBox.warning(self, _('Error'), _('Invalid value'), _('OK')) - return - - if self.wallet.gap_limit != n: - r = self.wallet.change_gap_limit(n) - if r: - self.update_receive_tab() - self.config.set_key('gap_limit', self.wallet.gap_limit, True) - else: - QMessageBox.warning(self, _('Error'), _('Invalid value'), _('OK')) - - need_restart = False - - lang_request = languages.keys()[lang_combo.currentIndex()] - if lang_request != self.config.get('language'): - self.config.set_key("language", lang_request, True) - need_restart = True - - cur_request = str(currencies[cur_combo.currentIndex()]) - if cur_request != self.config.get('currency', "None"): - self.config.set_key('currency', cur_request, True) - self.update_wallet() - - if need_restart: - QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK')) - - self.receive_tab_set_mode(view_combo.currentIndex()) - - - @staticmethod - def network_dialog(wallet, parent=None): - interface = wallet.interface - if parent: - if interface.is_connected: - status = _("Connected to")+" %s\n%d "%(interface.host, wallet.verifier.height)+_("blocks") - else: - status = _("Not connected") - server = interface.server - else: - import random - status = _("Please choose a server.") + "\n" + _("Select 'Cancel' if you are offline.") - server = interface.server - - plist, servers_list = interface.get_servers_list() - - d = QDialog(parent) - d.setModal(1) - d.setWindowTitle(_('Server')) - d.setMinimumSize(375, 20) - - 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) - vbox.addLayout(hbox) - - - # grid layout - grid = QGridLayout() - grid.setSpacing(8) - vbox.addLayout(grid) - - # server - server_protocol = QComboBox() - server_host = QLineEdit() - server_host.setFixedWidth(200) - server_port = QLineEdit() - server_port.setFixedWidth(60) - - protocol_names = ['TCP', 'HTTP', 'TCP/SSL', 'HTTPS'] - protocol_letters = 'thsg' - DEFAULT_PORTS = {'t':'50001', 's':'50002', 'h':'8081', 'g':'8082'} - server_protocol.addItems(protocol_names) - - grid.addWidget(QLabel(_('Server') + ':'), 0, 0) - grid.addWidget(server_protocol, 0, 1) - grid.addWidget(server_host, 0, 2) - grid.addWidget(server_port, 0, 3) - - def change_protocol(p): - protocol = protocol_letters[p] - host = unicode(server_host.text()) - pp = plist.get(host,DEFAULT_PORTS) - if protocol not in pp.keys(): - protocol = pp.keys()[0] - port = pp[protocol] - server_host.setText( host ) - server_port.setText( port ) - - server_protocol.connect(server_protocol, SIGNAL('currentIndexChanged(int)'), change_protocol) - - label = _('Active Servers') if wallet.interface.servers else _('Default Servers') - servers_list_widget = QTreeWidget(parent) - servers_list_widget.setHeaderLabels( [ label, _('Type') ] ) - servers_list_widget.setMaximumHeight(150) - servers_list_widget.setColumnWidth(0, 240) - for _host in servers_list.keys(): - _type = 'P' if servers_list[_host].get('pruning') else 'F' - servers_list_widget.addTopLevelItem(QTreeWidgetItem( [ _host, _type ] )) - - def change_server(host, protocol=None): - pp = plist.get(host,DEFAULT_PORTS) - if protocol: - port = pp.get(protocol) - if not port: protocol = None - - if not protocol: - if 't' in pp.keys(): - protocol = 't' - port = pp.get(protocol) - else: - protocol = pp.keys()[0] - port = pp.get(protocol) - - server_host.setText( host ) - server_port.setText( port ) - server_protocol.setCurrentIndex(protocol_letters.index(protocol)) - - if not plist: return - for p in protocol_letters: - i = protocol_letters.index(p) - j = server_protocol.model().index(i,0) - if p not in pp.keys(): - server_protocol.model().setData(j, QtCore.QVariant(0), QtCore.Qt.UserRole-1) - else: - server_protocol.model().setData(j, QtCore.QVariant(0,False), QtCore.Qt.UserRole-1) - - - if server: - host, port, protocol = server.split(':') - change_server(host,protocol) - - servers_list_widget.connect(servers_list_widget, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), lambda x: change_server(unicode(x.text(0)))) - grid.addWidget(servers_list_widget, 1, 1, 1, 3) - - if not wallet.config.is_modifiable('server'): - for w in [server_host, server_port, server_protocol, servers_list_widget]: w.setEnabled(False) - - # auto cycle - autocycle_cb = QCheckBox(_('Try random servers if disconnected')) - autocycle_cb.setChecked(wallet.config.get('auto_cycle', False)) - grid.addWidget(autocycle_cb, 3, 1, 3, 2) - if not wallet.config.is_modifiable('auto_cycle'): autocycle_cb.setEnabled(False) - - # proxy setting - proxy_mode = QComboBox() - proxy_host = QLineEdit() - proxy_host.setFixedWidth(200) - proxy_port = QLineEdit() - proxy_port.setFixedWidth(60) - proxy_mode.addItems(['NONE', 'SOCKS4', 'SOCKS5', 'HTTP']) - - def check_for_disable(index = False): - if proxy_mode.currentText() != 'NONE': - proxy_host.setEnabled(True) - proxy_port.setEnabled(True) - else: - proxy_host.setEnabled(False) - proxy_port.setEnabled(False) - - check_for_disable() - proxy_mode.connect(proxy_mode, SIGNAL('currentIndexChanged(int)'), check_for_disable) - - if not wallet.config.is_modifiable('proxy'): - for w in [proxy_host, proxy_port, proxy_mode]: w.setEnabled(False) - - proxy_config = interface.proxy if interface.proxy else { "mode":"none", "host":"localhost", "port":"8080"} - proxy_mode.setCurrentIndex(proxy_mode.findText(str(proxy_config.get("mode").upper()))) - proxy_host.setText(proxy_config.get("host")) - proxy_port.setText(proxy_config.get("port")) - - grid.addWidget(QLabel(_('Proxy') + ':'), 2, 0) - grid.addWidget(proxy_mode, 2, 1) - grid.addWidget(proxy_host, 2, 2) - grid.addWidget(proxy_port, 2, 3) - - # buttons - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - server = unicode( server_host.text() ) + ':' + unicode( server_port.text() ) + ':' + (protocol_letters[server_protocol.currentIndex()]) - if proxy_mode.currentText() != 'NONE': - proxy = { u'mode':unicode(proxy_mode.currentText()).lower(), u'host':unicode(proxy_host.text()), u'port':unicode(proxy_port.text()) } - else: - proxy = None - - wallet.config.set_key("proxy", proxy, True) - wallet.config.set_key("server", server, True) - interface.set_server(server, proxy) - wallet.config.set_key('auto_cycle', autocycle_cb.isChecked(), True) - return True - - def closeEvent(self, event): - g = self.geometry() - self.config.set_key("winpos-qt", [g.left(),g.top(),g.width(),g.height()], True) - self.save_column_widths() - self.config.set_key("column-widths", self.column_widths, True) - event.accept() - - -class ElectrumGui: - - def __init__(self, wallet, config, app=None): - self.wallet = wallet - self.config = config - if app is None: - self.app = QApplication(sys.argv) - - - def restore_or_create(self): - msg = _("Wallet file not found.")+"\n"+_("Do you want to create a new wallet, or to restore an existing one?") - r = QMessageBox.question(None, _('Message'), msg, _('Create'), _('Restore'), _('Cancel'), 0, 2) - if r==2: return None - return 'restore' if r==1 else 'create' - - def seed_dialog(self): - return ElectrumWindow.seed_dialog( self.wallet ) - - def network_dialog(self): - return ElectrumWindow.network_dialog( self.wallet, parent=None ) - - - def show_seed(self): - ElectrumWindow.show_seed_dialog(self.wallet) - - - def password_dialog(self): - ElectrumWindow.change_password_dialog(self.wallet) - - - def restore_wallet(self): - wallet = self.wallet - # wait until we are connected, because the user might have selected another server - if not wallet.interface.is_connected: - waiting = lambda: False if wallet.interface.is_connected else "%s \n" % (_("Connecting...")) - waiting_dialog(waiting) - - waiting = lambda: False if wallet.is_up_to_date() else "%s\n%s %d\n%s %.1f"\ - %(_("Please wait..."),_("Addresses generated:"),len(wallet.addresses(True)),_("Kilobytes received:"), wallet.interface.bytes_received/1024.) - - wallet.set_up_to_date(False) - wallet.interface.poke('synchronizer') - waiting_dialog(waiting) - if wallet.is_found(): - print_error( "Recovery successful" ) - else: - QMessageBox.information(None, _('Error'), _("No transactions found for this seed"), _('OK')) - - return True - - def main(self,url): - s = Timer() - s.start() - w = ElectrumWindow(self.wallet, self.config) - if url: w.set_url(url) - w.app = self.app - w.connect_slots(s) - w.update_wallet() - w.show() - - self.app.exec_() diff --git a/lib/gui_text.py b/lib/gui_text.py @@ -1,423 +0,0 @@ -import curses, datetime -from decimal import Decimal -_ = lambda x:x -#from i18n import _ -from util import format_satoshis, set_verbosity -from bitcoin import is_valid - -import tty, sys - - -class ElectrumGui: - - def __init__(self, wallet, config, app=None): - self.stdscr = curses.initscr() - curses.noecho() - curses.cbreak() - curses.start_color() - curses.use_default_colors() - curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) - curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN) - self.stdscr.keypad(1) - self.stdscr.border(0) - self.maxy, self.maxx = self.stdscr.getmaxyx() - curses.curs_set(0) - self.w = curses.newwin(10, 50, 5, 5) - - self.wallet = wallet - self.config = config - set_verbosity(False) - self.tab = 0 - self.pos = 0 - self.popup_pos = 0 - - self.str_recipient = "" - self.str_description = "" - self.str_amount = "" - self.str_fee = "" - - self.wallet.interface.register_callback('updated', self.refresh) - self.wallet.interface.register_callback('connected', self.refresh) - self.wallet.interface.register_callback('disconnected', self.refresh) - self.wallet.interface.register_callback('disconnecting', self.refresh) - self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")] - self.num_tabs = len(self.tab_names) - - - def restore_or_create(self): - pass - - - def get_string(self, y, x): - curses.curs_set(1) - curses.echo() - self.stdscr.addstr( y, x, " "*20, curses.A_REVERSE) - s = self.stdscr.getstr(y,x) - curses.noecho() - curses.curs_set(0) - return s - - - def print_history(self): - width = [20, 40, 14, 14] - delta = (self.maxx - sum(width) - 4)/3 - format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%"+"%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s" - - b = 0 - messages = [] - - for item in self.wallet.get_tx_history(): - tx_hash, conf, is_mine, value, fee, balance, timestamp = item - if conf: - try: - time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3] - except: - time_str = "------" - else: - time_str = 'pending' - - label, is_default_label = self.wallet.get_label(tx_hash) - messages.append( format_str%( time_str, label, format_satoshis(value), format_satoshis(balance) ) ) - - self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance"))) - - - def print_balance(self): - if self.wallet.interface and self.wallet.interface.is_connected: - if not self.wallet.up_to_date: - msg = _( "Synchronizing..." ) - else: - c, u = self.wallet.get_balance() - msg = _("Balance")+": %f "%(Decimal( c ) / 100000000) - if u: msg += " [%f unconfirmed]"%(Decimal( u ) / 100000000) - else: - msg = _( "Not connected" ) - - self.stdscr.addstr( self.maxy -1, 3, msg) - - for i in range(self.num_tabs): - self.stdscr.addstr( 0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0) - - self.stdscr.addstr( self.maxy -1, self.maxx-30, ' '.join([_("Settings"), _("Network"), _("Quit")])) - - - def print_contacts(self): - messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addressbook) - self.print_list(messages, "%19s %25s "%("Address", "Label")) - - def print_receive(self): - messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addresses()) - self.print_list(messages, "%19s %25s "%("Address", "Label")) - - def print_edit_line(self, y, label, text, index, size): - text += " "*(size - len(text) ) - self.stdscr.addstr( y, 2, label) - self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1)) - - def print_send_tab(self): - self.stdscr.clear() - self.print_edit_line(3, _("Pay to"), self.str_recipient, 0, 40) - self.print_edit_line(5, _("Description"), self.str_description, 1, 40) - self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15) - self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15) - self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2)) - self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2)) - - def print_banner(self): - self.stdscr.addstr( 1, 1, self.wallet.banner ) - - def print_list(self, list, firstline): - self.maxpos = len(list) - if not self.maxpos: return - firstline += " "*(self.maxx -2 - len(firstline)) - self.stdscr.addstr( 1, 1, firstline ) - for i in range(self.maxy-4): - msg = list[i] if i < len(list) else "" - msg += " "*(self.maxx - 2 - len(msg)) - self.stdscr.addstr( i+2, 1, msg[0:self.maxx - 2], curses.A_REVERSE if i == (self.pos % self.maxpos) else 0) - - def refresh(self): - if self.tab == -1: return - self.stdscr.border(0) - self.print_balance() - self.stdscr.refresh() - - def main_command(self): - c = self.stdscr.getch() - print c - if c == curses.KEY_RIGHT: self.tab = (self.tab + 1)%self.num_tabs - elif c == curses.KEY_LEFT: self.tab = (self.tab - 1)%self.num_tabs - elif c == curses.KEY_DOWN: self.pos +=1 - elif c == curses.KEY_UP: self.pos -= 1 - elif c == 9: self.pos +=1 # tab - elif curses.unctrl(c) in ['^W', '^C', '^X', '^Q']: self.tab = -1 - elif curses.unctrl(c) in ['^N']: self.network_dialog() - elif curses.unctrl(c) == '^S': self.settings_dialog() - else: return c - if self.pos<0: self.pos=0 - if self.pos>=self.maxpos: self.pos=self.maxpos - 1 - - def run_tab(self, i, print_func, exec_func): - while self.tab == i: - self.stdscr.clear() - print_func() - self.refresh() - c = self.main_command() - if c: exec_func(c) - - - def run_history_tab(self, c): - if c == 10: - out = self.run_popup('',["blah","foo"]) - - - def edit_str(self, target, c, is_num=False): - if c==263 and target: - target = target[:-1] - elif not is_num or curses.unctrl(c) in '0123456789.': - target += curses.unctrl(c) - return target - - - def run_send_tab(self, c): - if self.pos%6 == 0: - self.str_recipient = self.edit_str(self.str_recipient, c) - if self.pos%6 == 1: - self.str_description = self.edit_str(self.str_description, c) - if self.pos%6 == 2: - self.str_amount = self.edit_str(self.str_amount, c, True) - elif self.pos%6 == 3: - self.str_fee = self.edit_str(self.str_fee, c, True) - elif self.pos%6==4: - if c == 10: self.do_send() - elif self.pos%6==5: - if c == 10: self.do_clear() - - - def run_receive_tab(self, c): - if c == 10: - out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"]) - - def run_contacts_tab(self, c): - if c == 10: - out = self.run_popup('Adress', ["Copy", "Pay to", "Edit label", "Delete"]).get('button') - address = self.wallet.addressbook[self.pos%len(self.wallet.addressbook)] - if out == "Pay to": - self.tab = 1 - self.str_recipient = address - self.pos = 2 - elif out == "Edit label": - s = self.get_string(6 + self.pos, 18) - if s: - self.wallet.labels[address] = s - - def run_banner_tab(self, c): - self.show_message(repr(c)) - pass - - def main(self,url): - - tty.setraw(sys.stdin) - while self.tab != -1: - self.run_tab(0, self.print_history, self.run_history_tab) - self.run_tab(1, self.print_send_tab, self.run_send_tab) - self.run_tab(2, self.print_receive, self.run_receive_tab) - self.run_tab(3, self.print_contacts, self.run_contacts_tab) - self.run_tab(4, self.print_banner, self.run_banner_tab) - - tty.setcbreak(sys.stdin) - curses.nocbreak() - self.stdscr.keypad(0) - curses.echo() - curses.endwin() - - - def do_clear(self): - self.str_amount = '' - self.str_recipient = '' - self.str_fee = '' - self.str_description = '' - - def do_send(self): - if not is_valid(self.str_recipient): - self.show_message(_('Invalid Bitcoin address')) - return - try: - amount = int( Decimal( self.str_amount) * 100000000 ) - except: - self.show_message(_('Invalid Amount')) - return - try: - fee = int( Decimal( self.str_fee) * 100000000 ) - except: - self.show_message(_('Invalid Fee')) - return - - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - tx = self.wallet.mktx( [(self.str_recipient, amount)], password, fee) - except BaseException, e: - self.show_message(str(e)) - return - - if self.str_description: - self.wallet.labels[tx.hash()] = self.str_description - - h = self.wallet.send_tx(tx) - self.show_message(_("Please wait..."), getchar=False) - self.wallet.tx_event.wait() - status, msg = self.wallet.receive_tx( h ) - - if status: - self.show_message(_('Payment sent.')) - self.do_clear() - #self.update_contacts_tab() - else: - self.show_message(_('Error')) - - - def show_message(self, message, getchar = True): - w = self.w - w.clear() - w.border(0) - w.addstr(2,2,message) - w.refresh() - if getchar: c = self.stdscr.getch() - - - def run_popup(self, title, items): - return self.run_dialog(title, map(lambda x: {'type':'button','label':x}, items), interval=1, y_pos = self.pos+3) - - - def network_dialog(self): - out = self.run_dialog('Network', [ - {'label':'server', 'type':'str', 'value':self.wallet.interface.server}, - {'label':'proxy', 'type':'str', 'value':self.config.get('proxy', '')}, - ], buttons = 1) - if out: - if out.get('server'): - server = out.get('server') - if out.get('proxy'): - proxy = self.parse_proxy_options(out.get('proxy')) - else: - proxy = None - - self.wallet.config.set_key("proxy", proxy, True) - self.wallet.config.set_key("server", server, True) - self.wallet.interface.set_server(server, proxy) - - - - def settings_dialog(self): - out = self.run_dialog('Settings', [ - {'label':'Default GUI', 'type':'list', 'choices':['classic','lite','gtk','text'], 'value':self.config.get('gui')}, - {'label':'Default fee', 'type':'satoshis', 'value': format_satoshis(self.config.get('fee')).strip() } - ], buttons = 1) - if out: - if out.get('Default GUI'): - self.config.set_key('gui', out['Default GUI'], True) - if out.get('Default fee'): - fee = int ( Decimal( out['Default fee']) *10000000 ) - self.config.set_key('fee', fee, True) - - - def password_dialog(self): - out = self.run_dialog('Password', [ - {'label':'Password', 'type':'password', 'value':''} - ], buttons = 1) - return out.get('Password') - - - def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3): - self.popup_pos = 0 - - self.w = curses.newwin( 5 + len(items)*interval + (2 if buttons else 0), 50, y_pos, 5) - w = self.w - out = {} - while True: - w.clear() - w.border(0) - w.addstr( 0, 2, title) - - num = len(items) - - numpos = num - if buttons: numpos += 2 - - for i in range(num): - item = items[i] - label = item.get('label') - if item.get('type') == 'list': - value = item.get('value','') - elif item.get('type') == 'satoshis': - value = item.get('value','') - elif item.get('type') == 'str': - value = item.get('value','') - elif item.get('type') == 'password': - value = '*'*len(item.get('value','')) - else: - value = '' - - if len(value)<20: value += ' '*(20-len(value)) - - if item.has_key('value'): - w.addstr( 2+interval*i, 2, label) - w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) ) - else: - w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0) - - if buttons: - w.addstr( 5+interval*i, 10, "[ ok ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2)) - w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2)) - - w.refresh() - - c = self.stdscr.getch() - if c in [ord('q'), 27]: break - elif c == curses.KEY_UP: self.popup_pos -= 1 - elif c == curses.KEY_DOWN: self.popup_pos +=1 - else: - i = self.popup_pos%numpos - if buttons and c==10: - if i == numpos-2: - return out - elif i == numpos -1: - return {} - - item = items[i] - _type = item.get('type') - - if _type == 'str': - item['value'] = self.edit_str(item['value'], c) - out[item.get('label')] = item.get('value') - - elif _type == 'password': - item['value'] = self.edit_str(item['value'], c) - out[item.get('label')] = item ['value'] - - elif _type == 'satoshis': - item['value'] = self.edit_str(item['value'], c, True) - out[item.get('label')] = item.get('value') - - elif _type == 'list': - choices = item.get('choices') - try: - j = choices.index(item.get('value')) - except: - j = 0 - new_choice = choices[(j + 1)% len(choices)] - item['value'] = new_choice - out[item.get('label')] = item.get('value') - - elif _type == 'button': - out['button'] = item.get('label') - break - - return out - diff --git a/lib/pyqrnative.py b/lib/pyqrnative.py @@ -1,962 +0,0 @@ -import math - -#from PIL import Image, ImageDraw - -#QRCode for Python -# -#Ported from the Javascript library by Sam Curren -# -#QRCode for Javascript -#http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js -# -#Copyright (c) 2009 Kazuhiko Arase -# -#URL: http://www.d-project.com/ -# -#Licensed under the MIT license: -# http://www.opensource.org/licenses/mit-license.php -# -# The word "QR Code" is registered trademark of -# DENSO WAVE INCORPORATED -# http://www.denso-wave.com/qrcode/faqpatent-e.html - - -class QR8bitByte: - - def __init__(self, data): - self.mode = QRMode.MODE_8BIT_BYTE - self.data = data - - def getLength(self): - return len(self.data) - - def write(self, buffer): - for i in range(len(self.data)): - #// not JIS ... - buffer.put(ord(self.data[i]), 8) - def __repr__(self): - return self.data - -class QRCode: - def __init__(self, typeNumber, errorCorrectLevel): - self.typeNumber = typeNumber - self.errorCorrectLevel = errorCorrectLevel - self.modules = None - self.moduleCount = 0 - self.dataCache = None - self.dataList = [] - def addData(self, data): - newData = QR8bitByte(data) - self.dataList.append(newData) - self.dataCache = None - def isDark(self, row, col): - if (row < 0 or self.moduleCount <= row or col < 0 or self.moduleCount <= col): - raise Exception("%s,%s - %s" % (row, col, self.moduleCount)) - return self.modules[row][col] - def getModuleCount(self): - return self.moduleCount - def make(self): - self.makeImpl(False, self.getBestMaskPattern() ) - def makeImpl(self, test, maskPattern): - - self.moduleCount = self.typeNumber * 4 + 17 - self.modules = [None for x in range(self.moduleCount)] - - for row in range(self.moduleCount): - - self.modules[row] = [None for x in range(self.moduleCount)] - - for col in range(self.moduleCount): - self.modules[row][col] = None #//(col + row) % 3; - - self.setupPositionProbePattern(0, 0) - self.setupPositionProbePattern(self.moduleCount - 7, 0) - self.setupPositionProbePattern(0, self.moduleCount - 7) - self.setupPositionAdjustPattern() - self.setupTimingPattern() - self.setupTypeInfo(test, maskPattern) - - if (self.typeNumber >= 7): - self.setupTypeNumber(test) - - if (self.dataCache == None): - self.dataCache = QRCode.createData(self.typeNumber, self.errorCorrectLevel, self.dataList) - self.mapData(self.dataCache, maskPattern) - - def setupPositionProbePattern(self, row, col): - - for r in range(-1, 8): - - if (row + r <= -1 or self.moduleCount <= row + r): continue - - for c in range(-1, 8): - - if (col + c <= -1 or self.moduleCount <= col + c): continue - - if ( (0 <= r and r <= 6 and (c == 0 or c == 6) ) - or (0 <= c and c <= 6 and (r == 0 or r == 6) ) - or (2 <= r and r <= 4 and 2 <= c and c <= 4) ): - self.modules[row + r][col + c] = True; - else: - self.modules[row + r][col + c] = False; - - def getBestMaskPattern(self): - - minLostPoint = 0 - pattern = 0 - - for i in range(8): - - self.makeImpl(True, i); - - lostPoint = QRUtil.getLostPoint(self); - - if (i == 0 or minLostPoint > lostPoint): - minLostPoint = lostPoint - pattern = i - - return pattern - - - def setupTimingPattern(self): - - for r in range(8, self.moduleCount - 8): - if (self.modules[r][6] != None): - continue - self.modules[r][6] = (r % 2 == 0) - - for c in range(8, self.moduleCount - 8): - if (self.modules[6][c] != None): - continue - self.modules[6][c] = (c % 2 == 0) - - def setupPositionAdjustPattern(self): - - pos = QRUtil.getPatternPosition(self.typeNumber) - - for i in range(len(pos)): - - for j in range(len(pos)): - - row = pos[i] - col = pos[j] - - if (self.modules[row][col] != None): - continue - - for r in range(-2, 3): - - for c in range(-2, 3): - - if (r == -2 or r == 2 or c == -2 or c == 2 or (r == 0 and c == 0) ): - self.modules[row + r][col + c] = True - else: - self.modules[row + r][col + c] = False - - def setupTypeNumber(self, test): - - bits = QRUtil.getBCHTypeNumber(self.typeNumber) - - for i in range(18): - mod = (not test and ( (bits >> i) & 1) == 1) - self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; - - for i in range(18): - mod = (not test and ( (bits >> i) & 1) == 1) - self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; - - def setupTypeInfo(self, test, maskPattern): - - data = (self.errorCorrectLevel << 3) | maskPattern - bits = QRUtil.getBCHTypeInfo(data) - - #// vertical - for i in range(15): - - mod = (not test and ( (bits >> i) & 1) == 1) - - if (i < 6): - self.modules[i][8] = mod - elif (i < 8): - self.modules[i + 1][8] = mod - else: - self.modules[self.moduleCount - 15 + i][8] = mod - - #// horizontal - for i in range(15): - - mod = (not test and ( (bits >> i) & 1) == 1); - - if (i < 8): - self.modules[8][self.moduleCount - i - 1] = mod - elif (i < 9): - self.modules[8][15 - i - 1 + 1] = mod - else: - self.modules[8][15 - i - 1] = mod - - #// fixed module - self.modules[self.moduleCount - 8][8] = (not test) - - def mapData(self, data, maskPattern): - - inc = -1 - row = self.moduleCount - 1 - bitIndex = 7 - byteIndex = 0 - - for col in range(self.moduleCount - 1, 0, -2): - - if (col == 6): col-=1 - - while (True): - - for c in range(2): - - if (self.modules[row][col - c] == None): - - dark = False - - if (byteIndex < len(data)): - dark = ( ( (data[byteIndex] >> bitIndex) & 1) == 1) - - mask = QRUtil.getMask(maskPattern, row, col - c) - - if (mask): - dark = not dark - - self.modules[row][col - c] = dark - bitIndex-=1 - - if (bitIndex == -1): - byteIndex+=1 - bitIndex = 7 - - row += inc - - if (row < 0 or self.moduleCount <= row): - row -= inc - inc = -inc - break - PAD0 = 0xEC - PAD1 = 0x11 - - @staticmethod - def createData(typeNumber, errorCorrectLevel, dataList): - - rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel) - - buffer = QRBitBuffer(); - - for i in range(len(dataList)): - data = dataList[i] - buffer.put(data.mode, 4) - buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) ) - data.write(buffer) - - #// calc num max data. - totalDataCount = 0; - for i in range(len(rsBlocks)): - totalDataCount += rsBlocks[i].dataCount - - if (buffer.getLengthInBits() > totalDataCount * 8): - raise Exception("code length overflow. (" - + buffer.getLengthInBits() - + ">" - + totalDataCount * 8 - + ")") - - #// end code - if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): - buffer.put(0, 4) - - #// padding - while (buffer.getLengthInBits() % 8 != 0): - buffer.putBit(False) - - #// padding - while (True): - - if (buffer.getLengthInBits() >= totalDataCount * 8): - break - buffer.put(QRCode.PAD0, 8) - - if (buffer.getLengthInBits() >= totalDataCount * 8): - break - buffer.put(QRCode.PAD1, 8) - - return QRCode.createBytes(buffer, rsBlocks) - - @staticmethod - def createBytes(buffer, rsBlocks): - - offset = 0 - - maxDcCount = 0 - maxEcCount = 0 - - dcdata = [0 for x in range(len(rsBlocks))] - ecdata = [0 for x in range(len(rsBlocks))] - - for r in range(len(rsBlocks)): - - dcCount = rsBlocks[r].dataCount - ecCount = rsBlocks[r].totalCount - dcCount - - maxDcCount = max(maxDcCount, dcCount) - maxEcCount = max(maxEcCount, ecCount) - - dcdata[r] = [0 for x in range(dcCount)] - - for i in range(len(dcdata[r])): - dcdata[r][i] = 0xff & buffer.buffer[i + offset] - offset += dcCount - - rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) - rawPoly = QRPolynomial(dcdata[r], rsPoly.getLength() - 1) - - modPoly = rawPoly.mod(rsPoly) - ecdata[r] = [0 for x in range(rsPoly.getLength()-1)] - for i in range(len(ecdata[r])): - modIndex = i + modPoly.getLength() - len(ecdata[r]) - if (modIndex >= 0): - ecdata[r][i] = modPoly.get(modIndex) - else: - ecdata[r][i] = 0 - - totalCodeCount = 0 - for i in range(len(rsBlocks)): - totalCodeCount += rsBlocks[i].totalCount - - data = [None for x in range(totalCodeCount)] - index = 0 - - for i in range(maxDcCount): - for r in range(len(rsBlocks)): - if (i < len(dcdata[r])): - data[index] = dcdata[r][i] - index+=1 - - for i in range(maxEcCount): - for r in range(len(rsBlocks)): - if (i < len(ecdata[r])): - data[index] = ecdata[r][i] - index+=1 - - return data - - -class QRMode: - MODE_NUMBER = 1 << 0 - MODE_ALPHA_NUM = 1 << 1 - MODE_8BIT_BYTE = 1 << 2 - MODE_KANJI = 1 << 3 - -class QRErrorCorrectLevel: - L = 1 - M = 0 - Q = 3 - H = 2 - -class QRMaskPattern: - PATTERN000 = 0 - PATTERN001 = 1 - PATTERN010 = 2 - PATTERN011 = 3 - PATTERN100 = 4 - PATTERN101 = 5 - PATTERN110 = 6 - PATTERN111 = 7 - -class QRUtil(object): - PATTERN_POSITION_TABLE = [ - [], - [6, 18], - [6, 22], - [6, 26], - [6, 30], - [6, 34], - [6, 22, 38], - [6, 24, 42], - [6, 26, 46], - [6, 28, 50], - [6, 30, 54], - [6, 32, 58], - [6, 34, 62], - [6, 26, 46, 66], - [6, 26, 48, 70], - [6, 26, 50, 74], - [6, 30, 54, 78], - [6, 30, 56, 82], - [6, 30, 58, 86], - [6, 34, 62, 90], - [6, 28, 50, 72, 94], - [6, 26, 50, 74, 98], - [6, 30, 54, 78, 102], - [6, 28, 54, 80, 106], - [6, 32, 58, 84, 110], - [6, 30, 58, 86, 114], - [6, 34, 62, 90, 118], - [6, 26, 50, 74, 98, 122], - [6, 30, 54, 78, 102, 126], - [6, 26, 52, 78, 104, 130], - [6, 30, 56, 82, 108, 134], - [6, 34, 60, 86, 112, 138], - [6, 30, 58, 86, 114, 142], - [6, 34, 62, 90, 118, 146], - [6, 30, 54, 78, 102, 126, 150], - [6, 24, 50, 76, 102, 128, 154], - [6, 28, 54, 80, 106, 132, 158], - [6, 32, 58, 84, 110, 136, 162], - [6, 26, 54, 82, 110, 138, 166], - [6, 30, 58, 86, 114, 142, 170] - ] - - G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) - G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) - G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) - - @staticmethod - def getBCHTypeInfo(data): - d = data << 10; - while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): - d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) - - return ( (data << 10) | d) ^ QRUtil.G15_MASK - @staticmethod - def getBCHTypeNumber(data): - d = data << 12; - while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): - d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) - return (data << 12) | d - @staticmethod - def getBCHDigit(data): - digit = 0; - while (data != 0): - digit += 1 - data >>= 1 - return digit - @staticmethod - def getPatternPosition(typeNumber): - return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1] - @staticmethod - def getMask(maskPattern, i, j): - if maskPattern == QRMaskPattern.PATTERN000 : return (i + j) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN001 : return i % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN010 : return j % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN011 : return (i + j) % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN100 : return (math.floor(i / 2) + math.floor(j / 3) ) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0 - raise Exception("bad maskPattern:" + maskPattern); - @staticmethod - def getErrorCorrectPolynomial(errorCorrectLength): - a = QRPolynomial([1], 0); - for i in range(errorCorrectLength): - a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) - return a - @staticmethod - def getLengthInBits(mode, type): - - if 1 <= type and type < 10: - - #// 1 - 9 - - if mode == QRMode.MODE_NUMBER : return 10 - if mode == QRMode.MODE_ALPHA_NUM : return 9 - if mode == QRMode.MODE_8BIT_BYTE : return 8 - if mode == QRMode.MODE_KANJI : return 8 - raise Exception("mode:" + mode) - - elif (type < 27): - - #// 10 - 26 - - if mode == QRMode.MODE_NUMBER : return 12 - if mode == QRMode.MODE_ALPHA_NUM : return 11 - if mode == QRMode.MODE_8BIT_BYTE : return 16 - if mode == QRMode.MODE_KANJI : return 10 - raise Exception("mode:" + mode) - - elif (type < 41): - - #// 27 - 40 - - if mode == QRMode.MODE_NUMBER : return 14 - if mode == QRMode.MODE_ALPHA_NUM : return 13 - if mode == QRMode.MODE_8BIT_BYTE : return 16 - if mode == QRMode.MODE_KANJI : return 12 - raise Exception("mode:" + mode) - - else: - raise Exception("type:" + type) - @staticmethod - def getLostPoint(qrCode): - - moduleCount = qrCode.getModuleCount(); - - lostPoint = 0; - - #// LEVEL1 - - for row in range(moduleCount): - - for col in range(moduleCount): - - sameCount = 0; - dark = qrCode.isDark(row, col); - - for r in range(-1, 2): - - if (row + r < 0 or moduleCount <= row + r): - continue - - for c in range(-1, 2): - - if (col + c < 0 or moduleCount <= col + c): - continue - if (r == 0 and c == 0): - continue - - if (dark == qrCode.isDark(row + r, col + c) ): - sameCount+=1 - if (sameCount > 5): - lostPoint += (3 + sameCount - 5) - - #// LEVEL2 - - for row in range(moduleCount - 1): - for col in range(moduleCount - 1): - count = 0; - if (qrCode.isDark(row, col ) ): count+=1 - if (qrCode.isDark(row + 1, col ) ): count+=1 - if (qrCode.isDark(row, col + 1) ): count+=1 - if (qrCode.isDark(row + 1, col + 1) ): count+=1 - if (count == 0 or count == 4): - lostPoint += 3 - - #// LEVEL3 - - for row in range(moduleCount): - for col in range(moduleCount - 6): - if (qrCode.isDark(row, col) - and not qrCode.isDark(row, col + 1) - and qrCode.isDark(row, col + 2) - and qrCode.isDark(row, col + 3) - and qrCode.isDark(row, col + 4) - and not qrCode.isDark(row, col + 5) - and qrCode.isDark(row, col + 6) ): - lostPoint += 40 - - for col in range(moduleCount): - for row in range(moduleCount - 6): - if (qrCode.isDark(row, col) - and not qrCode.isDark(row + 1, col) - and qrCode.isDark(row + 2, col) - and qrCode.isDark(row + 3, col) - and qrCode.isDark(row + 4, col) - and not qrCode.isDark(row + 5, col) - and qrCode.isDark(row + 6, col) ): - lostPoint += 40 - - #// LEVEL4 - - darkCount = 0; - - for col in range(moduleCount): - for row in range(moduleCount): - if (qrCode.isDark(row, col) ): - darkCount+=1 - - ratio = abs(100 * darkCount / moduleCount / moduleCount - 50) / 5 - lostPoint += ratio * 10 - - return lostPoint - -class QRMath: - - @staticmethod - def glog(n): - if (n < 1): - raise Exception("glog(" + n + ")") - return LOG_TABLE[n]; - @staticmethod - def gexp(n): - while n < 0: - n += 255 - while n >= 256: - n -= 255 - return EXP_TABLE[n]; - -EXP_TABLE = [x for x in range(256)] - -LOG_TABLE = [x for x in range(256)] - -for i in range(8): - EXP_TABLE[i] = 1 << i; - -for i in range(8, 256): - EXP_TABLE[i] = EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8] - -for i in range(255): - LOG_TABLE[EXP_TABLE[i] ] = i - -class QRPolynomial: - - def __init__(self, num, shift): - - if (len(num) == 0): - raise Exception(num.length + "/" + shift) - - offset = 0 - - while offset < len(num) and num[offset] == 0: - offset += 1 - - self.num = [0 for x in range(len(num)-offset+shift)] - for i in range(len(num) - offset): - self.num[i] = num[i + offset] - - - def get(self, index): - return self.num[index] - def getLength(self): - return len(self.num) - def multiply(self, e): - num = [0 for x in range(self.getLength() + e.getLength() - 1)]; - - for i in range(self.getLength()): - for j in range(e.getLength()): - num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) - - return QRPolynomial(num, 0); - def mod(self, e): - - if (self.getLength() - e.getLength() < 0): - return self; - - ratio = QRMath.glog(self.get(0) ) - QRMath.glog(e.get(0) ) - - num = [0 for x in range(self.getLength())] - - for i in range(self.getLength()): - num[i] = self.get(i); - - for i in range(e.getLength()): - num[i] ^= QRMath.gexp(QRMath.glog(e.get(i) ) + ratio) - - # recursive call - return QRPolynomial(num, 0).mod(e); - -class QRRSBlock: - - RS_BLOCK_TABLE = [ - - #// L - #// M - #// Q - #// H - - #// 1 - [1, 26, 19], - [1, 26, 16], - [1, 26, 13], - [1, 26, 9], - - #// 2 - [1, 44, 34], - [1, 44, 28], - [1, 44, 22], - [1, 44, 16], - - #// 3 - [1, 70, 55], - [1, 70, 44], - [2, 35, 17], - [2, 35, 13], - - #// 4 - [1, 100, 80], - [2, 50, 32], - [2, 50, 24], - [4, 25, 9], - - #// 5 - [1, 134, 108], - [2, 67, 43], - [2, 33, 15, 2, 34, 16], - [2, 33, 11, 2, 34, 12], - - #// 6 - [2, 86, 68], - [4, 43, 27], - [4, 43, 19], - [4, 43, 15], - - #// 7 - [2, 98, 78], - [4, 49, 31], - [2, 32, 14, 4, 33, 15], - [4, 39, 13, 1, 40, 14], - - #// 8 - [2, 121, 97], - [2, 60, 38, 2, 61, 39], - [4, 40, 18, 2, 41, 19], - [4, 40, 14, 2, 41, 15], - - #// 9 - [2, 146, 116], - [3, 58, 36, 2, 59, 37], - [4, 36, 16, 4, 37, 17], - [4, 36, 12, 4, 37, 13], - - #// 10 - [2, 86, 68, 2, 87, 69], - [4, 69, 43, 1, 70, 44], - [6, 43, 19, 2, 44, 20], - [6, 43, 15, 2, 44, 16], - - # 11 - [4, 101, 81], - [1, 80, 50, 4, 81, 51], - [4, 50, 22, 4, 51, 23], - [3, 36, 12, 8, 37, 13], - - # 12 - [2, 116, 92, 2, 117, 93], - [6, 58, 36, 2, 59, 37], - [4, 46, 20, 6, 47, 21], - [7, 42, 14, 4, 43, 15], - - # 13 - [4, 133, 107], - [8, 59, 37, 1, 60, 38], - [8, 44, 20, 4, 45, 21], - [12, 33, 11, 4, 34, 12], - - # 14 - [3, 145, 115, 1, 146, 116], - [4, 64, 40, 5, 65, 41], - [11, 36, 16, 5, 37, 17], - [11, 36, 12, 5, 37, 13], - - # 15 - [5, 109, 87, 1, 110, 88], - [5, 65, 41, 5, 66, 42], - [5, 54, 24, 7, 55, 25], - [11, 36, 12], - - # 16 - [5, 122, 98, 1, 123, 99], - [7, 73, 45, 3, 74, 46], - [15, 43, 19, 2, 44, 20], - [3, 45, 15, 13, 46, 16], - - # 17 - [1, 135, 107, 5, 136, 108], - [10, 74, 46, 1, 75, 47], - [1, 50, 22, 15, 51, 23], - [2, 42, 14, 17, 43, 15], - - # 18 - [5, 150, 120, 1, 151, 121], - [9, 69, 43, 4, 70, 44], - [17, 50, 22, 1, 51, 23], - [2, 42, 14, 19, 43, 15], - - # 19 - [3, 141, 113, 4, 142, 114], - [3, 70, 44, 11, 71, 45], - [17, 47, 21, 4, 48, 22], - [9, 39, 13, 16, 40, 14], - - # 20 - [3, 135, 107, 5, 136, 108], - [3, 67, 41, 13, 68, 42], - [15, 54, 24, 5, 55, 25], - [15, 43, 15, 10, 44, 16], - - # 21 - [4, 144, 116, 4, 145, 117], - [17, 68, 42], - [17, 50, 22, 6, 51, 23], - [19, 46, 16, 6, 47, 17], - - # 22 - [2, 139, 111, 7, 140, 112], - [17, 74, 46], - [7, 54, 24, 16, 55, 25], - [34, 37, 13], - - # 23 - [4, 151, 121, 5, 152, 122], - [4, 75, 47, 14, 76, 48], - [11, 54, 24, 14, 55, 25], - [16, 45, 15, 14, 46, 16], - - # 24 - [6, 147, 117, 4, 148, 118], - [6, 73, 45, 14, 74, 46], - [11, 54, 24, 16, 55, 25], - [30, 46, 16, 2, 47, 17], - - # 25 - [8, 132, 106, 4, 133, 107], - [8, 75, 47, 13, 76, 48], - [7, 54, 24, 22, 55, 25], - [22, 45, 15, 13, 46, 16], - - # 26 - [10, 142, 114, 2, 143, 115], - [19, 74, 46, 4, 75, 47], - [28, 50, 22, 6, 51, 23], - [33, 46, 16, 4, 47, 17], - - # 27 - [8, 152, 122, 4, 153, 123], - [22, 73, 45, 3, 74, 46], - [8, 53, 23, 26, 54, 24], - [12, 45, 15, 28, 46, 16], - - # 28 - [3, 147, 117, 10, 148, 118], - [3, 73, 45, 23, 74, 46], - [4, 54, 24, 31, 55, 25], - [11, 45, 15, 31, 46, 16], - - # 29 - [7, 146, 116, 7, 147, 117], - [21, 73, 45, 7, 74, 46], - [1, 53, 23, 37, 54, 24], - [19, 45, 15, 26, 46, 16], - - # 30 - [5, 145, 115, 10, 146, 116], - [19, 75, 47, 10, 76, 48], - [15, 54, 24, 25, 55, 25], - [23, 45, 15, 25, 46, 16], - - # 31 - [13, 145, 115, 3, 146, 116], - [2, 74, 46, 29, 75, 47], - [42, 54, 24, 1, 55, 25], - [23, 45, 15, 28, 46, 16], - - # 32 - [17, 145, 115], - [10, 74, 46, 23, 75, 47], - [10, 54, 24, 35, 55, 25], - [19, 45, 15, 35, 46, 16], - - # 33 - [17, 145, 115, 1, 146, 116], - [14, 74, 46, 21, 75, 47], - [29, 54, 24, 19, 55, 25], - [11, 45, 15, 46, 46, 16], - - # 34 - [13, 145, 115, 6, 146, 116], - [14, 74, 46, 23, 75, 47], - [44, 54, 24, 7, 55, 25], - [59, 46, 16, 1, 47, 17], - - # 35 - [12, 151, 121, 7, 152, 122], - [12, 75, 47, 26, 76, 48], - [39, 54, 24, 14, 55, 25], - [22, 45, 15, 41, 46, 16], - - # 36 - [6, 151, 121, 14, 152, 122], - [6, 75, 47, 34, 76, 48], - [46, 54, 24, 10, 55, 25], - [2, 45, 15, 64, 46, 16], - - # 37 - [17, 152, 122, 4, 153, 123], - [29, 74, 46, 14, 75, 47], - [49, 54, 24, 10, 55, 25], - [24, 45, 15, 46, 46, 16], - - # 38 - [4, 152, 122, 18, 153, 123], - [13, 74, 46, 32, 75, 47], - [48, 54, 24, 14, 55, 25], - [42, 45, 15, 32, 46, 16], - - # 39 - [20, 147, 117, 4, 148, 118], - [40, 75, 47, 7, 76, 48], - [43, 54, 24, 22, 55, 25], - [10, 45, 15, 67, 46, 16], - - # 40 - [19, 148, 118, 6, 149, 119], - [18, 75, 47, 31, 76, 48], - [34, 54, 24, 34, 55, 25], - [20, 45, 15, 61, 46, 16] - - ] - - def __init__(self, totalCount, dataCount): - self.totalCount = totalCount - self.dataCount = dataCount - - @staticmethod - def getRSBlocks(typeNumber, errorCorrectLevel): - rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel); - if rsBlock == None: - raise Exception("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel) - - length = len(rsBlock) / 3 - - list = [] - - for i in range(length): - - count = rsBlock[i * 3 + 0] - totalCount = rsBlock[i * 3 + 1] - dataCount = rsBlock[i * 3 + 2] - - for j in range(count): - list.append(QRRSBlock(totalCount, dataCount)) - - return list; - - @staticmethod - def getRsBlockTable(typeNumber, errorCorrectLevel): - if errorCorrectLevel == QRErrorCorrectLevel.L: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; - elif errorCorrectLevel == QRErrorCorrectLevel.M: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; - elif errorCorrectLevel == QRErrorCorrectLevel.Q: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; - elif errorCorrectLevel == QRErrorCorrectLevel.H: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; - else: - return None; - -class QRBitBuffer: - def __init__(self): - self.buffer = [] - self.length = 0 - def __repr__(self): - return ".".join([str(n) for n in self.buffer]) - def get(self, index): - bufIndex = math.floor(index / 8) - val = ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 - print "get ", val - return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 - def put(self, num, length): - for i in range(length): - self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) - def getLengthInBits(self): - return self.length - def putBit(self, bit): - bufIndex = self.length // 8 - if len(self.buffer) <= bufIndex: - self.buffer.append(0) - if bit: - self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) - self.length+=1 diff --git a/lib/qrscanner.py b/lib/qrscanner.py @@ -1,83 +0,0 @@ -from util import print_error - -try: - import zbar -except ImportError: - print_error("Install zbar package to enable QR scans") - zbar = None - -from urlparse import urlparse, parse_qs - -def is_available(): - if not zbar: - return False - - try: - proc = zbar.Processor() - proc.init() - except zbar.SystemError: - # Cannot open video device - return False - - return True - -def scan_qr(): - proc = zbar.Processor() - proc.init() - proc.visible = True - - while True: - try: - proc.process_one() - except: - # User closed the preview window - return {} - - for r in proc.results: - if str(r.type) != 'QRCODE': - continue - - return parse_uri(r.data) - -def parse_uri(uri): - if ':' not in uri: - # It's just an address (not BIP21) - return {'address': uri} - - if '//' not in uri: - # Workaround for urlparse, it don't handle bitcoin: URI properly - uri = uri.replace(':', '://') - - uri = urlparse(uri) - result = {'address': uri.netloc} - - if uri.path.startswith('?'): - params = parse_qs(uri.path[1:]) - else: - params = parse_qs(uri.path) - - for k,v in params.items(): - if k in ('amount', 'label', 'message'): - result[k] = v[0] - - return result - -if __name__ == '__main__': - # Run some tests - - assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') == - {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) - - assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') == - {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) - - assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') == - {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) - - assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') == - {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) - - assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') == - {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'}) - - diff --git a/lib/qt_console.py b/lib/qt_console.py @@ -1,296 +0,0 @@ -# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget - -import sys, os, re -import traceback -from PyQt4 import QtCore -from PyQt4 import QtGui -import util - - - -class Console(QtGui.QPlainTextEdit): - def __init__(self, prompt='>> ', startup_message='', parent=None): - QtGui.QPlainTextEdit.__init__(self, parent) - - self.prompt = prompt - self.history = [] - self.namespace = {} - self.construct = [] - - self.setGeometry(50, 75, 600, 400) - self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere) - self.setUndoRedoEnabled(False) - self.document().setDefaultFont(QtGui.QFont("monospace", 10, QtGui.QFont.Normal)) - self.showMessage(startup_message) - - self.updateNamespace({'run':self.run_script}) - self.set_json(False) - - def set_json(self, b): - self.is_json = b - - def run_script(self, filename): - with open(filename) as f: - script = f.read() - result = eval(script, self.namespace, self.namespace) - - - - def updateNamespace(self, namespace): - self.namespace.update(namespace) - - def showMessage(self, message): - self.appendPlainText(message) - self.newPrompt() - - def clear(self): - self.setPlainText('') - self.newPrompt() - - def newPrompt(self): - if self.construct: - prompt = '.' * len(self.prompt) - else: - prompt = self.prompt - - self.completions_pos = self.textCursor().position() - self.completions_visible = False - - self.appendPlainText(prompt) - self.moveCursor(QtGui.QTextCursor.End) - - def getCommand(self): - doc = self.document() - curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text()) - curr_line = curr_line.rstrip() - curr_line = curr_line[len(self.prompt):] - return curr_line - - def setCommand(self, command): - if self.getCommand() == command: - return - self.moveCursor(QtGui.QTextCursor.End) - self.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor) - for i in range(len(self.prompt)): - self.moveCursor(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor) - self.textCursor().removeSelectedText() - self.textCursor().insertText(command) - self.moveCursor(QtGui.QTextCursor.End) - - - def show_completions(self, completions): - if self.completions_visible: - self.hide_completions() - - c = self.textCursor() - c.setPosition(self.completions_pos) - - completions = map(lambda x: x.split('.')[-1], completions) - t = '\n' + ' '.join(completions) - if len(t) > 500: - t = t[:500] + '...' - c.insertText(t) - self.completions_end = c.position() - - self.moveCursor(QtGui.QTextCursor.End) - self.completions_visible = True - - - def hide_completions(self): - if not self.completions_visible: - return - c = self.textCursor() - c.setPosition(self.completions_pos) - l = self.completions_end - self.completions_pos - for x in range(l): c.deleteChar() - - self.moveCursor(QtGui.QTextCursor.End) - self.completions_visible = False - - - def getConstruct(self, command): - if self.construct: - prev_command = self.construct[-1] - self.construct.append(command) - if not prev_command and not command: - ret_val = '\n'.join(self.construct) - self.construct = [] - return ret_val - else: - return '' - else: - if command and command[-1] == (':'): - self.construct.append(command) - return '' - else: - return command - - def getHistory(self): - return self.history - - def setHisory(self, history): - self.history = history - - def addToHistory(self, command): - if command and (not self.history or self.history[-1] != command): - self.history.append(command) - self.history_index = len(self.history) - - def getPrevHistoryEntry(self): - if self.history: - self.history_index = max(0, self.history_index - 1) - return self.history[self.history_index] - return '' - - def getNextHistoryEntry(self): - if self.history: - hist_len = len(self.history) - self.history_index = min(hist_len, self.history_index + 1) - if self.history_index < hist_len: - return self.history[self.history_index] - return '' - - def getCursorPosition(self): - return self.textCursor().columnNumber() - len(self.prompt) - - def setCursorPosition(self, position): - self.moveCursor(QtGui.QTextCursor.StartOfLine) - for i in range(len(self.prompt) + position): - self.moveCursor(QtGui.QTextCursor.Right) - - def runCommand(self): - command = self.getCommand() - self.addToHistory(command) - - command = self.getConstruct(command) - - if command: - tmp_stdout = sys.stdout - - class stdoutProxy(): - def __init__(self, write_func): - self.write_func = write_func - self.skip = False - - def flush(self): - pass - - def write(self, text): - if not self.skip: - stripped_text = text.rstrip('\n') - self.write_func(stripped_text) - QtCore.QCoreApplication.processEvents() - self.skip = not self.skip - - if command == 'help()': - self.appendPlainText("no help here!") - self.newPrompt() - return - - sys.stdout = stdoutProxy(self.appendPlainText) - try: - try: - result = eval(command, self.namespace, self.namespace) - if result != None: - if self.is_json: - util.print_json(result) - else: - self.appendPlainText(repr(result)) - except SyntaxError: - exec command in self.namespace - except SystemExit: - self.close() - except: - traceback_lines = traceback.format_exc().split('\n') - # Remove traceback mentioning this file, and a linebreak - for i in (3,2,1,-1): - traceback_lines.pop(i) - self.appendPlainText('\n'.join(traceback_lines)) - sys.stdout = tmp_stdout - self.newPrompt() - self.set_json(False) - - - def keyPressEvent(self, event): - if event.key() == QtCore.Qt.Key_Tab: - self.completions() - return - - self.hide_completions() - - if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): - self.runCommand() - return - if event.key() == QtCore.Qt.Key_Home: - self.setCursorPosition(0) - return - if event.key() == QtCore.Qt.Key_PageUp: - return - elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace): - if self.getCursorPosition() == 0: - return - elif event.key() == QtCore.Qt.Key_Up: - self.setCommand(self.getPrevHistoryEntry()) - return - elif event.key() == QtCore.Qt.Key_Down: - self.setCommand(self.getNextHistoryEntry()) - return - elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier: - self.clear() - - super(Console, self).keyPressEvent(event) - - - - def completions(self): - cmd = self.getCommand() - lastword = re.split(' |\(|\)',cmd)[-1] - beginning = cmd[0:-len(lastword)] - - path = lastword.split('.') - ns = self.namespace.keys() - - if len(path) == 1: - ns = ns - prefix = '' - else: - obj = self.namespace.get(path[0]) - prefix = path[0] + '.' - ns = dir(obj) - - - completions = [] - for x in ns: - if x[0] == '_':continue - xx = prefix + x - if xx.startswith(lastword): - completions.append(xx) - completions.sort() - - if not completions: - self.hide_completions() - elif len(completions) == 1: - self.hide_completions() - self.setCommand(beginning + completions[0]) - else: - # find common prefix - p = os.path.commonprefix(completions) - if len(p)>len(lastword): - self.hide_completions() - self.setCommand(beginning + p) - else: - self.show_completions(completions) - - -welcome_message = ''' - --------------------------------------------------------------- - Welcome to a primitive Python interpreter. - --------------------------------------------------------------- -''' - -if __name__ == '__main__': - app = QtGui.QApplication(sys.argv) - console = Console(startup_message=welcome_message) - console.updateNamespace({'myVar1' : app, 'myVar2' : 1234}) - console.show(); - sys.exit(app.exec_()) diff --git a/setup.py b/setup.py @@ -45,7 +45,7 @@ data_files += [ setup(name = "Electrum", version = version.ELECTRUM_VERSION, install_requires = ['slowaes','ecdsa'], - package_dir = {'electrum': 'lib'}, + package_dir = {'electrum': 'lib', 'electrumGUI': 'gui'}, scripts= ['electrum'], data_files = data_files, py_modules = ['electrum.version', @@ -53,28 +53,28 @@ setup(name = "Electrum", 'electrum.wallet_bitkey', 'electrum.wallet_factory', 'electrum.interface', - 'electrum.gui', 'electrum.commands', - 'electrum.qt_console', - 'electrum.gui_qt', - 'electrum.gui_lite', - 'electrum.gui_text', - 'electrum.exchange_rate', - 'electrum.icons_rc', 'electrum.mnemonic', - 'electrum.pyqrnative', - 'electrum.qrscanner', - 'electrum.history_widget', - 'electrum.receiving_widget', 'electrum.simple_config', 'electrum.socks', - 'electrum.bmp', 'electrum.msqr', 'electrum.util', 'electrum.bitcoin', 'electrum.deserialize', 'electrum.verifier', - 'electrum.i18n'], + 'electrumGUI.gui', + 'electrumGUI.qt_console', + 'electrumGUI.gui_qt', + 'electrumGUI.gui_lite', + 'electrumGUI.gui_text', + 'electrumGUI.exchange_rate', + 'electrumGUI.icons_rc', + 'electrumGUI.pyqrnative', + 'electrumGUI.qrscanner', + 'electrumGUI.history_widget', + 'electrumGUI.receiving_widget', + 'electrumGUI.bmp', + 'electrumGUI.i18n'], description = "Lightweight Bitcoin Wallet", author = "thomasv", author_email = "thomasv@gitorious",