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 decimal import Decimal
30 def modal_dialog(title, msg = None):
31 droid.dialogCreateAlert(title,msg)
32 droid.dialogSetPositiveButtonText('OK')
34 droid.dialogGetResponse()
37 def modal_input(title, msg, value = None, etype=None):
38 droid.dialogCreateInput(title, msg, value, etype)
39 droid.dialogSetPositiveButtonText('OK')
40 droid.dialogSetNegativeButtonText('Cancel')
42 response = droid.dialogGetResponse()
43 result = response.result
45 print "modal input: result is none"
48 if result.get('which') == 'positive':
49 return result.get('value')
51 def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'):
52 droid.dialogCreateAlert(q, msg)
53 droid.dialogSetPositiveButtonText(pos_text)
54 droid.dialogSetNegativeButtonText(neg_text)
56 response = droid.dialogGetResponse()
57 result = response.result
59 print "modal question: result is none"
62 return result.get('which') == 'positive'
65 v = modal_input('Edit label',None,wallet.labels.get(addr))
68 wallet.labels[addr] = v
70 if addr in wallet.labels.keys():
71 wallet.labels.pop(addr)
72 wallet.update_tx_history()
74 droid.fullSetProperty("labelTextView", "text", v)
76 def select_from_contacts():
78 droid.dialogCreateAlert(title)
80 for i in range(len(wallet.addressbook)):
81 addr = wallet.addressbook[i]
82 label = wallet.labels.get(addr,addr)
84 droid.dialogSetItems(l)
85 droid.dialogSetPositiveButtonText('New contact')
87 response = droid.dialogGetResponse().result
90 if response.get('which') == 'positive':
93 result = response.get('item')
95 if result is not None:
96 addr = wallet.addressbook[result]
100 def select_from_addresses():
101 droid.dialogCreateAlert("Addresses:")
103 addresses = wallet.addresses()
104 for i in range(len(addresses)):
106 label = wallet.labels.get(addr,addr)
108 droid.dialogSetItems(l)
110 response = droid.dialogGetResponse()
111 result = response.result.get('item')
112 droid.dialogDismiss()
113 if result is not None:
114 addr = addresses[result]
118 def protocol_name(p):
119 if p == 't': return 'TCP'
120 if p == 'h': return 'HTTP'
121 if p == 's': return 'TCP/SSL'
122 if p == 'g': return 'HTTPS'
125 def protocol_dialog(host, protocol, z):
126 droid.dialogCreateAlert('Protocol',host)
132 current = protocols.index(protocol)
134 l.append(protocol_name(p))
135 droid.dialogSetSingleChoiceItems(l, current)
136 droid.dialogSetPositiveButtonText('OK')
137 droid.dialogSetNegativeButtonText('Cancel')
139 response = droid.dialogGetResponse().result
140 selected_item = droid.dialogGetSelectedItems().result
141 droid.dialogDismiss()
143 if not response: return
144 if not selected_item: return
145 if response.get('which') == 'positive':
146 p = protocols[selected_item[0]]
148 return host + ':' + port + ':' + p
153 def make_layout(s, scrollable = False):
158 android:layout_width="match_parent"
159 android:layout_height="wrap_content"
160 android:background="#ff222222">
163 android:id="@+id/textElectrum"
164 android:text="Electrum"
165 android:textSize="7pt"
166 android:textColor="#ff4444ff"
167 android:gravity="left"
168 android:layout_height="wrap_content"
169 android:layout_width="match_parent"
178 android:id="@+id/scrollview"
179 android:layout_width="match_parent"
180 android:layout_height="match_parent" >
183 android:orientation="vertical"
184 android:layout_width="match_parent"
185 android:layout_height="wrap_content" >
194 return """<?xml version="1.0" encoding="utf-8"?>
195 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
196 android:id="@+id/background"
197 android:orientation="vertical"
198 android:layout_width="match_parent"
199 android:layout_height="match_parent"
200 android:background="#ff000022">
203 </LinearLayout>"""%content
209 return make_layout("""
210 <TextView android:id="@+id/balanceTextView"
211 android:layout_width="match_parent"
213 android:textColor="#ffffffff"
214 android:textAppearance="?android:attr/textAppearanceLarge"
215 android:padding="7dip"
216 android:textSize="8pt"
217 android:gravity="center_vertical|center_horizontal|left">
220 <TextView android:id="@+id/historyTextView"
221 android:layout_width="match_parent"
222 android:layout_height="wrap_content"
223 android:text="Recent transactions"
224 android:textAppearance="?android:attr/textAppearanceLarge"
225 android:gravity="center_vertical|center_horizontal|center">
228 %s """%get_history_layout(15),True)
233 return make_layout("""
235 <TextView android:id="@+id/addrTextView"
236 android:layout_width="match_parent"
237 android:layout_height="50"
239 android:textAppearance="?android:attr/textAppearanceLarge"
240 android:gravity="center_vertical|center_horizontal|center">
244 android:id="@+id/qrView"
245 android:gravity="center"
246 android:layout_width="match_parent"
247 android:layout_height="350"
248 android:antialias="false"
249 android:src="file:///sdcard/sl4a/qrcode.bmp" />
251 <TextView android:id="@+id/labelTextView"
252 android:layout_width="match_parent"
253 android:layout_height="50"
255 android:textAppearance="?android:attr/textAppearanceLarge"
256 android:gravity="center_vertical|center_horizontal|center">
259 """%(addr,wallet.labels.get(addr,'')), True)
261 payto_layout = make_layout("""
263 <TextView android:id="@+id/recipientTextView"
264 android:layout_width="match_parent"
265 android:layout_height="wrap_content"
266 android:text="Pay to:"
267 android:textAppearance="?android:attr/textAppearanceLarge"
268 android:gravity="left">
272 <EditText android:id="@+id/recipient"
273 android:layout_width="match_parent"
274 android:layout_height="wrap_content"
275 android:tag="Tag Me" android:inputType="text">
278 <LinearLayout android:id="@+id/linearLayout1"
279 android:layout_width="match_parent"
280 android:layout_height="wrap_content">
281 <Button android:id="@+id/buttonQR" android:layout_width="wrap_content"
282 android:layout_height="wrap_content" android:text="From QR code"></Button>
283 <Button android:id="@+id/buttonContacts" android:layout_width="wrap_content"
284 android:layout_height="wrap_content" android:text="From Contacts"></Button>
288 <TextView android:id="@+id/labelTextView"
289 android:layout_width="match_parent"
290 android:layout_height="wrap_content"
291 android:text="Description:"
292 android:textAppearance="?android:attr/textAppearanceLarge"
293 android:gravity="left">
296 <EditText android:id="@+id/label"
297 android:layout_width="match_parent"
298 android:layout_height="wrap_content"
299 android:tag="Tag Me" android:inputType="text">
302 <TextView android:id="@+id/amountLabelTextView"
303 android:layout_width="match_parent"
304 android:layout_height="wrap_content"
305 android:text="Amount:"
306 android:textAppearance="?android:attr/textAppearanceLarge"
307 android:gravity="left">
310 <EditText android:id="@+id/amount"
311 android:layout_width="match_parent"
312 android:layout_height="wrap_content"
313 android:tag="Tag Me" android:inputType="numberDecimal">
316 <LinearLayout android:layout_width="match_parent"
317 android:layout_height="wrap_content" android:id="@+id/linearLayout1">
318 <Button android:id="@+id/buttonPay" android:layout_width="wrap_content"
319 android:layout_height="wrap_content" android:text="Send"></Button>
320 </LinearLayout>""",False)
324 settings_layout = make_layout(""" <ListView
325 android:id="@+id/myListView"
326 android:layout_width="match_parent"
327 android:layout_height="wrap_content" />""")
331 def get_history_values(n):
333 h = wallet.get_tx_history()
334 length = min(n, len(h))
335 for i in range(length):
336 tx_hash, conf, is_mine, value, fee, balance, timestamp = h[-i-1]
338 dt = datetime.datetime.fromtimestamp( timestamp )
339 if dt.date() == dt.today().date():
340 time_str = str( dt.time() )
342 time_str = str( dt.date() )
346 conf_str = 'v' if conf else 'o'
347 label, is_default_label = wallet.get_label(tx_hash)
348 values.append((conf_str, ' ' + time_str, ' ' + format_satoshis(value,True), ' ' + label ))
353 def get_history_layout(n):
356 values = get_history_values(n)
359 color = "#ff00ff00" if a == 'v' else "#ffff0000"
363 android:id="@+id/hl_%d_col1"
364 android:layout_column="0"
366 android:textColor="%s"
367 android:padding="3" />
369 android:id="@+id/hl_%d_col2"
370 android:layout_column="1"
372 android:padding="3" />
374 android:id="@+id/hl_%d_col3"
375 android:layout_column="2"
377 android:padding="3" />
379 android:id="@+id/hl_%d_col4"
380 android:layout_column="3"
382 android:padding="4" />
383 </TableRow>"""%(i,a,color,i,b,i,c,i,d)
387 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
388 android:layout_width="fill_parent"
389 android:layout_height="wrap_content"
390 android:stretchColumns="0,1,2,3">
392 </TableLayout>"""% rows
396 def set_history_layout(n):
397 values = get_history_values(n)
401 droid.fullSetProperty("hl_%d_col1"%i,"text", a)
404 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00")
406 droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000")
408 droid.fullSetProperty("hl_%d_col2"%i,"text", b)
409 droid.fullSetProperty("hl_%d_col3"%i,"text", c)
410 droid.fullSetProperty("hl_%d_col4"%i,"text", d)
419 if not wallet.interface.is_connected:
420 text = "Not connected..."
421 elif not wallet.up_to_date:
422 text = "Synchronizing..."
424 c, u = wallet.get_balance()
425 text = "Balance:"+format_satoshis(c)
426 if u : text += ' [' + format_satoshis(u,True).strip() + ']'
429 # vibrate if status changed
430 if text != status_text:
431 if status_text and wallet.interface.is_connected and wallet.up_to_date:
435 droid.fullSetProperty("balanceTextView", "text", status_text)
437 if wallet.up_to_date:
438 set_history_layout(15)
443 def pay_to(recipient, amount, fee, label):
445 if wallet.use_encryption:
446 password = droid.dialogGetPassword('Password').result
447 if not password: return
451 droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...")
455 tx = wallet.mktx( [(recipient, amount)], password, fee)
456 except BaseException, e:
457 modal_dialog('error', e.message)
458 droid.dialogDismiss()
462 self.wallet.labels[tx.hash()] = label
464 droid.dialogDismiss()
466 r, h = wallet.sendtx( tx )
468 modal_dialog('Payment sent', h)
471 modal_dialog('Error', h)
479 def make_new_contact():
480 code = droid.scanBarcode()
483 data = r['extras']['SCAN_RESULT']
485 if re.match('^bitcoin:', data):
486 address, _, _, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question',x))
492 if modal_question('Add to contacts?', address):
493 wallet.addressbook.append(address)
496 modal_dialog('Invalid address', data)
501 def update_callback():
503 print "gui callback", wallet.interface.is_connected, wallet.up_to_date
505 droid.eventPost("refresh",'z')
515 event = droid.eventWait(1000).result
522 print "got event in main loop", repr(event)
523 if event == 'OK': continue
524 if event is None: continue
525 if not event.get("name"): continue
527 # request 2 taps before we exit
528 if event["name"]=="key":
529 if event["data"]["key"] == '4':
534 else: quitting = False
536 if event["name"]=="click":
537 id=event["data"]["id"]
539 elif event["name"]=="settings":
542 elif event["name"] in menu_commands:
545 if out == 'contacts':
547 contact_addr = select_from_contacts()
548 if contact_addr == 'newcontact':
554 elif out == "receive":
556 receive_addr = select_from_addresses()
558 amount = modal_input('Amount', 'Amount you want receive. ', '', "numberDecimal")
560 receive_addr = 'bitcoin:%s?amount=%s'%(receive_addr, amount)
572 droid.fullSetProperty("recipient","text",recipient)
577 event = droid.eventWait().result
578 if not event: continue
579 print "got event in payto loop", event
580 if event == 'OK': continue
581 if not event.get("name"): continue
583 if event["name"] == "click":
584 id = event["data"]["id"]
589 recipient = droid.fullQueryDetail("recipient").result.get('text')
590 label = droid.fullQueryDetail("label").result.get('text')
591 amount = droid.fullQueryDetail('amount').result.get('text')
593 if not is_valid(recipient):
594 modal_dialog('Error','Invalid Bitcoin address')
598 amount = int( 100000000 * Decimal(amount) )
600 modal_dialog('Error','Invalid amount')
603 result = pay_to(recipient, amount, wallet.fee, label)
607 elif id=="buttonContacts":
608 addr = select_from_contacts()
609 droid.fullSetProperty("recipient","text",addr)
612 code = droid.scanBarcode()
615 data = r['extras']['SCAN_RESULT']
617 if re.match('^bitcoin:', data):
618 payto, amount, label, _, _, _, _ = wallet.parse_url(data, None, lambda x: modal_question('Question', x))
619 droid.fullSetProperty("recipient", "text",payto)
620 droid.fullSetProperty("amount", "text", amount)
621 droid.fullSetProperty("label", "text", label)
623 droid.fullSetProperty("recipient", "text", data)
626 elif event["name"] in menu_commands:
629 elif event["name"]=="key":
630 if event["data"]["key"] == '4':
633 #elif event["name"]=="screen":
634 # if event["data"]=="destroy":
647 event = droid.eventWait().result
648 print "got event", event
649 if event["name"]=="key":
650 if event["data"]["key"] == '4':
653 elif event["name"]=="clipboard":
654 droid.setClipboard(receive_addr)
655 modal_dialog('Address copied to clipboard',receive_addr)
657 elif event["name"]=="edit":
658 edit_label(receive_addr)
666 event = droid.eventWait().result
667 print "got event", event
668 if event["name"]=="key":
669 if event["data"]["key"] == '4':
672 elif event["name"]=="clipboard":
673 droid.setClipboard(contact_addr)
674 modal_dialog('Address copied to clipboard',contact_addr)
676 elif event["name"]=="edit":
677 edit_label(contact_addr)
679 elif event["name"]=="paytocontact":
680 recipient = contact_addr
683 elif event["name"]=="deletecontact":
684 if modal_question('delete contact', contact_addr):
690 def server_dialog(plist):
691 droid.dialogCreateAlert("Public servers")
692 droid.dialogSetItems( plist.keys() )
693 droid.dialogSetPositiveButtonText('Private server')
695 response = droid.dialogGetResponse().result
696 droid.dialogDismiss()
697 if not response: return
699 if response.get('which') == 'positive':
700 return modal_input('Private server', None)
702 i = response.get('item')
704 response = plist.keys()[i]
709 if wallet.use_encryption:
710 password = droid.dialogGetPassword('Seed').result
711 if not password: return
716 seed = wallet.decode_seed(password)
718 modal_dialog('error','incorrect password')
721 modal_dialog('Your seed is',seed)
722 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(seed)) )
724 def change_password_dialog():
725 if wallet.use_encryption:
726 password = droid.dialogGetPassword('Your wallet is encrypted').result
727 if password is None: return
732 seed = wallet.decode_seed(password)
734 modal_dialog('error','incorrect password')
737 new_password = droid.dialogGetPassword('Choose a password').result
738 if new_password == None:
741 if new_password != '':
742 password2 = droid.dialogGetPassword('Confirm new password').result
743 if new_password != password2:
744 modal_dialog('error','passwords do not match')
747 wallet.update_password(seed, password, new_password)
749 modal_dialog('Password updated','your wallet is encrypted')
751 modal_dialog('No password','your wallet is not encrypted')
759 server, port, p = interface.server.split(':')
760 fee = str( Decimal( wallet.fee)/100000000 )
761 is_encrypted = 'yes' if wallet.use_encryption else 'no'
762 protocol = protocol_name(p)
763 droid.fullShow(settings_layout)
764 droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed'])
770 event = droid.eventWait()
772 print "got event", event
773 if event == 'OK': continue
774 if not event: continue
776 plist, servers_list = interface.get_servers_list()
777 name = event.get("name")
778 if not name: continue
780 if name == "itemclick":
781 pos = event["data"]["position"]
782 host, port, protocol = interface.server.split(':')
784 if pos == "0": #server
785 host = server_dialog(plist)
789 srv = host + ':' + port + ':t'
790 wallet.config.set_key("server", srv, True)
792 wallet.interface.set_server(srv)
794 modal_dialog('error','invalid server')
797 elif pos == "1": #protocol
799 srv = protocol_dialog(host, protocol, plist[host])
801 wallet.config.set_key("server", srv, True)
803 wallet.interface.set_server(srv)
805 modal_dialog('error','invalid server')
808 elif pos == "2": #port
809 a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number")
812 srv = host + ':' + a_port + ':'+ protocol
813 wallet.config.set_key("server", srv, True)
815 wallet.interface.set_server(srv)
817 modal_dialog('error','invalid port number')
820 elif pos == "3": #fee
821 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")
824 fee = int( 100000000 * Decimal(fee) )
826 modal_dialog('error','invalid fee value')
827 if wallet.fee != fee:
833 if change_password_dialog():
840 elif name in menu_commands:
843 elif name == 'cancel':
847 if event["data"]["key"] == '4':
853 droid.clearOptionsMenu()
855 droid.addOptionsMenuItem("Send","send",None,"")
856 droid.addOptionsMenuItem("Receive","receive",None,"")
857 droid.addOptionsMenuItem("Contacts","contacts",None,"")
858 droid.addOptionsMenuItem("Settings","settings",None,"")
860 droid.addOptionsMenuItem("Copy","clipboard",None,"")
861 droid.addOptionsMenuItem("Label","edit",None,"")
862 elif s == 'contacts':
863 droid.addOptionsMenuItem("Copy","clipboard",None,"")
864 droid.addOptionsMenuItem("Label","edit",None,"")
865 droid.addOptionsMenuItem("Pay to","paytocontact",None,"")
866 #droid.addOptionsMenuItem("Delete","deletecontact",None,"")
869 def make_bitmap(addr):
870 # fixme: this is highly inefficient
871 droid.dialogCreateSpinnerProgress("please wait")
874 import pyqrnative, bmp
875 qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.L)
878 k = qr.getModuleCount()
880 bmp.save_qrcode(qr,"/sdcard/sl4a/qrcode.bmp")
882 droid.dialogDismiss()
887 droid = android.Android()
888 menu_commands = ["send", "receive", "settings", "contacts", "main"]
894 def __init__(self, w, config, app=None):
895 global wallet, interface
897 interface = wallet.interface
898 interface.register_callback('updated',update_callback)
899 interface.register_callback('connected', update_callback)
900 interface.register_callback('disconnected', update_callback)
901 interface.register_callback('disconnecting', update_callback)
909 droid.fullShow(main_layout())
913 droid.fullShow(payto_layout)
917 make_bitmap(receive_addr)
918 droid.fullShow(qr_layout(receive_addr))
921 elif s == 'contacts':
922 make_bitmap(contact_addr)
923 droid.fullShow(qr_layout(contact_addr))
926 elif s == 'settings':
932 droid.makeToast("Bye!")
934 def restore_or_create(self):
935 droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?")
936 droid.dialogSetPositiveButtonText('Create')
937 droid.dialogSetNeutralButtonText('Restore')
938 droid.dialogSetNegativeButtonText('Cancel')
940 response = droid.dialogGetResponse().result
941 droid.dialogDismiss()
942 if not response: return
943 if response.get('which') == 'negative':
946 return 'restore' if response.get('which') == 'neutral' else 'create'
948 def seed_dialog(self):
949 if modal_question("Input method",None,'QR Code', 'mnemonic'):
950 code = droid.scanBarcode()
953 seed = r['extras']['SCAN_RESULT']
957 m = modal_input('Mnemonic','please enter your code')
959 seed = mnemonic_decode(m.split(' '))
961 modal_dialog('error: could not decode this seed')
966 return str(seed), gap
969 def network_dialog(self):
974 modal_dialog('Your seed is:', wallet.seed)
975 modal_dialog('Mnemonic code:', ' '.join(mnemonic_encode(wallet.seed)) )
978 def password_dialog(self):
979 change_password_dialog()
982 def restore_wallet(self):
984 msg = "recovering wallet..."
985 droid.dialogCreateSpinnerProgress("Electrum", msg)
990 droid.dialogDismiss()
993 if wallet.is_found():
994 wallet.fill_addressbook()
995 modal_dialog("recovery successful")
997 if not modal_question("no transactions found for this seed","do you want to keep this wallet?"):