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, Interface, WalletSynchronizer, Wallet, 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 p = protocols[selected_item[0]]
149 return host + ':' + port + ':' + p
154 def make_layout(s, scrollable = False):
159 android:layout_width="match_parent"
160 android:layout_height="wrap_content"
161 android:background="#ff222222">
164 android:id="@+id/textElectrum"
165 android:text="Electrum"
166 android:textSize="7pt"
167 android:textColor="#ff4444ff"
168 android:gravity="left"
169 android:layout_height="wrap_content"
170 android:layout_width="match_parent"
179 android:id="@+id/scrollview"
180 android:layout_width="match_parent"
181 android:layout_height="match_parent" >
184 android:orientation="vertical"
185 android:layout_width="match_parent"
186 android:layout_height="wrap_content" >
195 return """<?xml version="1.0" encoding="utf-8"?>
196 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
197 android:id="@+id/background"
198 android:orientation="vertical"
199 android:layout_width="match_parent"
200 android:layout_height="match_parent"
201 android:background="#ff000022">
204 </LinearLayout>"""%content
210 return make_layout("""
211 <TextView android:id="@+id/balanceTextView"
212 android:layout_width="match_parent"
214 android:textColor="#ffffffff"
215 android:textAppearance="?android:attr/textAppearanceLarge"
216 android:padding="7dip"
217 android:textSize="8pt"
218 android:gravity="center_vertical|center_horizontal|left">
221 <TextView android:id="@+id/historyTextView"
222 android:layout_width="match_parent"
223 android:layout_height="wrap_content"
224 android:text="Recent transactions"
225 android:textAppearance="?android:attr/textAppearanceLarge"
226 android:gravity="center_vertical|center_horizontal|center">
229 %s """%get_history_layout(15),True)
234 return make_layout("""
236 <TextView android:id="@+id/addrTextView"
237 android:layout_width="match_parent"
238 android:layout_height="50"
240 android:textAppearance="?android:attr/textAppearanceLarge"
241 android:gravity="center_vertical|center_horizontal|center">
245 android:id="@+id/qrView"
246 android:gravity="center"
247 android:layout_width="match_parent"
248 android:layout_height="350"
249 android:antialias="false"
250 android:src="file:///sdcard/sl4a/qrcode.bmp" />
252 <TextView android:id="@+id/labelTextView"
253 android:layout_width="match_parent"
254 android:layout_height="50"
256 android:textAppearance="?android:attr/textAppearanceLarge"
257 android:gravity="center_vertical|center_horizontal|center">
260 """%(addr,wallet.labels.get(addr,'')), True)
262 payto_layout = make_layout("""
264 <TextView android:id="@+id/recipientTextView"
265 android:layout_width="match_parent"
266 android:layout_height="wrap_content"
267 android:text="Pay to:"
268 android:textAppearance="?android:attr/textAppearanceLarge"
269 android:gravity="left">
273 <EditText android:id="@+id/recipient"
274 android:layout_width="match_parent"
275 android:layout_height="wrap_content"
276 android:tag="Tag Me" android:inputType="text">
279 <LinearLayout android:id="@+id/linearLayout1"
280 android:layout_width="match_parent"
281 android:layout_height="wrap_content">
282 <Button android:id="@+id/buttonQR" android:layout_width="wrap_content"
283 android:layout_height="wrap_content" android:text="From QR code"></Button>
284 <Button android:id="@+id/buttonContacts" android:layout_width="wrap_content"
285 android:layout_height="wrap_content" android:text="From Contacts"></Button>
289 <TextView android:id="@+id/labelTextView"
290 android:layout_width="match_parent"
291 android:layout_height="wrap_content"
292 android:text="Description:"
293 android:textAppearance="?android:attr/textAppearanceLarge"
294 android:gravity="left">
297 <EditText android:id="@+id/label"
298 android:layout_width="match_parent"
299 android:layout_height="wrap_content"
300 android:tag="Tag Me" android:inputType="text">
303 <TextView android:id="@+id/amountLabelTextView"
304 android:layout_width="match_parent"
305 android:layout_height="wrap_content"
306 android:text="Amount:"
307 android:textAppearance="?android:attr/textAppearanceLarge"
308 android:gravity="left">
311 <EditText android:id="@+id/amount"
312 android:layout_width="match_parent"
313 android:layout_height="wrap_content"
314 android:tag="Tag Me" android:inputType="numberDecimal">
317 <LinearLayout android:layout_width="match_parent"
318 android:layout_height="wrap_content" android:id="@+id/linearLayout1">
319 <Button android:id="@+id/buttonPay" android:layout_width="wrap_content"
320 android:layout_height="wrap_content" android:text="Send"></Button>
321 </LinearLayout>""",False)
325 settings_layout = make_layout(""" <ListView
326 android:id="@+id/myListView"
327 android:layout_width="match_parent"
328 android:layout_height="wrap_content" />""")
332 def get_history_values(n):
334 h = wallet.get_tx_history()
335 length = min(n, len(h))
336 for i in range(length):
337 tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1]
339 dt = datetime.datetime.fromtimestamp( timestamp )
340 if dt.date() == dt.today().date():
341 time_str = str( dt.time() )
343 time_str = str( dt.date() )
347 conf_str = 'v' if conf else 'o'
348 label, is_default_label = wallet.get_label(tx_hash)
349 values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label ))
354 def get_history_layout(n):
357 values = get_history_values(n)
360 color = "#ff00ff00" if a == 'v' else "#ffff0000"
364 android:id="@+id/hl_%d_col1"
365 android:layout_column="0"
367 android:textColor="%s"
368 android:padding="3" />
370 android:id="@+id/hl_%d_col2"
371 android:layout_column="1"
373 android:padding="3" />
375 android:id="@+id/hl_%d_col3"
376 android:layout_column="2"
378 android:padding="3" />
380 android:id="@+id/hl_%d_col4"
381 android:layout_column="3"
383 android:padding="4" />
384 </TableRow>"""%(i,a,color,i,b,i,c,i,d)
388 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
389 android:layout_width="fill_parent"
390 android:layout_height="wrap_content"
391 android:stretchColumns="0,1,2,3">
393 </TableLayout>"""% rows
397 def set_history_layout(n):
398 values = get_history_values(n)
402 droid.fullSetProperty("hl_%d_col1"%i,"text", a)
405 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00")
407 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000")
409 droid.fullSetProperty("hl_%d_col2"%i,"text", b)
410 droid.fullSetProperty("hl_%d_col3"%i,"text", c)
411 droid.fullSetProperty("hl_%d_col4"%i,"text", d)
420 if not wallet.interface.is_connected:
421 text = "Not connected..."
422 elif not wallet.up_to_date:
423 text = "Synchronizing..."
425 c, u = wallet.get_balance()
426 text = "Balance:"+format_satoshis(c)
427 if u : text += ' [' + format_satoshis(u,True).strip() + ']'
430 # vibrate if status changed
431 if text != status_text:
432 if status_text and wallet.interface.is_connected and wallet.up_to_date:
436 droid.fullSetProperty("balanceTextView", "text", status_text)
438 if wallet.up_to_date:
439 set_history_layout(15)
444 def pay_to(recipient, amount, fee, label):
446 if wallet.use_encryption:
447 password = droid.dialogGetPassword('Password').result
448 if not password: return
452 droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...")
456 tx = wallet.mktx( [(recipient, amount)], password, fee)
457 except BaseException, e:
458 modal_dialog('error', e.message)
459 droid.dialogDismiss()
463 self.wallet.labels[tx.hash()] = label
465 droid.dialogDismiss()
467 r, h = wallet.sendtx( tx )
469 modal_dialog('Payment sent', h)
472 modal_dialog('Error', h)
480 def make_new_contact():
481 code = droid.scanBarcode()
484 data = r['extras']['SCAN_RESULT']
486 if re.match('^bitcoin:', data):
487 address, _, _, _, _, _, _ = util.parse_url(data)
493 if modal_question('Add to contacts?', address):
494 wallet.addressbook.append(address)
497 modal_dialog('Invalid address', data)
502 def update_callback():
504 print "gui callback", wallet.interface.is_connected, wallet.up_to_date
506 droid.eventPost("refresh",'z')
516 event = droid.eventWait(1000).result
523 print "got event in main loop", repr(event)
524 if event == 'OK': continue
525 if event is None: continue
526 if not event.get("name"): continue
528 # request 2 taps before we exit
529 if event["name"]=="key":
530 if event["data"]["key"] == '4':
535 else: quitting = False
537 if event["name"]=="click":
538 id=event["data"]["id"]
540 elif event["name"]=="settings":
543 elif event["name"] in menu_commands:
546 if out == 'contacts':
548 contact_addr = select_from_contacts()
549 if contact_addr == 'newcontact':
555 elif out == "receive":
557 receive_addr = select_from_addresses()
559 amount = modal_input('Amount', 'Amount you want receive. ', '', "numberDecimal")
561 receive_addr = 'bitcoin:%s?amount=%s'%(receive_addr, amount)
573 droid.fullSetProperty("recipient","text",recipient)
578 event = droid.eventWait().result
579 if not event: continue
580 print "got event in payto loop", event
581 if event == 'OK': continue
582 if not event.get("name"): continue
584 if event["name"] == "click":
585 id = event["data"]["id"]
590 recipient = droid.fullQueryDetail("recipient").result.get('text')
591 label = droid.fullQueryDetail("label").result.get('text')
592 amount = droid.fullQueryDetail('amount').result.get('text')
594 if not is_valid(recipient):
595 modal_dialog('Error','Invalid Bitcoin address')
599 amount = int( 100000000 * Decimal(amount) )
601 modal_dialog('Error','Invalid amount')
604 result = pay_to(recipient, amount, wallet.fee, label)
608 elif id=="buttonContacts":
609 addr = select_from_contacts()
610 droid.fullSetProperty("recipient","text",addr)
613 code = droid.scanBarcode()
616 data = r['extras']['SCAN_RESULT']
618 if re.match('^bitcoin:', data):
619 payto, amount, label, _, _, _, _ = util.parse_url(data)
620 droid.fullSetProperty("recipient", "text",payto)
621 droid.fullSetProperty("amount", "text", amount)
622 droid.fullSetProperty("label", "text", label)
624 droid.fullSetProperty("recipient", "text", data)
627 elif event["name"] in menu_commands:
630 elif event["name"]=="key":
631 if event["data"]["key"] == '4':
634 #elif event["name"]=="screen":
635 # if event["data"]=="destroy":
648 event = droid.eventWait().result
649 print "got event", event
650 if event["name"]=="key":
651 if event["data"]["key"] == '4':
654 elif event["name"]=="clipboard":
655 droid.setClipboard(receive_addr)
656 modal_dialog('Address copied to clipboard',receive_addr)
658 elif event["name"]=="edit":
659 edit_label(receive_addr)
667 event = droid.eventWait().result
668 print "got event", event
669 if event["name"]=="key":
670 if event["data"]["key"] == '4':
673 elif event["name"]=="clipboard":
674 droid.setClipboard(contact_addr)
675 modal_dialog('Address copied to clipboard',contact_addr)
677 elif event["name"]=="edit":
678 edit_label(contact_addr)
680 elif event["name"]=="paytocontact":
681 recipient = contact_addr
684 elif event["name"]=="deletecontact":
685 if modal_question('delete contact', contact_addr):
691 def server_dialog(plist):
692 droid.dialogCreateAlert("Public servers")
693 droid.dialogSetItems( plist.keys() )
694 droid.dialogSetPositiveButtonText('Private server')
696 response = droid.dialogGetResponse().result
697 droid.dialogDismiss()
698 if not response: return
700 if response.get('which') == 'positive':
701 return modal_input('Private server', None)
703 i = response.get('item')
705 response = plist.keys()[i]
710 if wallet.use_encryption:
711 password = droid.dialogGetPassword('Seed').result
712 if not password: return
717 seed = wallet.decode_seed(password)
719 modal_dialog('error','incorrect password')
722 modal_dialog('Your seed is',seed)
723 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) )
725 def change_password_dialog():
726 if wallet.use_encryption:
727 password = droid.dialogGetPassword('Your wallet is encrypted').result
728 if password is None: return
733 seed = wallet.decode_seed(password)
735 modal_dialog('error','incorrect password')
738 new_password = droid.dialogGetPassword('Choose a password').result
739 if new_password == None:
742 if new_password != '':
743 password2 = droid.dialogGetPassword('Confirm new password').result
744 if new_password != password2:
745 modal_dialog('error','passwords do not match')
748 wallet.update_password(seed, password, new_password)
750 modal_dialog('Password updated','your wallet is encrypted')
752 modal_dialog('No password','your wallet is not encrypted')
760 server, port, p = interface.server.split(':')
761 fee = str( Decimal( wallet.fee)/100000000 )
762 is_encrypted = 'yes' if wallet.use_encryption else 'no'
763 protocol = protocol_name(p)
764 droid.fullShow(settings_layout)
765 droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed'])
771 event = droid.eventWait()
773 print "got event", event
774 if event == 'OK': continue
775 if not event: continue
777 plist, servers_list = interface.get_servers_list()
778 name = event.get("name")
779 if not name: continue
781 if name == "itemclick":
782 pos = event["data"]["position"]
783 host, port, protocol = interface.server.split(':')
785 if pos == "0": #server
786 host = server_dialog(plist)
790 srv = host + ':' + port + ':t'
791 wallet.config.set_key("server", srv, True)
793 wallet.interface.set_server(srv)
795 modal_dialog('error','invalid server')
798 elif pos == "1": #protocol
800 srv = protocol_dialog(host, protocol, plist[host])
802 wallet.config.set_key("server", srv, True)
804 wallet.interface.set_server(srv)
806 modal_dialog('error','invalid server')
809 elif pos == "2": #port
810 a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number")
813 srv = host + ':' + a_port + ':'+ protocol
814 wallet.config.set_key("server", srv, True)
816 wallet.interface.set_server(srv)
818 modal_dialog('error','invalid port number')
821 elif pos == "3": #fee
822 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")
825 fee = int( 100000000 * Decimal(fee) )
827 modal_dialog('error','invalid fee value')
828 if wallet.fee != fee:
834 if change_password_dialog():
841 elif name in menu_commands:
844 elif name == 'cancel':
848 if event["data"]["key"] == '4':
854 droid.clearOptionsMenu()
856 droid.addOptionsMenuItem("Send","send",None,"")
857 droid.addOptionsMenuItem("Receive","receive",None,"")
858 droid.addOptionsMenuItem("Contacts","contacts",None,"")
859 droid.addOptionsMenuItem("Settings","settings",None,"")
861 droid.addOptionsMenuItem("Copy","clipboard",None,"")
862 droid.addOptionsMenuItem("Label","edit",None,"")
863 elif s == 'contacts':
864 droid.addOptionsMenuItem("Copy","clipboard",None,"")
865 droid.addOptionsMenuItem("Label","edit",None,"")
866 droid.addOptionsMenuItem("Pay to","paytocontact",None,"")
867 #droid.addOptionsMenuItem("Delete","deletecontact",None,"")
870 def make_bitmap(addr):
871 # fixme: this is highly inefficient
872 droid.dialogCreateSpinnerProgress("please wait")
875 import pyqrnative, bmp
876 qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.L)
879 k = qr.getModuleCount()
881 bmp.save_qrcode(qr,"/sdcard/sl4a/qrcode.bmp")
883 droid.dialogDismiss()
888 droid = android.Android()
889 menu_commands = ["send", "receive", "settings", "contacts", "main"]
895 def __init__(self, w, config, app=None):
896 global wallet, interface
898 interface = wallet.interface
899 interface.register_callback('updated',update_callback)
900 interface.register_callback('connected', update_callback)
901 interface.register_callback('disconnected', update_callback)
902 interface.register_callback('disconnecting', update_callback)
910 droid.fullShow(main_layout())
914 droid.fullShow(payto_layout)
918 make_bitmap(receive_addr)
919 droid.fullShow(qr_layout(receive_addr))
922 elif s == 'contacts':
923 make_bitmap(contact_addr)
924 droid.fullShow(qr_layout(contact_addr))
927 elif s == 'settings':
933 droid.makeToast("Bye!")
935 def restore_or_create(self):
936 droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?")
937 droid.dialogSetPositiveButtonText('Create')
938 droid.dialogSetNeutralButtonText('Restore')
939 droid.dialogSetNegativeButtonText('Cancel')
941 response = droid.dialogGetResponse().result
942 droid.dialogDismiss()
943 if not response: return
944 if response.get('which') == 'negative':
947 return 'restore' if response.get('which') == 'neutral' else 'create'
949 def seed_dialog(self):
950 if modal_question("Input method",None,'QR Code', 'mnemonic'):
951 code = droid.scanBarcode()
954 seed = r['extras']['SCAN_RESULT']
958 m = modal_input('Mnemonic','please enter your code')
960 seed = mnemonic_decode(m.split(' '))
962 modal_dialog('error: could not decode this seed')
967 return str(seed), gap
970 def network_dialog(self):
973 def verify_seed(self):
974 self.wallet.save_seed()
978 modal_dialog('Your seed is:', wallet.seed)
979 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) )
982 def password_dialog(self):
983 change_password_dialog()
986 def restore_wallet(self):
988 msg = "recovering wallet..."
989 droid.dialogCreateSpinnerProgress("Electrum", msg)
994 droid.dialogDismiss()
997 if wallet.is_found():
998 wallet.fill_addressbook()
999 modal_dialog("recovery successful")
1001 if not modal_question("no transactions found for this seed","do you want to keep this wallet?"):