deseed and reseed
[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 "This wallet has no seed"
253         else:
254             ns = options.wallet_path+'.seed'
255             print "Warning: you are going to extract the seed from '%s'\nThe seed will be saved in '%s'"%(options.wallet_path,ns)
256             if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
257                 f = open(ns,'w')
258                 f.write(wallet.seed)
259                 f.close()
260                 wallet.seed = ''
261                 wallet.use_encryption = False
262                 wallet.save()
263                 print "Done."
264             else:
265                 print "Action canceled."
266
267     elif cmd == 'reseed':
268         if wallet.seed:
269             print "This wallet already has a seed"
270         else:
271             ns = options.wallet_path+'.seed'
272             try:
273                 f = open(ns,'r')
274                 seed = f.read()
275                 f.close()
276             except:
277                 print "seed file not found"
278                 sys.exit()
279
280             mpk = wallet.master_public_key
281             wallet.seed = seed
282             wallet.use_encryption = False
283             wallet.init_mpk(seed)
284             if mpk == wallet.master_public_key:
285                 wallet.save()
286                 print "done"
287             else:
288                 print "error: master public key does not match"
289
290
291     elif cmd == 'validateaddress':
292         addr = args[1]
293         print wallet.is_valid(addr)
294
295     elif cmd == 'balance':
296         try:
297             addrs = args[1:]
298         except:
299             pass
300         if addrs == []:
301             c, u = wallet.get_balance()
302             if u:
303                 print Decimal( c ) / 100000000 , Decimal( u ) / 100000000
304             else:
305                 print Decimal( c ) / 100000000
306         else:
307             for addr in addrs:
308                 c, u = wallet.get_addr_balance(addr)
309                 if u:
310                     print "%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000))
311                 else:
312                     print "%s %s" % (addr, str(Decimal(c)/100000000))
313
314     elif cmd in [ 'contacts']:
315         for addr in wallet.addressbook:
316             print addr, "   ", wallet.labels.get(addr)
317
318     elif cmd == 'eval':
319         print eval(args[1])
320         wallet.save()
321
322     elif cmd in [ 'addresses']:
323         for addr in wallet.all_addresses():
324             if options.show_all or not wallet.is_change(addr):
325                 label = wallet.labels.get(addr)
326                 _type = ''
327                 if wallet.is_change(addr): _type = "[change]"
328                 if addr in wallet.imported_keys.keys(): _type = "[imported]"
329                 if label is None: label = ''
330                 if options.show_balance:
331                     h = wallet.history.get(addr,[])
332                     ni = no = 0
333                     for item in h:
334                         if item['is_input']:  ni += 1
335                         else:              no += 1
336                     b = "%d %d %s"%(no, ni, str(Decimal(wallet.get_addr_balance(addr)[0])/100000000))
337                 else: b=''
338                 if options.show_keys:
339                     pk = wallet.get_private_key(addr, password)
340                     addr = addr + ':' + SecretToASecret(pk)
341                 print addr, b, _type, label
342
343     if cmd == 'history':
344         lines = wallet.get_tx_history()
345         b = 0 
346         for line in lines:
347             import datetime
348             v = line['value'] 
349             b += v
350             try:
351                 time_str = str( datetime.datetime.fromtimestamp( line['timestamp']))
352             except:
353                 print line['timestamp']
354                 time_str = 'pending'
355             label = line.get('label')
356             if not label: label = line['tx_hash']
357             else: label = label + ' '*(64 - len(label) )
358
359             print time_str , "  " + label + "  " + format_satoshis(v)+ "  "+ format_satoshis(b)
360         print "# balance: ", format_satoshis(b)
361
362     elif cmd == 'label':
363         try:
364             tx = args[1]
365             label = ' '.join(args[2:])
366         except:
367             print "syntax:  label <tx_hash> <text>"
368             sys.exit(1)
369         wallet.labels[tx] = label
370         wallet.save()
371             
372     elif cmd in ['payto', 'mktx']:
373         if from_addr and is_temporary:
374             if from_addr.find(":") == -1:
375                 keypair = from_addr + ":" + getpass.getpass('Private key:')
376             else:
377                 keypair = from_addr
378                 from_addr = keypair.split(':')[0]
379             if not wallet.import_key(keypair,password):
380                 print "invalid key pair"
381                 exit(1)
382             wallet.history[from_addr] = interface.retrieve_history(from_addr)
383             wallet.update_tx_history()
384             change_addr = from_addr
385
386         if options.change_addr:
387             change_addr = options.change_addr
388
389         for k, v in wallet.labels.items():
390             if v == to_address:
391                 to_address = k
392                 print "alias", to_address
393                 break
394             if change_addr and v == change_addr:
395                 change_addr = k
396         try:
397             tx = wallet.mktx( to_address, amount, label, password,
398                 fee = options.tx_fee, change_addr = change_addr, from_addr = from_addr )
399         except:
400             import traceback
401             traceback.print_exc(file=sys.stdout)
402             tx = None
403
404         if tx and cmd=='payto': 
405             r, h = wallet.sendtx( tx )
406             print h
407         else:
408             print tx
409
410         if is_temporary:
411             wallet.imported_keys.pop(from_addr)
412             del(wallet.history[from_addr])
413         wallet.save()
414
415     elif cmd == 'sendtx':
416         tx = args[1]
417         r, h = wallet.sendtx( tx )
418         print h
419
420     elif cmd == 'password':
421         try:
422             seed = wallet.pw_decode( wallet.seed, password)
423         except:
424             print "sorry"
425             sys.exit(1)
426         new_password = getpass.getpass('New password:')
427         if new_password == getpass.getpass('Confirm new password:'):
428             wallet.use_encryption = (new_password != '')
429             wallet.seed = wallet.pw_encode( seed, new_password)
430             for k in wallet.imported_keys.keys():
431                 a = wallet.imported_keys[k]
432                 b = wallet.pw_decode(a, password)
433                 c = wallet.pw_encode(b, new_password)
434                 wallet.imported_keys[k] = c
435             wallet.save()
436         else:
437             print "error: mismatch"
438
439     elif cmd == 'signmessage':
440         address, message = args[1:3]
441         print wallet.sign_message(address, message, password)
442
443     elif cmd == 'verifymessage':
444         address, signature, message = args[1:4]
445         try:
446             wallet.verify_message(address, signature, message)
447             print True
448         except:
449             print False
450         
451