move 'addresses' command
[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
20 import sys, os, time, ast
21 import optparse
22 import platform
23
24 try:
25     import ecdsa  
26 except ImportError:
27     sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
28
29 try:
30     import aes
31 except ImportError:
32     sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
33
34 try:
35     from lib import *
36 except ImportError:
37     from electrum import *
38
39 from decimal import Decimal
40
41 known_commands = {
42     'help':'Prints this help',
43     'validateaddress':'Check that the address is valid', 
44     'balance': "Display the balance of your wallet or of an address.\nSyntax: balance [<address>]", 
45     'contacts': "Show your list of contacts", 
46     'create':'Create a wallet', 
47     'restore':'Restore a wallet', 
48     'payto':"""Create and broadcast a transaction.
49 Syntax: payto <recipient> <amount> [label]
50 <recipient> can be a bitcoin address or a label
51 options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address -\n  --changeaddr, -c: send change to address
52             """,
53     'sendrawtransaction':
54             'Broadcasts a transaction to the network. \nSyntax: sendrawtransaction <tx in hexadecimal>',
55     'password': 
56             "Changes your password",
57     'addresses':  
58             """Shows your list of addresses.
59 options:
60   -a: show all addresses, including change addresses
61   -k: show private keys
62   -b: show the balance of addresses""",
63
64     'history':"Shows the transaction history",
65     'setlabel':'Assign a label to an item\nSyntax: label <tx_hash> <label>',
66     'mktx':
67         """Create a signed transaction, password protected.
68 Syntax: mktx <recipient> <amount> [label]
69 options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address -\n  --changeaddr, -c: send change to address
70         """,
71     'get_seed':
72             "Print the generation seed of your wallet.",
73     'importprivkey': 
74             'Import a private key\nSyntax: importprivkey <privatekey>',
75     'signmessage':
76             'Signs a message with a key\nSyntax: signmessage <address> <message>\nIf you want to lead or end a message with spaces, or want double spaces inside the message make sure you quote the string. I.e. " Hello  This is a weird String "',
77     'verifymessage':
78              'Verifies a signature\nSyntax: verifymessage <address> <signature> <message>\nIf you want to lead or end a message with spaces, or want double spaces inside the message make sure you quote the string. I.e. " Hello  This is a weird String "',
79     'eval':  
80              "Run python eval() on an object\nSyntax: eval <expression>\nExample: eval \"wallet.aliases\"",
81     'get': 
82              "Get config parameter.",
83     'set': 
84              "Set config parameter.",
85     'deseed':
86             "Create a seedless, watching-only wallet.",
87     'freeze':'',
88     'unfreeze':'',
89     'prioritize':'',
90     'unprioritize':'',
91     'dumpprivkey':'similar to bitcoind\'s command',
92     'dumpprivkeys':'dump all private keys',
93     'listunspent':'similar to bitcoind\'s command',
94     'createmultisig':'similar to bitcoind\'s command',
95     'createrawtransaction':'similar to bitcoind\'s command',
96     'decoderawtransaction':'similar to bitcoind\'s command',
97     'signrawtransaction':'similar to bitcoind\'s command',
98     'get_history': 'get history for an address'
99     
100     }
101
102
103
104 offline_commands = [ 'password', 'mktx',
105                      'setlabel', 'contacts',
106                      'help', 'validateaddress',
107                      'signmessage', 'verifymessage',
108                      'eval', 'set', 'get', 'create', 'addresses',
109                      'importprivkey', 'get_seed',
110                      'deseed',
111                      'freeze','unfreeze',
112                      'prioritize','unprioritize',
113                      'dumpprivkey','listunspent',
114                      'createmultisig', 'createrawtransaction', 'decoderawtransaction', 'signrawtransaction'
115                      ]
116
117
118
119 # get password routine
120 def prompt_password(prompt, confirm=True):
121     import getpass
122     if sys.stdin.isatty():
123         password = getpass.getpass(prompt)
124         if password and confirm:
125             password2 = getpass.getpass("Confirm: ")
126             if password != password2:
127                 sys.exit("Error: Passwords do not match.")
128     else:
129         password = raw_input(prompt)
130     if not password:
131         password = None
132     return password
133
134 def arg_parser():
135     usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands))
136     parser = optparse.OptionParser(prog=usage)
137     parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text")
138     parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
139     parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline")
140     parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
141     parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance at listed addresses")
142     parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee")
143     parser.add_option("-F", "--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.")
144     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")
145     parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h")
146     parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
147     parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
148     parser.add_option("-P", "--portable", action="store_true", dest="portable", default=False, help="portable wallet")
149     parser.add_option("-L", "--lang", dest="language", default=None, help="defaut language used in GUI")
150     parser.add_option("-u", "--usb", dest="bitkey", action="store_true", help="Turn on support for hardware wallets (EXPERIMENTAL)")
151     return parser
152
153
154 if __name__ == '__main__':
155
156     parser = arg_parser()
157     options, args = parser.parse_args()
158     set_verbosity(options.verbose)
159
160     # config is an object passed to the various constructors (wallet, interface, gui)
161     if 'ANDROID_DATA' in os.environ:
162         config_options = {'wallet_path':"/sdcard/electrum.dat", 'portable':True, 'verbose':True, 'gui':'android'}
163     else:
164         config_options = eval(str(options))
165         for k, v in config_options.items():
166             if v is None: config_options.pop(k)
167
168     # Wallet migration on Electrum 1.7
169     # Todo: In time we could remove this again
170     if platform.system() == "Windows":
171         util.check_windows_wallet_migration()
172
173     config = SimpleConfig(config_options)
174     wallet = Wallet(config)
175
176     if len(args)==0:
177         url = None
178         cmd = 'gui'
179     elif len(args)==1 and re.match('^bitcoin:', args[0]):
180         url = args[0]
181         cmd = 'gui'
182     else:
183         cmd = args[0]
184         firstarg = args[1] if len(args) > 1 else ''
185        
186     #this entire if/else block is just concerned with importing the 
187     #right GUI toolkit based the GUI command line option given 
188     if cmd == 'gui':
189         pref_gui = config.get('gui','classic')
190
191         if pref_gui == 'gtk':
192             try:
193                 import lib.gui as gui
194             except ImportError:
195                 import electrum.gui as gui
196         elif pref_gui in ['classic', 'qt']:
197             try:
198                 import lib.gui_qt as gui
199             except ImportError:
200                 import electrum.gui_qt as gui
201         elif pref_gui == 'lite':
202               try:
203                   import lib.gui_lite as gui
204               except ImportError:
205                   import electrum.gui_lite as gui
206         elif pref_gui == 'text':
207               try:
208                   import lib.gui_text as gui
209               except ImportError:
210                   import electrum.gui_text as gui
211         elif pref_gui == 'android':
212               try:
213                   import lib.gui_android as gui
214               except ImportError:
215                   import electrum.gui_android as gui
216         else:
217             sys.exit("Error: Unknown GUI: " + pref_gui )
218
219         
220         interface = Interface(config, True)
221         wallet.interface = interface
222         interface.start()
223         if interface.is_connected:
224             interface.send([('server.peers.subscribe',[])])
225
226         set_language(config.get('language'))
227         gui = gui.ElectrumGui(wallet, config)
228
229         found = config.wallet_file_exists
230         if not found:
231             a = gui.restore_or_create()
232             if not a: exit()
233             # select a server.
234             s = gui.network_dialog()
235
236             if a =='create':
237                 wallet.init_seed(None)
238             else:
239                 # ask for seed and gap.
240                 sg = gui.seed_dialog()
241                 if not sg: exit()
242                 seed, gap = sg
243                 if not seed: exit()
244                 wallet.gap_limit = gap
245                 if len(seed) == 128:
246                     wallet.seed = ''
247                     wallet.sequence.master_public_key = seed
248                 else:
249                     wallet.init_seed(str(seed))
250             
251
252             # generate the first addresses, in case we are offline
253             if s is None or a == 'create':
254                 wallet.synchronize()
255             if a == 'create':
256                 # display seed
257                 gui.show_seed()
258
259         verifier = WalletVerifier(interface, config)
260         wallet.set_verifier(verifier)
261         synchronizer = WalletSynchronizer(wallet, config)
262         synchronizer.start()
263
264         if not found and a == 'restore' and s is not None:
265             try:
266                 keep_it = gui.restore_wallet()
267                 wallet.fill_addressbook()
268             except:
269                 import traceback
270                 traceback.print_exc(file=sys.stdout)
271                 exit()
272
273             if not keep_it: exit()
274
275         if not found:
276             gui.password_dialog()
277
278         wallet.save()
279         verifier.start()
280         gui.main(url)
281         wallet.save()
282
283         verifier.stop()
284         synchronizer.stop()
285         interface.stop()
286
287         # we use daemon threads, their termination is enforced.
288         # this sleep command gives them time to terminate cleanly. 
289         time.sleep(0.1)
290         sys.exit(0)
291
292     if cmd not in known_commands:
293         cmd = 'help'
294
295     if not config.wallet_file_exists and cmd not in ['help','create','restore']:
296         print_msg("Error: Wallet file not found.")
297         print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
298         sys.exit(0)
299     
300     if cmd in ['create', 'restore']:
301         if config.wallet_file_exists:
302             sys.exit("Error: Remove the existing wallet first!")
303         password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):")
304
305         server = config.get('server')
306         if not server: server = pick_random_server()
307         w_host, w_port, w_protocol = server.split(':')
308         host = raw_input("server (default:%s):"%w_host)
309         port = raw_input("port (default:%s):"%w_port)
310         protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol)
311         fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) )
312         gap = raw_input("gap limit (default 5):")
313         if host: w_host = host
314         if port: w_port = port
315         if protocol: w_protocol = protocol
316         wallet.config.set_key('server', w_host + ':' + w_port + ':' +w_protocol)
317         if fee: wallet.fee = float(fee)
318         if gap: wallet.gap_limit = int(gap)
319
320         if cmd == 'restore':
321             seed = raw_input("seed:")
322             try:
323                 seed.decode('hex')
324             except:
325                 print_error("Warning: Not hex, trying decode.")
326                 seed = mnemonic_decode( seed.split(' ') )
327             if not seed:
328                 sys.exit("Error: No seed")
329
330             if len(seed) == 128:
331                 wallet.seed = None
332                 wallet.sequence.master_public_key = seed
333             else:
334                 wallet.seed = str(seed)
335                 wallet.init_mpk( wallet.seed )
336
337             if not options.offline:
338                 interface = Interface(config)
339                 interface.start()
340                 wallet.interface = interface
341
342                 verifier = WalletVerifier(interface, config)
343                 wallet.set_verifier(verifier)
344
345                 print_msg("Recovering wallet...")
346                 WalletSynchronizer(wallet, config).start()
347                 wallet.update()
348                 if wallet.is_found():
349                     print_msg("Recovery successful")
350                 else:
351                     print_msg("Warning: Found no history for this wallet")
352             else:
353                 wallet.synchronize()
354             wallet.fill_addressbook()
355             wallet.save()
356             print_msg("Wallet saved in '%s'"%wallet.config.path)
357         else:
358             wallet.init_seed(None)
359             wallet.synchronize() # there is no wallet thread 
360             wallet.save()
361             print_msg("Your wallet generation seed is: " + wallet.seed)
362             print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")
363             print_msg("Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:")
364             print_msg("\""+' '.join(mnemonic_encode(wallet.seed))+"\"")
365             print_msg("Wallet saved in '%s'"%wallet.config.path)
366             
367         if password:
368             wallet.update_password(wallet.seed, None, password)
369
370
371     # open session
372     if cmd not in offline_commands and not options.offline:
373         interface = Interface(config)
374         interface.register_callback('connected', lambda: sys.stderr.write("Connected to " + interface.connection_msg + "\n"))
375         interface.start()
376         wallet.interface = interface
377         verifier = WalletVerifier(interface, config)
378         wallet.set_verifier(verifier)
379         synchronizer = WalletSynchronizer(wallet, config)
380         synchronizer.start()
381         wallet.update()
382         wallet.save()
383
384
385                 
386     # important warning
387     if cmd in ['dumpprivkey', 'dumpprivkeys']:
388         print_msg("WARNING: ALL your private keys are secret.")
389         print_msg("Exposing a single private key can compromise your entire wallet!")
390         print_msg("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
391
392     # commands needing password
393     if cmd in protected_commands:
394         if wallet.use_encryption:
395             password = prompt_password('Password:', False)
396             if not password:
397                 print_msg("Error: Password required")
398                 exit(1)
399             # check password
400             try:
401                 seed = wallet.decode_seed(password)
402             except:
403                 print_msg("Error: This password does not decode this wallet.")
404                 exit(1)
405         else:
406             password = None
407             seed = wallet.seed
408     else:
409         password = None
410
411
412     # check and format the arguments
413     if cmd == 'importprivkey':
414         # See if they specificed a key on the cmd line, if not prompt
415         if len(args) == 1:
416             args[1] = prompt_password('Enter PrivateKey (will not echo):', False)
417
418     elif cmd == 'signmessage':
419         if len(args) < 3:
420             print_msg("Error: Invalid usage of signmessage.")
421             print_msg(known_commands[cmd])
422             sys.exit(1)
423         address = args[1]
424         message = ' '.join(args[2:])
425         if len(args) > 3:
426             print_msg("Warning: Message was reconstructed from several arguments:", repr(message))
427         args = [ cmd, address, message ]
428
429     elif cmd == 'verifymessage':
430         try:
431             address = args[1]
432             signature = args[2]
433             message = ' '.join(args[3:])
434         except:
435             print_msg("Error: Not all parameters were given, displaying help instead.")
436             print_msg(known_commands[cmd])
437             sys.exit(1)
438         if len(args) > 4:
439             print_msg("Warning: Message was reconstructed from several arguments:", repr(message))
440         args = [ cmd, address, signature, message]
441
442     elif cmd == 'signrawtransaction':
443         args = [ cmd, args[1], ast.literal_eval(args[2]) if len(args)>2 else [], ast.literal_eval(args[3]) if len(args)>3 else []]
444
445     elif cmd == 'createmultisig':
446         args = [ cmd, int(args[1]), ast.literal_eval(args[2])]
447
448     elif cmd == 'createrawtransaction':
449         args = [ cmd, ast.literal_eval(args[1]), ast.literal_eval(args[2])]
450
451     elif cmd == 'dumpprivkeys':
452         args = [cmd, wallet.all_addresses() if options.show_all else wallet.addresses + wallet.imported_keys.keys() ]
453
454     elif cmd=='addresses':
455         args = [cmd, options.show_all]
456                 
457     elif cmd == 'setlabel':
458         try:
459             tx = args[1]
460             label = ' '.join(args[2:])
461         except:
462             print_msg("Error. Syntax:  label <tx_hash> <text>")
463             sys.exit(1)
464         args = [ cmd, tx, label ]
465
466     elif cmd in ['payto', 'mktx']:
467
468         #is_temporary = False
469         from_addr = None
470         if options.from_addr:
471             from_addr = options.from_addr
472             if from_addr not in wallet.all_addresses():
473                 #is_temporary = True
474                 raise BaseException("address not in wallet")
475
476         try:
477             to_address = args[1]
478             amount = Decimal(args[2])
479             change_addr = None
480             label = ' '.join(args[3:])
481             if options.tx_fee: 
482                 options.tx_fee = Decimal(options.tx_fee)
483         except:
484             firstarg = cmd
485             cmd = 'help'
486
487         #if from_addr and is_temporary:
488         #    if from_addr.find(":") == -1:
489         #        keypair = from_addr + ":" + prompt_password('Private key:', False)
490         #    else:
491         #        keypair = from_addr
492         #        from_addr = keypair.split(':')[0]
493         #    if not wallet.import_key(keypair,password):
494         #        print_msg("Error: Invalid key pair")
495         #        exit(1)
496         #    wallet.history[from_addr] = interface.retrieve_history(from_addr)
497         #    wallet.update_tx_history()
498         #    change_addr = from_addr
499
500         if options.change_addr:
501             change_addr = options.change_addr
502             
503         args = [ 'mktx', to_address, amount, options.tx_fee, options.change_addr, from_addr ]
504
505         #if is_temporary:
506         #    wallet.imported_keys.pop(from_addr)
507         #    del(wallet.history[from_addr])
508         #wallet.save()
509
510
511
512     # run the command
513     if cmd == 'help':
514         cmd2 = firstarg
515         if cmd2 not in known_commands:
516             parser.print_help()
517             print_msg("Type 'electrum help <command>' to see the help for a specific command")
518             print_msg("Type 'electrum --help' to see the list of options")
519             print_msg("List of commands:", ', '.join(known_commands))
520         else:
521             print_msg(known_commands[cmd2])
522
523     elif cmd == 'deseed':
524         if not wallet.seed:
525             print_msg("Error: This wallet has no seed")
526         else:
527             ns = wallet.config.path + '.seedless'
528             print_msg("Warning: you are going to create a seedless wallet'\nIt will be saved in '%s'"%ns)
529             if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
530                 wallet.config.path = ns
531                 wallet.seed = ''
532                 wallet.config.set_key('seed','', True)
533                 for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = ''
534                 wallet.save()
535                 print_msg("Done.")
536             else:
537                 print_msg("Action canceled.")
538
539     elif cmd == 'eval':
540         print_msg(eval(args[1]))
541         wallet.save()
542
543     elif cmd == 'get':
544         key = args[1]
545         print_msg(wallet.config.get(key))
546
547     elif cmd == 'set':
548         key, value = args[1:3]
549         if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']:
550             wallet.config.set_key(key, value, True)
551             print_msg(True)
552         else:
553             print_msg(False)
554
555
556     elif cmd == 'password':
557         new_password = prompt_password('New password:')
558         wallet.update_password(seed, password, new_password)
559
560
561
562     else:
563         cmd_runner = Commands(wallet, interface)
564         func = eval('cmd_runner.' + cmd)
565         if password: 
566             cmd_runner.password = password
567         func(*args[1:])
568         
569
570     if cmd not in offline_commands and not options.offline:
571         verifier.stop()
572         synchronizer.stop()
573         interface.stop()
574         time.sleep(0.1)
575         sys.exit(0)