simplification
[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 pkgutil
21 import sys, os, time, json
22 import optparse
23 import platform
24 from decimal import Decimal
25
26 try:
27     import ecdsa  
28 except ImportError:
29     sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
30
31 try:
32     import aes
33 except ImportError:
34     sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
35
36
37 is_android = 'ANDROID_DATA' in os.environ
38
39 # load local module as electrum
40 if os.path.exists("lib") or is_android:
41     import imp
42     imp.load_module('electrum', *imp.find_module('lib'))
43     imp.load_module('electrum_gui', *imp.find_module('gui'))
44
45 from electrum import *
46
47
48 # get password routine
49 def prompt_password(prompt, confirm=True):
50     import getpass
51     if sys.stdin.isatty():
52         password = getpass.getpass(prompt)
53         if password and confirm:
54             password2 = getpass.getpass("Confirm: ")
55             if password != password2:
56                 sys.exit("Error: Passwords do not match.")
57     else:
58         password = raw_input(prompt)
59     if not password:
60         password = None
61     return password
62
63 def arg_parser():
64     usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands))
65     parser = optparse.OptionParser(prog=usage)
66     parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text")
67     parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
68     parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline")
69     parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
70     parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance of listed addresses")
71     parser.add_option("-l", "--labels", action="store_true", dest="show_labels", default=False, help="show the labels of listed addresses")
72     parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee")
73     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.")
74     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")
75     parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h")
76     parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
77     parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
78     parser.add_option("-P", "--portable", action="store_true", dest="portable", default=False, help="portable wallet")
79     parser.add_option("-L", "--lang", dest="language", default=None, help="defaut language used in GUI")
80     parser.add_option("-u", "--usb", dest="bitkey", action="store_true", help="Turn on support for hardware wallets (EXPERIMENTAL)")
81     return parser
82
83
84 if __name__ == '__main__':
85
86     parser = arg_parser()
87     options, args = parser.parse_args()
88     set_verbosity(options.verbose)
89
90     # config is an object passed to the various constructors (wallet, interface, gui)
91     if is_android:
92         config_options = {'wallet_path':"/sdcard/electrum.dat", 'portable':True, 'verbose':True, 'gui':'android', 'auto_cycle':True}
93     else:
94         config_options = eval(str(options))
95         for k, v in config_options.items():
96             if v is None: config_options.pop(k)
97
98     # Wallet migration on Electrum 1.7
99     # Todo: In time we could remove this again
100     if platform.system() == "Windows":
101         util.check_windows_wallet_migration()
102
103     config = SimpleConfig(config_options)
104     wallet = Wallet(config)
105
106
107     if len(args)==0:
108         url = None
109         cmd = 'gui'
110     elif len(args)==1 and re.match('^bitcoin:', args[0]):
111         url = args[0]
112         cmd = 'gui'
113     else:
114         cmd = args[0]
115        
116
117     if cmd == 'gui':
118         gui_name = config.get('gui','classic')
119         try:
120             gui = __import__('electrum_gui.gui_' + gui_name, fromlist=['electrum_gui'])
121         except ImportError:
122             sys.exit("Error: Unknown GUI: " + gui_name )
123         
124         interface = Interface(config, True)
125         wallet.interface = interface
126         interface.start(wait = False)
127         interface.send([('server.peers.subscribe',[])])
128
129         gui = gui.ElectrumGui(wallet, config)
130
131         found = config.wallet_file_exists
132         if not found:
133             a = gui.restore_or_create()
134             if not a: exit()
135             # select a server.
136             s = gui.network_dialog()
137
138             if a =='create':
139                 wallet.init_seed(None)
140             else:
141                 # ask for seed and gap.
142                 sg = gui.seed_dialog()
143                 if not sg: exit()
144                 seed, gap = sg
145                 if not seed: exit()
146                 wallet.gap_limit = gap
147                 if len(seed) == 128:
148                     wallet.seed = ''
149                     wallet.init_sequence(str(seed))
150                 else:
151                     wallet.init_seed(str(seed))
152             
153
154             # generate the first addresses, in case we are offline
155             if s is None or a == 'create':
156                 wallet.synchronize()
157             if a == 'create':
158                 # display seed
159                 gui.show_seed()
160
161         verifier = WalletVerifier(interface, config)
162         verifier.start()
163         wallet.set_verifier(verifier)
164         synchronizer = WalletSynchronizer(wallet, config)
165         synchronizer.start()
166
167         if not found and a == 'restore' and s is not None:
168             try:
169                 keep_it = gui.restore_wallet()
170                 wallet.fill_addressbook()
171             except:
172                 import traceback
173                 traceback.print_exc(file=sys.stdout)
174                 exit()
175
176             if not keep_it: exit()
177
178         if not found:
179             gui.password_dialog()
180
181         wallet.save()
182         gui.main(url)
183         wallet.save()
184
185         verifier.stop()
186         synchronizer.stop()
187         interface.stop()
188
189         # we use daemon threads, their termination is enforced.
190         # this sleep command gives them time to terminate cleanly. 
191         time.sleep(0.1)
192         sys.exit(0)
193
194     if cmd not in known_commands:
195         cmd = 'help'
196
197     if not config.wallet_file_exists and cmd not in ['help','create','restore']:
198         print_msg("Error: Wallet file not found.")
199         print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
200         sys.exit(0)
201     
202     if cmd in ['create', 'restore']:
203         if config.wallet_file_exists:
204             sys.exit("Error: Remove the existing wallet first!")
205         password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):")
206
207         server = config.get('server')
208         if not server: server = pick_random_server()
209         w_host, w_port, w_protocol = server.split(':')
210         host = raw_input("server (default:%s):"%w_host)
211         port = raw_input("port (default:%s):"%w_port)
212         protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol)
213         fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) )
214         gap = raw_input("gap limit (default 5):")
215         if host: w_host = host
216         if port: w_port = port
217         if protocol: w_protocol = protocol
218         wallet.config.set_key('server', w_host + ':' + w_port + ':' +w_protocol)
219         if fee: wallet.fee = float(fee)
220         if gap: wallet.gap_limit = int(gap)
221
222         if cmd == 'restore':
223             seed = raw_input("seed:")
224             try:
225                 seed.decode('hex')
226             except:
227                 print_error("Warning: Not hex, trying decode.")
228                 seed = mnemonic_decode( seed.split(' ') )
229             if not seed:
230                 sys.exit("Error: No seed")
231
232             if len(seed) == 128:
233                 wallet.seed = None
234                 wallet.init_sequence(str(seed))
235             else:
236                 wallet.init_seed( str(seed) )
237
238             if not options.offline:
239                 interface = Interface(config)
240                 if not interface.start(wait=True):
241                     print_msg("Not connected, aborting.")
242                     sys.exit(1)
243                 wallet.interface = interface
244                 verifier = WalletVerifier(interface, config)
245                 verifier.start()
246                 wallet.set_verifier(verifier)
247
248                 print_msg("Recovering wallet...")
249                 WalletSynchronizer(wallet, config).start()
250                 wallet.update()
251                 if wallet.is_found():
252                     print_msg("Recovery successful")
253                 else:
254                     print_msg("Warning: Found no history for this wallet")
255             else:
256                 wallet.synchronize()
257             wallet.fill_addressbook()
258             wallet.save()
259             print_msg("Wallet saved in '%s'"%wallet.config.path)
260         else:
261             wallet.init_seed(None)
262             wallet.synchronize() # there is no wallet thread 
263             wallet.save()
264             print_msg("Your wallet generation seed is: " + wallet.seed)
265             print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")
266             print_msg("Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:")
267             print_msg("\""+' '.join(mnemonic_encode(wallet.seed))+"\"")
268             print_msg("Wallet saved in '%s'"%wallet.config.path)
269             
270         if password:
271             wallet.update_password(wallet.seed, None, password)
272
273         # terminate
274         sys.exit(0)
275
276
277
278     # important warning
279     if cmd in ['dumpprivkey', 'dumpprivkeys']:
280         print_msg("WARNING: ALL your private keys are secret.")
281         print_msg("Exposing a single private key can compromise your entire wallet!")
282         print_msg("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
283
284     # commands needing password
285     if cmd in protected_commands:
286         if wallet.use_encryption:
287             password = prompt_password('Password:', False)
288             if not password:
289                 print_msg("Error: Password required")
290                 exit(1)
291             # check password
292             try:
293                 seed = wallet.decode_seed(password)
294             except:
295                 print_msg("Error: This password does not decode this wallet.")
296                 exit(1)
297         else:
298             password = None
299             seed = wallet.seed
300     else:
301         password = None
302
303
304     # add missing arguments, do type conversions
305     if cmd == 'importprivkey':
306         # See if they specificed a key on the cmd line, if not prompt
307         if len(args) == 1:
308             args[1] = prompt_password('Enter PrivateKey (will not echo):', False)
309
310     elif cmd == 'signrawtransaction':
311         args = [ cmd, args[1], json.loads(args[2]) if len(args)>2 else [], json.loads(args[3]) if len(args)>3 else []]
312
313     elif cmd == 'createmultisig':
314         args = [ cmd, int(args[1]), json.loads(args[2])]
315
316     elif cmd == 'createrawtransaction':
317         args = [ cmd, json.loads(args[1]), json.loads(args[2])]
318
319     elif cmd == 'listaddresses':
320         args = [cmd, options.show_all, options.show_balance, options.show_labels]
321
322     elif cmd in ['payto', 'mktx']:
323         args = [ 'mktx', args[1], Decimal(args[2]), Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, options.from_addr ]
324
325     elif cmd == 'help':
326         if len(args) < 2:
327             parser.print_help()
328             print_msg("Type 'electrum help <command>' to see the help for a specific command")
329             print_msg("Type 'electrum --help' to see the list of options")
330
331
332                 
333
334     # check the number of arguments
335     min_args, max_args, description, syntax, options_syntax = known_commands[cmd]
336     if len(args) - 1 < min_args:
337         print_msg("Not enough arguments")
338         print_msg("Syntax:", syntax)
339         sys.exit(1)
340
341     if max_args >= 0 and len(args) - 1 > max_args:
342         print_msg("too many arguments", args)
343         print_msg("Syntax:", syntax)
344         sys.exit(1)
345
346     if max_args < 0:
347         if len(args) > min_args + 1:
348             message = ' '.join(args[min_args:])
349             print_msg("Warning: Final argument was reconstructed from several arguments:", repr(message))
350             args = args[0:min_args] + [ message ]
351         
352
353
354
355
356     # open session
357     if cmd not in offline_commands and not options.offline:
358         interface = Interface(config)
359         interface.register_callback('connected', lambda: sys.stderr.write("Connected to " + interface.connection_msg + "\n"))
360         if not interface.start(wait=True):
361             print_msg("Not connected, aborting.")
362             sys.exit(1)
363         wallet.interface = interface
364         verifier = WalletVerifier(interface, config)
365         verifier.start()
366         wallet.set_verifier(verifier)
367         synchronizer = WalletSynchronizer(wallet, config)
368         synchronizer.start()
369         wallet.update()
370         wallet.save()
371
372
373     # run the command
374
375     if cmd == 'deseed':
376         if not wallet.seed:
377             print_msg("Error: This wallet has no seed")
378         else:
379             ns = wallet.config.path + '.seedless'
380             print_msg("Warning: you are going to create a seedless wallet'\nIt will be saved in '%s'"%ns)
381             if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
382                 wallet.config.path = ns
383                 wallet.seed = ''
384                 wallet.use_encryption = False
385                 wallet.config.set_key('seed','', True)
386                 for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = ''
387                 wallet.save()
388                 print_msg("Done.")
389             else:
390                 print_msg("Action canceled.")
391
392     elif cmd == 'eval':
393         print_msg(eval(args[1]))
394         wallet.save()
395
396     elif cmd == 'getconfig':
397         key = args[1]
398         print_msg(wallet.config.get(key))
399
400     elif cmd == 'setconfig':
401         key, value = args[1:3]
402         if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']:
403             wallet.config.set_key(key, value, True)
404             print_msg(True)
405         else:
406             print_msg(False)
407
408     elif cmd == 'password':
409         new_password = prompt_password('New password:')
410         wallet.update_password(seed, password, new_password)
411
412     else:
413         cmd_runner = Commands(wallet, interface)
414         func = eval('cmd_runner.' + cmd)
415         cmd_runner.password = password
416         try:
417             result = func(*args[1:])
418         except BaseException, e:
419             print_msg("Error: " + str(e))
420             sys.exit(1)
421             
422         if type(result) == str:
423             util.print_msg(result)
424         elif result is not None:
425             util.print_json(result)
426             
427         
428
429     if cmd not in offline_commands and not options.offline:
430         verifier.stop()
431         synchronizer.stop()
432         interface.stop()
433         time.sleep(0.1)
434         sys.exit(0)