3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 from electrum import SimpleConfig, Wallet, WalletStorage, format_satoshis, mnemonic_encode, mnemonic_decode, is_valid
25 from electrum import util
26 from decimal import Decimal
31 def modal_dialog(title, msg = None):
32 droid.dialogCreateAlert(title,msg)
33 droid.dialogSetPositiveButtonText('OK')
35 droid.dialogGetResponse()
38 def modal_input(title, msg, value = None, etype=None):
39 droid.dialogCreateInput(title, msg, value, etype)
40 droid.dialogSetPositiveButtonText('OK')
41 droid.dialogSetNegativeButtonText('Cancel')
43 response = droid.dialogGetResponse()
44 result = response.result
46 print "modal input: result is none"
49 if result.get('which') == 'positive':
50 return result.get('value')
52 def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'):
53 droid.dialogCreateAlert(q, msg)
54 droid.dialogSetPositiveButtonText(pos_text)
55 droid.dialogSetNegativeButtonText(neg_text)
57 response = droid.dialogGetResponse()
58 result = response.result
60 print "modal question: result is none"
63 return result.get('which') == 'positive'
66 v = modal_input('Edit label',None,wallet.labels.get(addr))
69 wallet.labels[addr] = v
71 if addr in wallet.labels.keys():
72 wallet.labels.pop(addr)
73 wallet.update_tx_history()
75 droid.fullSetProperty("labelTextView", "text", v)
77 def select_from_contacts():
79 droid.dialogCreateAlert(title)
81 for i in range(len(wallet.addressbook)):
82 addr = wallet.addressbook[i]
83 label = wallet.labels.get(addr,addr)
85 droid.dialogSetItems(l)
86 droid.dialogSetPositiveButtonText('New contact')
88 response = droid.dialogGetResponse().result
91 if response.get('which') == 'positive':
94 result = response.get('item')
96 if result is not None:
97 addr = wallet.addressbook[result]
101 def select_from_addresses():
102 droid.dialogCreateAlert("Addresses:")
104 addresses = wallet.addresses()
105 for i in range(len(addresses)):
107 label = wallet.labels.get(addr,addr)
109 droid.dialogSetItems(l)
111 response = droid.dialogGetResponse()
112 result = response.result.get('item')
113 droid.dialogDismiss()
114 if result is not None:
115 addr = addresses[result]
119 def protocol_name(p):
120 if p == 't': return 'TCP'
121 if p == 'h': return 'HTTP'
122 if p == 's': return 'TCP/SSL'
123 if p == 'g': return 'HTTPS'
126 def protocol_dialog(host, protocol, z):
127 droid.dialogCreateAlert('Protocol',host)
133 current = protocols.index(protocol)
135 l.append(protocol_name(p))
136 droid.dialogSetSingleChoiceItems(l, current)
137 droid.dialogSetPositiveButtonText('OK')
138 droid.dialogSetNegativeButtonText('Cancel')
140 response = droid.dialogGetResponse().result
141 selected_item = droid.dialogGetSelectedItems().result
142 droid.dialogDismiss()
144 if not response: return
145 if not selected_item: return
146 if response.get('which') == 'positive':
147 return protocols[selected_item[0]]
152 def make_layout(s, scrollable = False):
157 android:layout_width="match_parent"
158 android:layout_height="wrap_content"
159 android:background="#ff222222">
162 android:id="@+id/textElectrum"
163 android:text="Electrum"
164 android:textSize="7pt"
165 android:textColor="#ff4444ff"
166 android:gravity="left"
167 android:layout_height="wrap_content"
168 android:layout_width="match_parent"
177 android:id="@+id/scrollview"
178 android:layout_width="match_parent"
179 android:layout_height="match_parent" >
182 android:orientation="vertical"
183 android:layout_width="match_parent"
184 android:layout_height="wrap_content" >
193 return """<?xml version="1.0" encoding="utf-8"?>
194 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
195 android:id="@+id/background"
196 android:orientation="vertical"
197 android:layout_width="match_parent"
198 android:layout_height="match_parent"
199 android:background="#ff000022">
202 </LinearLayout>"""%content
208 return make_layout("""
209 <TextView android:id="@+id/balanceTextView"
210 android:layout_width="match_parent"
212 android:textColor="#ffffffff"
213 android:textAppearance="?android:attr/textAppearanceLarge"
214 android:padding="7dip"
215 android:textSize="8pt"
216 android:gravity="center_vertical|center_horizontal|left">
219 <TextView android:id="@+id/historyTextView"
220 android:layout_width="match_parent"
221 android:layout_height="wrap_content"
222 android:text="Recent transactions"
223 android:textAppearance="?android:attr/textAppearanceLarge"
224 android:gravity="center_vertical|center_horizontal|center">
227 %s """%get_history_layout(15),True)
232 return make_layout("""
234 <TextView android:id="@+id/addrTextView"
235 android:layout_width="match_parent"
236 android:layout_height="50"
238 android:textAppearance="?android:attr/textAppearanceLarge"
239 android:gravity="center_vertical|center_horizontal|center">
243 android:id="@+id/qrView"
244 android:gravity="center"
245 android:layout_width="match_parent"
246 android:layout_height="350"
247 android:antialias="false"
248 android:src="file:///sdcard/sl4a/qrcode.bmp" />
250 <TextView android:id="@+id/labelTextView"
251 android:layout_width="match_parent"
252 android:layout_height="50"
254 android:textAppearance="?android:attr/textAppearanceLarge"
255 android:gravity="center_vertical|center_horizontal|center">
258 """%(addr,wallet.labels.get(addr,'')), True)
260 payto_layout = make_layout("""
262 <TextView android:id="@+id/recipientTextView"
263 android:layout_width="match_parent"
264 android:layout_height="wrap_content"
265 android:text="Pay to:"
266 android:textAppearance="?android:attr/textAppearanceLarge"
267 android:gravity="left">
271 <EditText android:id="@+id/recipient"
272 android:layout_width="match_parent"
273 android:layout_height="wrap_content"
274 android:tag="Tag Me" android:inputType="text">
277 <LinearLayout android:id="@+id/linearLayout1"
278 android:layout_width="match_parent"
279 android:layout_height="wrap_content">
280 <Button android:id="@+id/buttonQR" android:layout_width="wrap_content"
281 android:layout_height="wrap_content" android:text="From QR code"></Button>
282 <Button android:id="@+id/buttonContacts" android:layout_width="wrap_content"
283 android:layout_height="wrap_content" android:text="From Contacts"></Button>
287 <TextView android:id="@+id/labelTextView"
288 android:layout_width="match_parent"
289 android:layout_height="wrap_content"
290 android:text="Description:"
291 android:textAppearance="?android:attr/textAppearanceLarge"
292 android:gravity="left">
295 <EditText android:id="@+id/label"
296 android:layout_width="match_parent"
297 android:layout_height="wrap_content"
298 android:tag="Tag Me" android:inputType="text">
301 <TextView android:id="@+id/amountLabelTextView"
302 android:layout_width="match_parent"
303 android:layout_height="wrap_content"
304 android:text="Amount:"
305 android:textAppearance="?android:attr/textAppearanceLarge"
306 android:gravity="left">
309 <EditText android:id="@+id/amount"
310 android:layout_width="match_parent"
311 android:layout_height="wrap_content"
312 android:tag="Tag Me" android:inputType="numberDecimal">
315 <LinearLayout android:layout_width="match_parent"
316 android:layout_height="wrap_content" android:id="@+id/linearLayout1">
317 <Button android:id="@+id/buttonPay" android:layout_width="wrap_content"
318 android:layout_height="wrap_content" android:text="Send"></Button>
319 </LinearLayout>""",False)
323 settings_layout = make_layout(""" <ListView
324 android:id="@+id/myListView"
325 android:layout_width="match_parent"
326 android:layout_height="wrap_content" />""")
330 def get_history_values(n):
332 h = wallet.get_tx_history()
333 length = min(n, len(h))
334 for i in range(length):
335 tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1]
337 dt = datetime.datetime.fromtimestamp( timestamp )
338 if dt.date() == dt.today().date():
339 time_str = str( dt.time() )
341 time_str = str( dt.date() )
345 conf_str = 'v' if conf else 'o'
346 label, is_default_label = wallet.get_label(tx_hash)
347 values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label ))
352 def get_history_layout(n):
355 values = get_history_values(n)
358 color = "#ff00ff00" if a == 'v' else "#ffff0000"
362 android:id="@+id/hl_%d_col1"
363 android:layout_column="0"
365 android:textColor="%s"
366 android:padding="3" />
368 android:id="@+id/hl_%d_col2"
369 android:layout_column="1"
371 android:padding="3" />
373 android:id="@+id/hl_%d_col3"
374 android:layout_column="2"
376 android:padding="3" />
378 android:id="@+id/hl_%d_col4"
379 android:layout_column="3"
381 android:padding="4" />
382 </TableRow>"""%(i,a,color,i,b,i,c,i,d)
386 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
387 android:layout_width="fill_parent"
388 android:layout_height="wrap_content"
389 android:stretchColumns="0,1,2,3">
391 </TableLayout>"""% rows
395 def set_history_layout(n):
396 values = get_history_values(n)
400 droid.fullSetProperty("hl_%d_col1"%i,"text", a)
403 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00")
405 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000")
407 droid.fullSetProperty("hl_%d_col2"%i,"text", b)
408 droid.fullSetProperty("hl_%d_col3"%i,"text", c)
409 droid.fullSetProperty("hl_%d_col4"%i,"text", d)
418 if not network.is_connected():
419 text = "Not connected..."
420 elif not wallet.up_to_date:
421 text = "Synchronizing..."
423 c, u = wallet.get_balance()
424 text = "Balance:"+format_satoshis(c)
425 if u : text += ' [' + format_satoshis(u,True).strip() + ']'
428 # vibrate if status changed
429 if text != status_text:
430 if status_text and network.is_connected() and wallet.up_to_date:
434 droid.fullSetProperty("balanceTextView", "text", status_text)
436 if wallet.up_to_date:
437 set_history_layout(15)
442 def pay_to(recipient, amount, fee, label):
444 if wallet.use_encryption:
445 password = droid.dialogGetPassword('Password').result
446 if not password: return
450 droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...")
454 tx = wallet.mktx( [(recipient, amount)], password, fee)
455 except BaseException, e:
456 modal_dialog('error', e.message)
457 droid.dialogDismiss()
461 wallet.labels[tx.hash()] = label
463 droid.dialogDismiss()
465 r, h = wallet.sendtx( tx )
467 modal_dialog('Payment sent', h)
470 modal_dialog('Error', h)
478 def make_new_contact():
479 code = droid.scanBarcode()
482 data = r['extras']['SCAN_RESULT']
484 if re.match('^bitcoin:', data):
485 address, _, _, _, _, _, _ = util.parse_url(data)
491 if modal_question('Add to contacts?', address):
492 wallet.add_contact(address)
494 modal_dialog('Invalid address', data)
499 def update_callback():
501 print "gui callback", network.is_connected(), wallet.up_to_date
503 droid.eventPost("refresh",'z')
513 event = droid.eventWait(1000).result
520 print "got event in main loop", repr(event)
521 if event == 'OK': continue
522 if event is None: continue
523 if not event.get("name"): continue
525 # request 2 taps before we exit
526 if event["name"]=="key":
527 if event["data"]["key"] == '4':
532 else: quitting = False
534 if event["name"]=="click":
535 id=event["data"]["id"]
537 elif event["name"]=="settings":
540 elif event["name"] in menu_commands:
543 if out == 'contacts':
545 contact_addr = select_from_contacts()
546 if contact_addr == 'newcontact':
552 elif out == "receive":
554 receive_addr = select_from_addresses()
556 amount = modal_input('Amount', 'Amount you want receive. ', '', "numberDecimal")
558 receive_addr = 'bitcoin:%s?amount=%s'%(receive_addr, amount)
570 droid.fullSetProperty("recipient","text",recipient)
575 event = droid.eventWait().result
576 if not event: continue
577 print "got event in payto loop", event
578 if event == 'OK': continue
579 if not event.get("name"): continue
581 if event["name"] == "click":
582 id = event["data"]["id"]
587 recipient = droid.fullQueryDetail("recipient").result.get('text')
588 label = droid.fullQueryDetail("label").result.get('text')
589 amount = droid.fullQueryDetail('amount').result.get('text')
591 if not is_valid(recipient):
592 modal_dialog('Error','Invalid Bitcoin address')
596 amount = int( 100000000 * Decimal(amount) )
598 modal_dialog('Error','Invalid amount')
601 result = pay_to(recipient, amount, wallet.fee, label)
605 elif id=="buttonContacts":
606 addr = select_from_contacts()
607 droid.fullSetProperty("recipient","text",addr)
610 code = droid.scanBarcode()
613 data = r['extras']['SCAN_RESULT']
615 if re.match('^bitcoin:', data):
616 payto, amount, label, _, _, _, _ = util.parse_url(data)
617 droid.fullSetProperty("recipient", "text",payto)
618 droid.fullSetProperty("amount", "text", amount)
619 droid.fullSetProperty("label", "text", label)
621 droid.fullSetProperty("recipient", "text", data)
624 elif event["name"] in menu_commands:
627 elif event["name"]=="key":
628 if event["data"]["key"] == '4':
631 #elif event["name"]=="screen":
632 # if event["data"]=="destroy":
645 event = droid.eventWait().result
646 print "got event", event
647 if event["name"]=="key":
648 if event["data"]["key"] == '4':
651 elif event["name"]=="clipboard":
652 droid.setClipboard(receive_addr)
653 modal_dialog('Address copied to clipboard',receive_addr)
655 elif event["name"]=="edit":
656 edit_label(receive_addr)
664 event = droid.eventWait().result
665 print "got event", event
666 if event["name"]=="key":
667 if event["data"]["key"] == '4':
670 elif event["name"]=="clipboard":
671 droid.setClipboard(contact_addr)
672 modal_dialog('Address copied to clipboard',contact_addr)
674 elif event["name"]=="edit":
675 edit_label(contact_addr)
677 elif event["name"]=="paytocontact":
678 recipient = contact_addr
681 elif event["name"]=="deletecontact":
682 if modal_question('delete contact', contact_addr):
688 def server_dialog(servers):
689 droid.dialogCreateAlert("Public servers")
690 droid.dialogSetItems( servers.keys() )
691 droid.dialogSetPositiveButtonText('Private server')
693 response = droid.dialogGetResponse().result
694 droid.dialogDismiss()
695 if not response: return
697 if response.get('which') == 'positive':
698 return modal_input('Private server', None)
700 i = response.get('item')
702 response = servers.keys()[i]
707 if wallet.use_encryption:
708 password = droid.dialogGetPassword('Seed').result
709 if not password: return
714 seed = wallet.decode_seed(password)
716 modal_dialog('error','incorrect password')
719 modal_dialog('Your seed is',seed)
720 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) )
722 def change_password_dialog():
723 if wallet.use_encryption:
724 password = droid.dialogGetPassword('Your wallet is encrypted').result
725 if password is None: return
730 seed = wallet.decode_seed(password)
732 modal_dialog('error','incorrect password')
735 new_password = droid.dialogGetPassword('Choose a password').result
736 if new_password == None:
739 if new_password != '':
740 password2 = droid.dialogGetPassword('Confirm new password').result
741 if new_password != password2:
742 modal_dialog('error','passwords do not match')
745 wallet.update_password(seed, password, new_password)
747 modal_dialog('Password updated','your wallet is encrypted')
749 modal_dialog('No password','your wallet is not encrypted')
757 server, port, p = network.default_server.split(':')
758 fee = str( Decimal( wallet.fee)/100000000 )
759 is_encrypted = 'yes' if wallet.use_encryption else 'no'
760 protocol = protocol_name(p)
761 droid.fullShow(settings_layout)
762 droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed'])
768 event = droid.eventWait()
770 print "got event", event
771 if event == 'OK': continue
772 if not event: continue
774 servers = network.get_servers()
775 name = event.get("name")
776 if not name: continue
778 if name == "itemclick":
779 pos = event["data"]["position"]
780 host, port, protocol = network.default_server.split(':')
781 network_changed = False
783 if pos == "0": #server
784 host = server_dialog(servers)
788 network_changed = True
790 elif pos == "1": #protocol
792 protocol = protocol_dialog(host, protocol, servers[host])
795 network_changed = True
797 elif pos == "2": #port
798 a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number")
801 network_changed = True
803 elif pos == "3": #fee
804 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")
807 fee = int( 100000000 * Decimal(fee) )
809 modal_dialog('error','invalid fee value')
814 if change_password_dialog():
824 network.set_parameters(host, port, protocol, proxy, auto_connect)
826 modal_dialog('error','invalid server')
829 elif name in menu_commands:
832 elif name == 'cancel':
836 if event["data"]["key"] == '4':
842 droid.clearOptionsMenu()
844 droid.addOptionsMenuItem("Send","send",None,"")
845 droid.addOptionsMenuItem("Receive","receive",None,"")
846 droid.addOptionsMenuItem("Contacts","contacts",None,"")
847 droid.addOptionsMenuItem("Settings","settings",None,"")
849 droid.addOptionsMenuItem("Copy","clipboard",None,"")
850 droid.addOptionsMenuItem("Label","edit",None,"")
851 elif s == 'contacts':
852 droid.addOptionsMenuItem("Copy","clipboard",None,"")
853 droid.addOptionsMenuItem("Label","edit",None,"")
854 droid.addOptionsMenuItem("Pay to","paytocontact",None,"")
855 #droid.addOptionsMenuItem("Delete","deletecontact",None,"")
858 def make_bitmap(addr):
859 # fixme: this is highly inefficient
860 droid.dialogCreateSpinnerProgress("please wait")
863 import pyqrnative, bmp
864 qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.L)
867 k = qr.getModuleCount()
869 bmp.save_qrcode(qr,"/sdcard/sl4a/qrcode.bmp")
871 droid.dialogDismiss()
876 droid = android.Android()
877 menu_commands = ["send", "receive", "settings", "contacts", "main"]
883 def __init__(self, config, _network):
884 global wallet, network
887 network.register_callback('updated', update_callback)
888 network.register_callback('connected', update_callback)
889 network.register_callback('disconnected', update_callback)
890 network.register_callback('disconnecting', update_callback)
892 storage = WalletStorage(config)
893 if not storage.file_exists:
894 print "Wallet not found. try 'electrum create'"
897 self.wallet = Wallet(storage)
898 self.wallet.start_threads(network)
906 droid.fullShow(main_layout())
910 droid.fullShow(payto_layout)
914 make_bitmap(receive_addr)
915 droid.fullShow(qr_layout(receive_addr))
918 elif s == 'contacts':
919 make_bitmap(contact_addr)
920 droid.fullShow(qr_layout(contact_addr))
923 elif s == 'settings':
929 droid.makeToast("Bye!")
932 def restore_or_create(self):
933 droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?")
934 droid.dialogSetPositiveButtonText('Create')
935 droid.dialogSetNeutralButtonText('Restore')
936 droid.dialogSetNegativeButtonText('Cancel')
938 response = droid.dialogGetResponse().result
939 droid.dialogDismiss()
940 if not response: return
941 if response.get('which') == 'negative':
944 return 'restore' if response.get('which') == 'neutral' else 'create'
947 def seed_dialog(self):
948 if modal_question("Input method",None,'QR Code', 'mnemonic'):
949 code = droid.scanBarcode()
952 seed = r['extras']['SCAN_RESULT']
956 m = modal_input('Mnemonic','please enter your code')
958 seed = mnemonic_decode(m.split(' '))
960 modal_dialog('error: could not decode this seed')
965 return str(seed), gap
968 def network_dialog(self):
971 def verify_seed(self):
976 modal_dialog('Your seed is:', wallet.seed)
977 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) )
980 def password_dialog(self):
981 change_password_dialog()
984 def restore_wallet(self):
986 msg = "recovering wallet..."
987 droid.dialogCreateSpinnerProgress("Electrum", msg)
992 droid.dialogDismiss()
995 if wallet.is_found():
996 wallet.fill_addressbook()
997 modal_dialog("recovery successful")
999 if not modal_question("no transactions found for this seed","do you want to keep this wallet?"):