make a regular gui module for android

This commit is contained in:
ThomasV 2012-11-18 11:34:52 +01:00
parent d929c4d2dd
commit 2d13107897
8 changed files with 193 additions and 214 deletions

136
electrum
View File

@ -17,7 +17,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import re import re
import sys import sys, os
import optparse import optparse
try: try:
@ -121,10 +121,7 @@ def prompt_password(prompt, confirm=True):
password = None password = None
return password return password
def parse_args():
if __name__ == '__main__':
usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands)) usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands))
parser = optparse.OptionParser(prog=usage) parser = optparse.OptionParser(prog=usage)
parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text") parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text")
@ -139,12 +136,20 @@ if __name__ == '__main__':
parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h") parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h")
parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http") parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
options, args = parser.parse_args() return parser.parse_args()
if __name__ == '__main__':
options, args = parse_args()
set_verbosity(options.verbose) set_verbosity(options.verbose)
# config is an object passed to the various constructors (wallet, interface, gui) # config is an object passed to the various constructors (wallet, interface, gui)
config = SimpleConfig(options) if 'ANDROID_DATA' in os.environ:
config = SimpleConfig({'wallet_path':"/sdcard/electrum.dat", 'blockchain_headers_path':'/sdcard', 'gui':'android'})
else:
config = SimpleConfig(eval(str(options)))
wallet = Wallet(config) wallet = Wallet(config)
if len(args)==0: if len(args)==0:
@ -181,6 +186,11 @@ if __name__ == '__main__':
import lib.gui_text as gui import lib.gui_text as gui
except ImportError: except ImportError:
import electrum.gui_text as gui import electrum.gui_text as gui
elif pref_gui == 'android':
try:
import lib.gui_android as gui
except ImportError:
import electrum.gui_android as gui
else: else:
sys.exit("Error: Unknown GUI: " + pref_gui ) sys.exit("Error: Unknown GUI: " + pref_gui )
@ -201,9 +211,9 @@ if __name__ == '__main__':
found = config.wallet_file_exists found = config.wallet_file_exists
if not found: if not found:
found = gui.restore_or_create() found = gui.restore_or_create()
except SystemExit, e: except SystemExit(e):
exit(e) exit(e)
except BaseException, e: except BaseException(e):
import traceback import traceback
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
#gui.show_message(e.message) #gui.show_message(e.message)
@ -222,8 +232,8 @@ if __name__ == '__main__':
cmd = 'help' cmd = 'help'
if not config.wallet_file_exists and cmd not in ['help','create','restore']: if not config.wallet_file_exists and cmd not in ['help','create','restore']:
print "Error: Wallet file not found." print("Error: Wallet file not found.")
print "Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option" print("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
sys.exit(0) sys.exit(0)
if cmd in ['create', 'restore']: if cmd in ['create', 'restore']:
@ -267,30 +277,30 @@ if __name__ == '__main__':
verifier = WalletVerifier(interface, config) verifier = WalletVerifier(interface, config)
wallet.set_verifier(verifier) wallet.set_verifier(verifier)
print "Recovering wallet..." print("Recovering wallet...")
WalletSynchronizer(wallet, config).start() WalletSynchronizer(wallet, config).start()
wallet.up_to_date_event.clear() wallet.up_to_date_event.clear()
wallet.up_to_date = False wallet.up_to_date = False
wallet.update() wallet.update()
if wallet.is_found(): if wallet.is_found():
print "Recovery successful" print("Recovery successful")
else: else:
print "Warning: Found no history for this wallet" print("Warning: Found no history for this wallet")
else: else:
wallet.synchronize() wallet.synchronize()
wallet.fill_addressbook() wallet.fill_addressbook()
wallet.save() wallet.save()
print "Wallet saved in '%s'"%wallet.config.path print("Wallet saved in '%s'"%wallet.config.path)
else: else:
wallet.new_seed(None) wallet.new_seed(None)
wallet.init_mpk( wallet.seed ) wallet.init_mpk( wallet.seed )
wallet.synchronize() # there is no wallet thread wallet.synchronize() # there is no wallet thread
wallet.save() wallet.save()
print "Your wallet generation seed is: " + wallet.seed print("Your wallet generation seed is: " + wallet.seed)
print "Please keep it in a safe place; if you lose it, you will not be able to restore your wallet." print("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")
print "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:" print("Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:")
print "\""+' '.join(mnemonic_encode(wallet.seed))+"\"" print("\""+' '.join(mnemonic_encode(wallet.seed))+"\"")
print "Wallet saved in '%s'"%wallet.config.path print("Wallet saved in '%s'"%wallet.config.path)
if password: if password:
wallet.update_password(wallet.seed, None, password) wallet.update_password(wallet.seed, None, password)
@ -328,9 +338,9 @@ if __name__ == '__main__':
# important warning # important warning
if cmd=='addresses' and options.show_keys: if cmd=='addresses' and options.show_keys:
print "WARNING: ALL your private keys are secret." print("WARNING: ALL your private keys are secret.")
print "Exposing a single private key can compromise your entire wallet!" print("Exposing a single private key can compromise your entire wallet!")
print "In particular, DO NOT use 'redeem private key' services proposed by third parties." print("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
# commands needing password # commands needing password
if cmd in protected_commands or ( cmd=='addresses' and options.show_keys): if cmd in protected_commands or ( cmd=='addresses' and options.show_keys):
@ -351,23 +361,23 @@ if __name__ == '__main__':
try: try:
wallet.import_key(keypair,password) wallet.import_key(keypair,password)
wallet.save() wallet.save()
print "Keypair imported" print("Keypair imported")
except BaseException, e: except BaseException(e):
print_error("Error: Keypair import failed: " + str(e)) print_error("Error: Keypair import failed: " + str(e))
if cmd == 'help': if cmd == 'help':
cmd2 = firstarg cmd2 = firstarg
if cmd2 not in known_commands: if cmd2 not in known_commands:
parser.print_help() parser.print_help()
print "Type 'electrum help <command>' to see the help for a specific command" print("Type 'electrum help <command>' to see the help for a specific command")
print "Type 'electrum --help' to see the list of options" print("Type 'electrum --help' to see the list of options")
print "List of commands:", ', '.join(known_commands) print("List of commands:", ', '.join(known_commands))
else: else:
print known_commands[cmd2] print(known_commands[cmd2])
elif cmd == 'seed': elif cmd == 'seed':
seed = wallet.pw_decode( wallet.seed, password) seed = wallet.pw_decode( wallet.seed, password)
print seed + ' "' + ' '.join(mnemonic_encode(seed)) + '"' print(seed + ' "' + ' '.join(mnemonic_encode(seed)) + '"')
elif cmd == 'deseed': elif cmd == 'deseed':
if not wallet.seed: if not wallet.seed:
@ -376,7 +386,7 @@ if __name__ == '__main__':
print_error("Error: This wallet is encrypted") print_error("Error: This wallet is encrypted")
else: else:
ns = wallet.path + '.seed' ns = wallet.path + '.seed'
print "Warning: you are going to extract the seed from '%s'\nThe seed will be saved in '%s'"%(wallet.path,ns) print("Warning: you are going to extract the seed from '%s'\nThe seed will be saved in '%s'"%(wallet.path,ns))
if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']: if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
f = open(ns,'w') f = open(ns,'w')
f.write(repr({'seed':wallet.seed, 'imported_keys':wallet.imported_keys})+"\n") f.write(repr({'seed':wallet.seed, 'imported_keys':wallet.imported_keys})+"\n")
@ -384,13 +394,13 @@ if __name__ == '__main__':
wallet.seed = '' wallet.seed = ''
for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = '' for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = ''
wallet.save() wallet.save()
print "Done." print("Done.")
else: else:
print_error("Action canceled.") print_error("Action canceled.")
elif cmd == 'reseed': elif cmd == 'reseed':
if wallet.seed: if wallet.seed:
print "Warning: This wallet already has a seed", wallet.seed print("Warning: This wallet already has a seed", wallet.seed)
else: else:
ns = wallet.path + '.seed' ns = wallet.path + '.seed'
try: try:
@ -414,13 +424,13 @@ if __name__ == '__main__':
wallet.init_mpk(seed) wallet.init_mpk(seed)
if mpk == wallet.master_public_key: if mpk == wallet.master_public_key:
wallet.save() wallet.save()
print "Done: " + wallet.path print("Done: " + wallet.path)
else: else:
print_error("Error: Master public key does not match") print_error("Error: Master public key does not match")
elif cmd == 'validateaddress': elif cmd == 'validateaddress':
addr = args[1] addr = args[1]
print wallet.is_valid(addr) print(wallet.is_valid(addr))
elif cmd == 'balance': elif cmd == 'balance':
try: try:
@ -430,36 +440,36 @@ if __name__ == '__main__':
if addrs == []: if addrs == []:
c, u = wallet.get_balance() c, u = wallet.get_balance()
if u: if u:
print Decimal( c ) / 100000000 , Decimal( u ) / 100000000 print(Decimal( c ) / 100000000 , Decimal( u ) / 100000000)
else: else:
print Decimal( c ) / 100000000 print(Decimal( c ) / 100000000)
else: else:
for addr in addrs: for addr in addrs:
c, u = wallet.get_addr_balance(addr) c, u = wallet.get_addr_balance(addr)
if u: if u:
print "%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)) print("%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)))
else: else:
print "%s %s" % (addr, str(Decimal(c)/100000000)) print("%s %s" % (addr, str(Decimal(c)/100000000)))
elif cmd in [ 'contacts']: elif cmd in [ 'contacts']:
for addr in wallet.addressbook: for addr in wallet.addressbook:
print addr, " ", wallet.labels.get(addr) print(addr, " ", wallet.labels.get(addr))
elif cmd == 'eval': elif cmd == 'eval':
print eval(args[1]) print(eval(args[1]))
wallet.save() wallet.save()
elif cmd == 'get': elif cmd == 'get':
key = args[1] key = args[1]
print wallet.config.get(key) print(wallet.config.get(key))
elif cmd == 'set': elif cmd == 'set':
key, value = args[1:3] key, value = args[1:3]
if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']: if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']:
wallet.config.set_key(key, value, True) wallet.config.set_key(key, value, True)
print True print(True)
else: else:
print False print(False)
elif cmd in [ 'addresses']: elif cmd in [ 'addresses']:
for addr in wallet.all_addresses(): for addr in wallet.all_addresses():
@ -481,7 +491,7 @@ if __name__ == '__main__':
m_addr = "%34s"%addr m_addr = "%34s"%addr
if options.show_keys: if options.show_keys:
m_addr += ':' + str(wallet.get_private_key_base58(addr, password)) m_addr += ':' + str(wallet.get_private_key_base58(addr, password))
print flags, m_addr, b, label print(flags, m_addr, b, label)
if cmd == 'history': if cmd == 'history':
import datetime import datetime
@ -496,8 +506,8 @@ if __name__ == '__main__':
if not label: label = tx_hash if not label: label = tx_hash
else: label = label + ' '*(64 - len(label) ) else: label = label + ' '*(64 - len(label) )
print "%17s"%time_str, " " + label + " " + format_satoshis(value)+ " "+ format_satoshis(balance) print("%17s"%time_str, " " + label + " " + format_satoshis(value)+ " "+ format_satoshis(balance))
print "# balance: ", format_satoshis(balance) print("# balance: ", format_satoshis(balance))
elif cmd == 'label': elif cmd == 'label':
try: try:
@ -529,7 +539,7 @@ if __name__ == '__main__':
for k, v in wallet.labels.items(): for k, v in wallet.labels.items():
if v == to_address: if v == to_address:
to_address = k to_address = k
print "alias", to_address print("alias", to_address)
break break
if change_addr and v == change_addr: if change_addr and v == change_addr:
change_addr = k change_addr = k
@ -543,9 +553,9 @@ if __name__ == '__main__':
if tx and cmd=='payto': if tx and cmd=='payto':
r, h = wallet.sendtx( tx ) r, h = wallet.sendtx( tx )
print h print(h)
else: else:
print tx print(tx)
if is_temporary: if is_temporary:
wallet.imported_keys.pop(from_addr) wallet.imported_keys.pop(from_addr)
@ -555,7 +565,7 @@ if __name__ == '__main__':
elif cmd == 'sendtx': elif cmd == 'sendtx':
tx = args[1] tx = args[1]
r, h = wallet.sendtx( tx ) r, h = wallet.sendtx( tx )
print h print(h)
elif cmd == 'password': elif cmd == 'password':
try: try:
@ -569,13 +579,13 @@ if __name__ == '__main__':
elif cmd == 'signmessage': elif cmd == 'signmessage':
if len(args) < 3: if len(args) < 3:
print_error("Error: Invalid usage of signmessage.") print_error("Error: Invalid usage of signmessage.")
print known_commands[cmd] print(known_commands[cmd])
sys.exit(1) sys.exit(1)
address = args[1] address = args[1]
message = ' '.join(args[2:]) message = ' '.join(args[2:])
if len(args) > 3: if len(args) > 3:
print "Warning: Message was reconstructed from several arguments:", repr(message) print("Warning: Message was reconstructed from several arguments:", repr(message))
print wallet.sign_message(address, message, password) print(wallet.sign_message(address, message, password))
elif cmd == 'verifymessage': elif cmd == 'verifymessage':
try: try:
@ -584,30 +594,30 @@ if __name__ == '__main__':
message = ' '.join(args[3:]) message = ' '.join(args[3:])
except: except:
print_error("Error: Not all parameters were given, displaying help instead.") print_error("Error: Not all parameters were given, displaying help instead.")
print known_commands[cmd] print(known_commands[cmd])
sys.exit(1) sys.exit(1)
if len(args) > 4: if len(args) > 4:
print "Warning: Message was reconstructed from several arguments:", repr(message) print("Warning: Message was reconstructed from several arguments:", repr(message))
try: try:
wallet.verify_message(address, signature, message) wallet.verify_message(address, signature, message)
print True print(True)
except BaseException as e: except BaseException as e:
print "Verification error: {0}".format(e) print_error("Verification error: {0}".format(e))
print False print(False)
elif cmd == 'freeze': elif cmd == 'freeze':
addr = args[1] addr = args[1]
print wallet.freeze(addr) print(wallet.freeze(addr))
elif cmd == 'unfreeze': elif cmd == 'unfreeze':
addr = args[1] addr = args[1]
print wallet.unfreeze(addr) print(wallet.unfreeze(addr))
elif cmd == 'prioritize': elif cmd == 'prioritize':
addr = args[1] addr = args[1]
print wallet.prioritize(addr) print(wallet.prioritize(addr))
elif cmd == 'unprioritize': elif cmd == 'unprioritize':
addr = args[1] addr = args[1]
print wallet.unprioritize(addr) print(wallet.unprioritize(addr))

View File

@ -331,23 +331,7 @@ def run_network_dialog( wallet, parent ):
status = "Please choose a server." status = "Please choose a server."
server = interface.server server = interface.server
plist, servers_list = interface.get_servers_list()
if not wallet.interface.servers:
servers_list = []
for x in DEFAULT_SERVERS:
h,port,protocol = x.split(':')
servers_list.append( (h,[(protocol,port)] ) )
else:
servers_list = wallet.interface.servers
plist = {}
for item in servers_list:
host, pp = item
z = {}
for item2 in pp:
protocol, port = item2
z[protocol] = port
plist[host] = z
dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status) gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status)

View File

@ -21,9 +21,7 @@
import android import android
from interface import WalletSynchronizer from electrum import SimpleConfig, Interface, WalletSynchronizer, Wallet, format_satoshis, mnemonic_encode, mnemonic_decode
from wallet import Wallet, format_satoshis
import mnemonic
from decimal import Decimal from decimal import Decimal
import datetime, re import datetime, re
@ -320,29 +318,21 @@ settings_layout = make_layout(""" <ListView
def get_history_values(n): def get_history_values(n):
values = [] values = []
h = wallet.get_tx_history() h = wallet.get_tx_history()
length = min(n, len(h)) length = min(n, len(h))
for i in range(length): for i in range(length):
line = h[-i-1] tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1]
v = line['value']
try: try:
dt = datetime.datetime.fromtimestamp( line['timestamp'] ) dt = datetime.datetime.fromtimestamp( timestamp )
if dt.date() == dt.today().date(): if dt.date() == dt.today().date():
time_str = str( dt.time() ) time_str = str( dt.time() )
else: else:
time_str = str( dt.date() ) time_str = str( dt.date() )
conf = 'v'
except: except:
print line['timestamp']
time_str = 'pending' time_str = 'pending'
conf = 'o'
tx_hash = line['tx_hash'] conf_str = 'v' if conf else 'o'
label = wallet.labels.get(tx_hash) label, is_default_label = wallet.get_label(tx_hash)
is_default_label = (label == '') or (label is None) values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label ))
if is_default_label: label = line['default_label']
values.append((conf, ' ' + time_str, ' ' + format_satoshis(v,True), ' ' + label ))
return values return values
@ -415,8 +405,6 @@ def update_layout():
global status_text global status_text
if not wallet.interface.is_connected: if not wallet.interface.is_connected:
text = "Not connected..." text = "Not connected..."
elif wallet.blocks == 0:
text = "Server not ready"
elif not wallet.up_to_date: elif not wallet.up_to_date:
text = "Synchronizing..." text = "Synchronizing..."
else: else:
@ -497,7 +485,7 @@ def recover():
else: else:
m = modal_input('Mnemonic','please enter your code') m = modal_input('Mnemonic','please enter your code')
try: try:
seed = mnemonic.mn_decode(m.split(' ')) seed = mnemonic_decode(m.split(' '))
except: except:
modal_dialog('error: could not decode this seed') modal_dialog('error: could not decode this seed')
exit(1) exit(1)
@ -505,7 +493,7 @@ def recover():
wallet.seed = str(seed) wallet.seed = str(seed)
modal_dialog('Your seed is:', wallet.seed) modal_dialog('Your seed is:', wallet.seed)
modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(wallet.seed)) ) modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) )
msg = "recovering wallet..." if is_recovery else "creating wallet..." msg = "recovering wallet..." if is_recovery else "creating wallet..."
droid.dialogCreateSpinnerProgress("Electrum", msg) droid.dialogCreateSpinnerProgress("Electrum", msg)
@ -748,6 +736,7 @@ def server_dialog(plist):
droid.dialogShow() droid.dialogShow()
response = droid.dialogGetResponse().result response = droid.dialogGetResponse().result
droid.dialogDismiss() droid.dialogDismiss()
if not response: return
if response.get('which') == 'positive': if response.get('which') == 'positive':
return modal_input('Private server', None) return modal_input('Private server', None)
@ -772,7 +761,7 @@ def seed_dialog():
return return
modal_dialog('Your seed is',seed) modal_dialog('Your seed is',seed)
modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(seed)) ) modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) )
def change_password_dialog(): def change_password_dialog():
if wallet.use_encryption: if wallet.use_encryption:
@ -809,7 +798,7 @@ def settings_loop():
def set_listview(): def set_listview():
server, port, p = wallet.server.split(':') server, port, p = interface.server.split(':')
fee = str( Decimal( wallet.fee)/100000000 ) fee = str( Decimal( wallet.fee)/100000000 )
is_encrypted = 'yes' if wallet.use_encryption else 'no' is_encrypted = 'yes' if wallet.use_encryption else 'no'
protocol = protocol_name(p) protocol = protocol_name(p)
@ -825,18 +814,11 @@ def settings_loop():
if event == 'OK': continue if event == 'OK': continue
if not event: continue if not event: continue
plist = {} plist, servers_list = interface.get_servers_list()
for item in wallet.interface.servers:
host, pp = item
z = {}
for item2 in pp:
protocol, port = item2
z[protocol] = port
plist[host] = z
if event["name"] == "itemclick": if event["name"] == "itemclick":
pos = event["data"]["position"] pos = event["data"]["position"]
host, port, protocol = wallet.server.split(':') host, port, protocol = interface.server.split(':')
if pos == "0": #server if pos == "0": #server
host = server_dialog(plist) host = server_dialog(plist)
@ -844,8 +826,9 @@ def settings_loop():
p = plist[host] p = plist[host]
port = p['t'] port = p['t']
srv = host + ':' + port + ':t' srv = host + ':' + port + ':t'
wallet.config.set_key("server", srv, True)
try: try:
wallet.set_server(srv) wallet.interface.set_server(srv)
except: except:
modal_dialog('error','invalid server') modal_dialog('error','invalid server')
set_listview() set_listview()
@ -855,7 +838,7 @@ def settings_loop():
srv = protocol_dialog(host, protocol, plist[host]) srv = protocol_dialog(host, protocol, plist[host])
if srv: if srv:
try: try:
wallet.set_server(srv) wallet.interface.set_server(srv)
except: except:
modal_dialog('error','invalid server') modal_dialog('error','invalid server')
set_listview() set_listview()
@ -866,7 +849,7 @@ def settings_loop():
if a_port != port: if a_port != port:
srv = host + ':' + a_port + ':'+ protocol srv = host + ':' + a_port + ':'+ protocol
try: try:
wallet.set_server(srv) wallet.interface.set_server(srv)
except: except:
modal_dialog('error','invalid port number') modal_dialog('error','invalid port number')
set_listview() set_listview()
@ -903,24 +886,6 @@ def settings_loop():
return out return out
menu_commands = ["send", "receive", "settings", "contacts", "main"]
droid = android.Android()
wallet = Wallet()
wallet.register_callback(update_callback)
wallet.set_path("/sdcard/electrum.dat")
wallet.read()
if not wallet.file_exists:
recover()
else:
WalletSynchronizer(wallet,True).start()
s = 'main'
def add_menu(s): def add_menu(s):
droid.clearOptionsMenu() droid.clearOptionsMenu()
if s == 'main': if s == 'main':
@ -937,6 +902,7 @@ def add_menu(s):
droid.addOptionsMenuItem("Pay to","paytocontact",None,"") droid.addOptionsMenuItem("Pay to","paytocontact",None,"")
#droid.addOptionsMenuItem("Delete","deletecontact",None,"") #droid.addOptionsMenuItem("Delete","deletecontact",None,"")
def make_bitmap(addr): def make_bitmap(addr):
# fixme: this is highly inefficient # fixme: this is highly inefficient
droid.dialogCreateSpinnerProgress("please wait") droid.dialogCreateSpinnerProgress("please wait")
@ -954,33 +920,51 @@ def make_bitmap(addr):
while True:
add_menu(s)
if s == 'main':
droid.fullShow(main_layout())
s = main_loop()
#droid.fullDismiss()
elif s == 'send': droid = android.Android()
droid.fullShow(payto_layout) menu_commands = ["send", "receive", "settings", "contacts", "main"]
s = payto_loop() wallet = None
#droid.fullDismiss() interface = None
elif s == 'receive': class ElectrumGui:
make_bitmap(receive_addr)
droid.fullShow(qr_layout(receive_addr))
s = receive_loop()
elif s == 'contacts': def __init__(self, w, config, app=None):
make_bitmap(contact_addr) global wallet, interface
droid.fullShow(qr_layout(contact_addr)) wallet = w
s = contacts_loop() 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)
elif s == 'settings': def server_list_changed(self): pass
#droid.fullShow(settings_layout)
s = settings_loop()
#droid.fullDismiss()
else:
break
droid.makeToast("Bye!") 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!")

View File

@ -1372,22 +1372,7 @@ class ElectrumWindow(QMainWindow):
status = _("Please choose a server.") status = _("Please choose a server.")
server = interface.server server = interface.server
plist, servers_list = interface.get_servers_list()
plist = {}
if not wallet.interface.servers:
servers_list = []
for x in DEFAULT_SERVERS:
h,port,protocol = x.split(':')
servers_list.append( (h,[(protocol,port)] ) )
else:
servers_list = wallet.interface.servers
for item in servers_list:
_host, pp = item
z = {}
for item2 in pp:
_protocol, _port = item2
z[_protocol] = _port
plist[_host] = z
d = QDialog(parent) d = QDialog(parent)
d.setModal(1) d.setModal(1)

View File

@ -490,6 +490,28 @@ class Interface(threading.Thread):
self.is_connected = False # this exits the polling loop self.is_connected = False # this exits the polling loop
self.trigger_callback('disconnecting') # for actively disconnecting self.trigger_callback('disconnecting') # for actively disconnecting
def get_servers_list(self):
plist = {}
if not self.servers:
servers_list = []
for x in DEFAULT_SERVERS:
h,port,protocol = x.split(':')
servers_list.append( (h,[(protocol,port)] ) )
else:
servers_list = self.servers
for item in servers_list:
_host, pp = item
z = {}
for item2 in pp:
_protocol, _port = item2
z[_protocol] = _port
plist[_host] = z
return plist, servers_list
def is_empty(self, channel): def is_empty(self, channel):
q = self.responses.get(channel) q = self.responses.get(channel)
if q: if q:

View File

@ -8,32 +8,29 @@ from version import ELECTRUM_VERSION, SEED_VERSION
class SimpleConfig: class SimpleConfig:
def __init__(self, options=None): def __init__(self, options={}):
# system conf, readonly # system conf, readonly
self.system_config = {} self.system_config = {}
self.read_system_config() self.read_system_config()
# user conf, writeable # user conf, writeable
self.user_dir = user_dir()
self.user_config = {} self.user_config = {}
self.read_user_config() self.read_user_config()
# command-line options # command-line options
self.options_config = {} self.options_config = options
if options:
if options.server: self.options_config['server'] = options.server
if options.proxy: self.options_config['proxy'] = options.proxy
if options.gui: self.options_config['gui'] = options.gui
self.wallet_config = {} self.wallet_config = {}
self.wallet_file_exists = False self.wallet_file_exists = False
self.init_path(options) self.init_path(self.options_config.get('wallet_path'))
print_error( "path", self.path ) print_error( "path", self.path )
if self.path: if self.path:
self.read_wallet_config(self.path) self.read_wallet_config(self.path)
def set_key(self, key, value, save = False): def set_key(self, key, value, save = False):
@ -62,8 +59,7 @@ class SimpleConfig:
def get(self, key, default=None): def get(self, key, default=None):
# 1. command-line options always override everything # 1. command-line options always override everything
if self.options_config.has_key(key): if self.options_config.has_key(key) and self.options_config.get(key) is not None:
# print "found", key, "in options"
out = self.options_config.get(key) out = self.options_config.get(key)
# 2. user configuration # 2. user configuration
@ -123,7 +119,9 @@ class SimpleConfig:
def read_user_config(self): def read_user_config(self):
name = os.path.join( user_dir(), 'electrum.conf') if not self.user_dir: return
name = os.path.join( self.user_dir, 'electrum.conf')
if os.path.exists(name): if os.path.exists(name):
try: try:
import ConfigParser import ConfigParser
@ -140,17 +138,9 @@ class SimpleConfig:
pass pass
def init_path(self, options): def init_path(self, path):
"""Set the path of the wallet.""" """Set the path of the wallet."""
path = None
if options:
# this will call read_wallet_config only if there is a wallet_path value in options
try:
path = options.wallet_path
except:
pass
if not path: if not path:
path = self.get('default_wallet_path') path = self.get('default_wallet_path')
@ -159,23 +149,22 @@ class SimpleConfig:
return return
# Look for wallet file in the default data directory. # Look for wallet file in the default data directory.
# Keeps backwards compatibility.
wallet_dir = user_dir()
# Make wallet directory if it does not yet exist. # Make wallet directory if it does not yet exist.
if not os.path.exists(wallet_dir): if not os.path.exists(self.user_dir):
os.mkdir(wallet_dir) os.mkdir(self.user_dir)
self.path = os.path.join(wallet_dir, "electrum.dat") self.path = os.path.join(self.user_dir, "electrum.dat")
def save_user_config(self): def save_user_config(self):
if not self.user_dir: return
import ConfigParser import ConfigParser
config = ConfigParser.RawConfigParser() config = ConfigParser.RawConfigParser()
config.add_section('client') config.add_section('client')
for k,v in self.user_config.items(): for k,v in self.user_config.items():
config.set('client', k, v) config.set('client', k, v)
with open( os.path.join( user_dir(), 'electrum.conf'), 'wb') as configfile: with open( os.path.join( self.user_dir, 'electrum.conf'), 'wb') as configfile:
config.write(configfile) config.write(configfile)
@ -207,6 +196,7 @@ class SimpleConfig:
f = open(self.path,"w") f = open(self.path,"w")
f.write( s ) f.write( s )
f.close() f.close()
import stat if self.get('gui') != 'android':
os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE) import stat
os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)

View File

@ -17,14 +17,14 @@ def print_error(*args):
def user_dir(): def user_dir():
if "HOME" in os.environ: if "HOME" in os.environ:
return os.path.join(os.environ["HOME"], ".electrum") return os.path.join(os.environ["HOME"], ".electrum")
elif "LOCALAPPDATA" in os.environ: elif "LOCALAPPDATA" in os.environ:
return os.path.join(os.environ["LOCALAPPDATA"], "Electrum") return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
elif "APPDATA" in os.environ: elif "APPDATA" in os.environ:
return os.path.join(os.environ["APPDATA"], "Electrum") return os.path.join(os.environ["APPDATA"], "Electrum")
else: else:
raise BaseException("No home directory found in environment variables.") #raise BaseException("No home directory found in environment variables.")
return
def appdata_dir(): def appdata_dir():
"""Find the path to the application data directory; add an electrum folder and return path.""" """Find the path to the application data directory; add an electrum folder and return path."""

View File

@ -379,7 +379,9 @@ class Wallet:
is_pruned = False is_pruned = False
v_in = v_out = v = 0 v_in = v_out = v = 0
d = self.transactions.get(tx_hash) d = self.transactions.get(tx_hash)
if not d: return 0 if not d:
return 0, 0, 0
for item in d.get('inputs'): for item in d.get('inputs'):
addr = item.get('address') addr = item.get('address')
if addr in addresses: if addr in addresses:
@ -611,7 +613,8 @@ class Wallet:
self.transactions[tx_hash] = tx self.transactions[tx_hash] = tx
tx_height = tx.get('height') tx_height = tx.get('height')
if tx_height>0: self.verifier.add(tx_hash, tx_height) if self.verifier and tx_height>0:
self.verifier.add(tx_hash, tx_height)
self.update_tx_outputs(tx_hash) self.update_tx_outputs(tx_hash)
@ -632,7 +635,7 @@ class Wallet:
for tx_hash, tx_height in hist: for tx_hash, tx_height in hist:
if tx_height>0: if tx_height>0:
# add it in case it was previously unconfirmed # add it in case it was previously unconfirmed
self.verifier.add(tx_hash, tx_height) if self.verifier: self.verifier.add(tx_hash, tx_height)
# set the height in case it changed # set the height in case it changed
tx = self.transactions.get(tx_hash) tx = self.transactions.get(tx_hash)
if tx: if tx:
@ -692,8 +695,8 @@ class Wallet:
def get_default_label(self, tx_hash): def get_default_label(self, tx_hash):
tx = self.transactions.get(tx_hash) tx = self.transactions.get(tx_hash)
default_label = ''
if tx: if tx:
default_label = ''
is_mine, _, _ = self.get_tx_value(tx_hash) is_mine, _, _ = self.get_tx_value(tx_hash)
if is_mine: if is_mine:
for o in tx['outputs']: for o in tx['outputs']:
@ -1202,8 +1205,9 @@ class WalletSynchronizer(threading.Thread):
if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx: if (tx_hash, tx_height) not in requested_tx and (tx_hash, tx_height) not in missing_tx:
missing_tx.append( (tx_hash, tx_height) ) missing_tx.append( (tx_hash, tx_height) )
else: else:
timestamp = self.wallet.verifier.get_timestamp(tx_height) if self.wallet.verifier:
self.wallet.set_tx_timestamp(tx_hash, timestamp) timestamp = self.wallet.verifier.get_timestamp(tx_height)
self.wallet.set_tx_timestamp(tx_hash, timestamp)
elif method == 'blockchain.transaction.get': elif method == 'blockchain.transaction.get':
tx_hash = params[0] tx_hash = params[0]
@ -1239,6 +1243,6 @@ class WalletSynchronizer(threading.Thread):
d = deserialize.parse_Transaction(vds) d = deserialize.parse_Transaction(vds)
d['height'] = tx_height d['height'] = tx_height
d['tx_hash'] = tx_hash d['tx_hash'] = tx_hash
d['timestamp'] = self.wallet.verifier.get_timestamp(tx_height) if self.wallet.verifier: d['timestamp'] = self.wallet.verifier.get_timestamp(tx_height)
return d return d