deseed: error if wallet is encrypted
[electrum-nvc.git] / electrum
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19 import re, sys, getpass
20
21 import electrum
22 from optparse import OptionParser
23 from decimal import Decimal
24
25 from electrum import Wallet, SecretToASecret, WalletSynchronizer, format_satoshis
26
27 known_commands = ['help', 'validateaddress', 'balance', 'contacts', 'create', 'restore', 'payto', 'sendtx', 'password', 'addresses', 'history', 'label', 'mktx','seed','import','signmessage','verifymessage','eval','deseed','reseed']
28 offline_commands = ['password', 'mktx', 'history', 'label', 'contacts', 'help', 'validateaddress', 'signmessage', 'verifymessage', 'eval', 'create', 'addresses', 'import', 'seed','deseed','reseed']
29 protected_commands = ['payto', 'password', 'mktx', 'seed', 'import','signmessage' ]
30
31 if __name__ == '__main__':
32
33     usage = "usage: %prog [options] command args\nCommands: "+ (', '.join(known_commands))
34     parser = OptionParser(usage=usage)
35     parser.add_option("-g", "--gui", dest="gui", default="qt", help="gui")
36     parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
37     parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
38     parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance at listed addresses")
39     parser.add_option("-k", "--keys",action="store_true", dest="show_keys",default=False, help="show the private keys of listed addresses")
40     parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee")
41     parser.add_option("-s", "--fromaddr", dest="from_addr", default=None, help="set source address for payto/mktx. if it isn't in the wallet, it will ask for the private key unless supplied in the format public_key:private_key. It's not saved in the wallet.")
42     parser.add_option("-c", "--changeaddr", dest="change_addr", default=None, help="set the change address for payto/mktx. default is a spare address, or the source address if it's not in the wallet")
43     parser.add_option("-r", "--remote", dest="remote_url", default=None, help="URL of a remote wallet")
44     options, args = parser.parse_args()
45
46     wallet = Wallet()
47     wallet.set_path(options.wallet_path)
48     wallet.read()
49     wallet.remote_url = options.remote_url
50
51     if len(args)==0:
52         url = None
53         cmd = 'gui'
54     elif len(args)==1 and re.match('^bitcoin:', args[0]):
55         url = args[0]
56         cmd = 'gui'
57     else:
58         cmd = args[0]
59         firstarg = args[1] if len(args) > 1 else ''
60         
61     if cmd == 'gui':
62         if options.gui=='gtk':
63             import electrum.gui as gui
64         elif options.gui=='qt':
65             import electrum.gui_qt as gui
66         else:
67             print "unknown gui", options.gui
68             exit(1)
69
70         gui = gui.ElectrumGui(wallet)
71         WalletSynchronizer(wallet,True).start()
72
73         try:
74             found = wallet.file_exists
75             if not found:
76                 found = gui.restore_or_create()
77         except SystemExit, e:
78             exit(e)
79         except BaseException, e:
80             import traceback
81             traceback.print_exc(file=sys.stdout)
82             #gui.show_message(e.message)
83             exit(1)
84
85         if not found: exit(1)
86
87         gui.main(url)
88         wallet.save()
89         sys.exit(0)
90
91     if cmd not in known_commands:
92         cmd = 'help'
93
94     if not wallet.file_exists and cmd not in ['help','create','restore']:
95         print "Wallet file not found."
96         print "Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option"
97         sys.exit(0)
98     
99     if cmd in ['create', 'restore']:
100         from electrum import mnemonic
101         if wallet.file_exists:
102             print "remove the existing wallet first!"
103             sys.exit(0)
104         password = getpass.getpass("Password (hit return if you do not wish to encrypt your wallet):")
105         if password:
106             password2 = getpass.getpass("Confirm password:")
107             if password != password2:
108                 print "error"
109                 sys.exit(1)
110         else:
111             password = None
112
113         w_host, w_port, w_protocol = wallet.server.split(':')
114         host = raw_input("server (default:%s):"%w_host)
115         port = raw_input("port (default:%s):"%w_port)
116         protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol)
117         fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) )
118         gap = raw_input("gap limit (default 5):")
119         if host: w_host = host
120         if port: w_port = port
121         if protocol: w_protocol = protocol
122         wallet.server = w_host + ':' + w_port + ':' +w_protocol
123         if fee: wallet.fee = float(fee)
124         if gap: wallet.gap_limit = int(gap)
125
126         if cmd == 'restore':
127             seed = raw_input("seed:")
128             try:
129                 seed.decode('hex')
130             except:
131                 print "not hex, trying decode"
132                 seed = mnemonic.mn_decode( seed.split(' ') )
133             if not seed:
134                 print "no seed"
135                 sys.exit(1)
136
137             wallet.seed = str(seed)
138             WalletSynchronizer(wallet).start()
139             print "recovering wallet..."
140             wallet.init_mpk( wallet.seed )
141             wallet.up_to_date_event.clear()
142             wallet.up_to_date = False
143             wallet.update()
144             if wallet.is_found():
145                 wallet.fill_addressbook()
146                 wallet.save()
147                 print "recovery successful"
148             else:
149                 print "found no history for this wallet"
150         else:
151             wallet.new_seed(None)
152             wallet.init_mpk( wallet.seed )
153             wallet.synchronize() # there is no wallet thread 
154             wallet.save()
155             print "Your wallet generation seed is: " + wallet.seed
156             print "Please keep it in a safe place; if you lose it, you will not be able to restore your wallet."
157             print "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:"
158             print "\""+' '.join(mnemonic.mn_encode(wallet.seed))+"\""
159
160     # check syntax
161     if cmd in ['payto', 'mktx']:
162         try:
163             to_address = args[1]
164             amount = int( 100000000 * Decimal(args[2]) )
165             change_addr = None
166             label = ' '.join(args[3:])
167             if options.tx_fee: 
168                 options.tx_fee = int( 100000000 * Decimal(options.tx_fee) )
169         except:
170             firstarg = cmd
171             cmd = 'help'
172
173     # open session
174     if cmd not in offline_commands:
175         WalletSynchronizer(wallet).start()
176         wallet.update()
177         wallet.save()
178
179     # check if --from_addr not in wallet (for mktx/payto)
180     is_temporary = False
181     from_addr = None
182     if options.from_addr:
183         from_addr = options.from_addr
184         if from_addr not in wallet.all_addresses():
185             is_temporary = True
186                 
187     # commands needing password
188     if cmd in protected_commands or ( cmd=='addresses' and options.show_keys):
189         password = getpass.getpass('Password:') if wallet.use_encryption and not is_temporary else None
190         # check password
191         try:
192             wallet.pw_decode( wallet.seed, password)
193         except:
194             print "invalid password"
195             exit(1)
196
197     if cmd == 'import':
198         keypair = args[1]
199         if wallet.import_key(keypair,password):
200             print "keypair imported"
201         else:
202             print "error"
203         wallet.save()
204
205     if cmd=='help':
206         cmd2 = firstarg
207         if cmd2 not in known_commands:
208             print "known commands:", ', '.join(known_commands)
209             print "'electrum help <command>' shows the help on a specific command"
210             print "'electrum --help' shows the list of options"
211         elif cmd2 == 'balance':
212             print "Display the balance of your wallet or a specific address. The address does not have to be a owned address (you know the private key)."
213             print "syntax: balance [<address>]"
214         elif cmd2 == 'contacts':
215             print "show your list of contacts"
216         elif cmd2 == 'payto':
217             print "payto <recipient> <amount> [label]"
218             print "create and broadcast a transaction."
219             print "<recipient> can be a bitcoin address or a label"
220             print "options: --fee, --fromaddr, --changeaddr"
221         elif cmd2== 'sendtx':
222             print "sendtx <tx>"
223             print "broadcast a transaction to the network. <tx> must be in hexadecimal"
224         elif cmd2 == 'password':
225             print "change your password"
226         elif cmd2 == 'addresses':
227             print "show your list of addresses. options: -a, -k, -b"
228         elif cmd2 == 'history':
229             print "show the transaction history"
230         elif cmd2 == 'label':
231             print "assign a label to an item"
232         elif cmd2 == 'gtk':
233             print "start the GUI"
234         elif cmd2 == 'mktx':
235             print "create a signed transaction. password protected"
236             print "syntax: mktx <recipient> <amount> [label]"
237             print "options: --fee, --fromaddr, --changeaddr"
238         elif cmd2 == 'seed':
239             print "show generation seed of your wallet. password protected."
240         elif cmd2 == 'deseed':
241             print "remove the seed of your wallet."
242         elif cmd2 == 'eval':
243             print "Run python eval() on an object\nSyntax: eval <expression>\nExample: eval \"wallet.aliases\""
244
245     elif cmd == 'seed':
246         from electrum import mnemonic
247         seed = wallet.pw_decode( wallet.seed, password)
248         print seed, '"'+' '.join(mnemonic.mn_encode(seed))+'"'
249
250     elif cmd == 'deseed':
251         if not wallet.seed:
252             print "Eooro: This wallet has no seed"
253         elif wallet.use_encryption:
254             print "Error: This wallet is encrypted"
255         else:
256             ns = options.wallet_path+'.seed'
257             print "Warning: you are going to extract the seed from '%s'\nThe seed will be saved in '%s'"%(options.wallet_path,ns)
258             if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
259                 f = open(ns,'w')
260                 f.write(wallet.seed)
261                 f.close()
262                 wallet.seed = ''
263                 wallet.save()
264                 print "Done."
265             else:
266                 print "Action canceled."
267
268     elif cmd == 'reseed':
269         if wallet.seed:
270             print "This wallet already has a seed"
271         else:
272             ns = options.wallet_path+'.seed'
273             try:
274                 f = open(ns,'r')
275                 seed = f.read()
276                 f.close()
277             except:
278                 print "seed file not found"
279                 sys.exit()
280
281             mpk = wallet.master_public_key
282             wallet.seed = seed
283             wallet.use_encryption = False
284             wallet.init_mpk(seed)
285             if mpk == wallet.master_public_key:
286                 wallet.save()
287                 print "done"
288             else:
289                 print "error: master public key does not match"
290
291
292     elif cmd == 'validateaddress':
293         addr = args[1]
294         print wallet.is_valid(addr)
295
296     elif cmd == 'balance':
297         try:
298             addrs = args[1:]
299         except:
300             pass
301         if addrs == []:
302             c, u = wallet.get_balance()
303             if u:
304                 print Decimal( c ) / 100000000 , Decimal( u ) / 100000000
305             else:
306                 print Decimal( c ) / 100000000
307         else:
308             for addr in addrs:
309                 c, u = wallet.get_addr_balance(addr)
310                 if u:
311                     print "%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000))
312                 else:
313                     print "%s %s" % (addr, str(Decimal(c)/100000000))
314
315     elif cmd in [ 'contacts']:
316         for addr in wallet.addressbook:
317             print addr, "   ", wallet.labels.get(addr)
318
319     elif cmd == 'eval':
320         print eval(args[1])
321         wallet.save()
322
323     elif cmd in [ 'addresses']:
324         for addr in wallet.all_addresses():
325             if options.show_all or not wallet.is_change(addr):
326                 label = wallet.labels.get(addr)
327                 _type = ''
328                 if wallet.is_change(addr): _type = "[change]"
329                 if addr in wallet.imported_keys.keys(): _type = "[imported]"
330                 if label is None: label = ''
331                 if options.show_balance:
332                     h = wallet.history.get(addr,[])
333                     ni = no = 0
334                     for item in h:
335                         if item['is_input']:  ni += 1
336                         else:              no += 1
337                     b = "%d %d %s"%(no, ni, str(Decimal(wallet.get_addr_balance(addr)[0])/100000000))
338                 else: b=''
339                 if options.show_keys:
340                     pk = wallet.get_private_key(addr, password)
341                     addr = addr + ':' + SecretToASecret(pk)
342                 print addr, b, _type, label
343
344     if cmd == 'history':
345         lines = wallet.get_tx_history()
346         b = 0 
347         for line in lines:
348             import datetime
349             v = line['value'] 
350             b += v
351             try:
352                 time_str = str( datetime.datetime.fromtimestamp( line['timestamp']))
353             except:
354                 print line['timestamp']
355                 time_str = 'pending'
356             label = line.get('label')
357             if not label: label = line['tx_hash']
358             else: label = label + ' '*(64 - len(label) )
359
360             print time_str , "  " + label + "  " + format_satoshis(v)+ "  "+ format_satoshis(b)
361         print "# balance: ", format_satoshis(b)
362
363     elif cmd == 'label':
364         try:
365             tx = args[1]
366             label = ' '.join(args[2:])
367         except:
368             print "syntax:  label <tx_hash> <text>"
369             sys.exit(1)
370         wallet.labels[tx] = label
371         wallet.save()
372             
373     elif cmd in ['payto', 'mktx']:
374         if from_addr and is_temporary:
375             if from_addr.find(":") == -1:
376                 keypair = from_addr + ":" + getpass.getpass('Private key:')
377             else:
378                 keypair = from_addr
379                 from_addr = keypair.split(':')[0]
380             if not wallet.import_key(keypair,password):
381                 print "invalid key pair"
382                 exit(1)
383             wallet.history[from_addr] = interface.retrieve_history(from_addr)
384             wallet.update_tx_history()
385             change_addr = from_addr
386
387         if options.change_addr:
388             change_addr = options.change_addr
389
390         for k, v in wallet.labels.items():
391             if v == to_address:
392                 to_address = k
393                 print "alias", to_address
394                 break
395             if change_addr and v == change_addr:
396                 change_addr = k
397         try:
398             tx = wallet.mktx( to_address, amount, label, password,
399                 fee = options.tx_fee, change_addr = change_addr, from_addr = from_addr )
400         except:
401             import traceback
402             traceback.print_exc(file=sys.stdout)
403             tx = None
404
405         if tx and cmd=='payto': 
406             r, h = wallet.sendtx( tx )
407             print h
408         else:
409             print tx
410
411         if is_temporary:
412             wallet.imported_keys.pop(from_addr)
413             del(wallet.history[from_addr])
414         wallet.save()
415
416     elif cmd == 'sendtx':
417         tx = args[1]
418         r, h = wallet.sendtx( tx )
419         print h
420
421     elif cmd == 'password':
422         try:
423             seed = wallet.pw_decode( wallet.seed, password)
424         except:
425             print "sorry"
426             sys.exit(1)
427         new_password = getpass.getpass('New password:')
428         if new_password == getpass.getpass('Confirm new password:'):
429             wallet.use_encryption = (new_password != '')
430             wallet.seed = wallet.pw_encode( seed, new_password)
431             for k in wallet.imported_keys.keys():
432                 a = wallet.imported_keys[k]
433                 b = wallet.pw_decode(a, password)
434                 c = wallet.pw_encode(b, new_password)
435                 wallet.imported_keys[k] = c
436             wallet.save()
437         else:
438             print "error: mismatch"
439
440     elif cmd == 'signmessage':
441         address, message = args[1:3]
442         print wallet.sign_message(address, message, password)
443
444     elif cmd == 'verifymessage':
445         address, signature, message = args[1:4]
446         try:
447             wallet.verify_message(address, signature, message)
448             print True
449         except:
450             print False
451         
452