start network daemon automatically when needed
[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 from decimal import Decimal
20 import json
21 import optparse
22 import os
23 import re
24 import sys
25 import time
26 import traceback
27
28 try:
29     import ecdsa  # todo: 'ecdsa' imported but unused
30 except ImportError:
31     sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
32
33 try:
34     import aes  # todo: 'aes' imported but unused
35 except ImportError:
36     sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
37
38
39 is_local = os.path.dirname(os.path.realpath(__file__)) == os.getcwd()
40 is_android = 'ANDROID_DATA' in os.environ
41
42 import __builtin__
43 __builtin__.use_local_modules = is_local or is_android
44
45 # load local module as electrum
46 if __builtin__.use_local_modules:
47     import imp
48     imp.load_module('electrum', *imp.find_module('lib'))
49     imp.load_module('electrum_gui', *imp.find_module('gui'))
50
51 from electrum import *  # todo: import * is generally frowned upon. should import just what is used
52
53
54 # get password routine
55 def prompt_password(prompt, confirm=True):
56     import getpass
57     if sys.stdin.isatty():
58         password = getpass.getpass(prompt)
59         if password and confirm:
60             password2 = getpass.getpass("Confirm: ")
61             if password != password2:
62                 sys.exit("Error: Passwords do not match.")
63     else:
64         password = raw_input(prompt)
65     if not password:
66         password = None
67     return password
68
69
70 def arg_parser():
71     usage = "%prog [options] command"
72     parser = optparse.OptionParser(prog=usage, add_help_option=False)
73     parser.add_option("-h", "--help", action="callback", callback=print_help_cb, help="show this help text")
74     parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk, text or stdio")
75     parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
76     parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline")
77     parser.add_option("-C", "--concealed", action="store_true", dest="concealed", default=False, help="don't echo seed to console when restoring")
78     parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
79     parser.add_option("-l", "--labels", action="store_true", dest="show_labels", default=False, help="show the labels of listed addresses")
80     parser.add_option("-f", "--fee", dest="tx_fee", default=None, help="set tx fee")
81     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.")
82     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")
83     parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is either t (tcp), h (http), s (tcp+ssl), or g (https)")
84     parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
85     parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
86     parser.add_option("-P", "--portable", action="store_true", dest="portable", default=False, help="portable wallet")
87     parser.add_option("-L", "--lang", dest="language", default=None, help="defaut language used in GUI")
88     parser.add_option("-u", "--usb", dest="bitkey", action="store_true", help="Turn on support for hardware wallets (EXPERIMENTAL)")
89     parser.add_option("-G", "--gap", dest="gap_limit", default=None, help="gap limit")
90     parser.add_option("-W", "--password", dest="password", default=None, help="set password for usage with commands (currently only implemented for create command, do not use it for longrunning gui session since the password is visible in /proc)")
91     parser.add_option("-1", "--oneserver", action="store_true", dest="oneserver", default=False, help="connect to one server only")
92     parser.add_option("--bip32", action="store_true", dest="bip32", default=False, help="bip32")
93     return parser
94
95
96 def print_help(parser):
97     parser.print_help()
98     print_msg("Type 'electrum help <command>' to see the help for a specific command")
99     print_msg("Type 'electrum --help' to see the list of options")
100     run_command(known_commands['help'])
101     sys.exit(1)
102
103
104 def print_help_cb(self, opt, value, parser):
105     print_help(parser)
106
107
108 def run_command(cmd, password=None, args=[]):
109     import xmlrpclib, socket
110     cmd_runner = Commands(wallet, network)
111     func = getattr(cmd_runner, cmd.name)
112     cmd_runner.password = password
113
114     if cmd.requires_network and not options.offline:
115         cmd_runner.network = xmlrpclib.ServerProxy('http://localhost:8000')
116
117         while True:
118             try:
119                 if cmd_runner.network.ping() == 'pong':
120                     break
121             except socket.error:
122                 if cmd.name != 'daemon':
123                     start_daemon()
124                 else:
125                     print "Daemon not running"
126                     sys.exit(1)
127
128         if wallet:
129             wallet.start_threads(cmd_runner.network)
130             wallet.update()
131     else:
132         cmd_runner.network = None
133
134     try:
135         result = func(*args[1:])
136     except Exception:
137         print "ecxeption"
138         traceback.print_exc(file=sys.stdout)
139         sys.exit(1)
140
141
142     if cmd.requires_network and not options.offline:
143         if wallet:
144             wallet.stop_threads()
145
146
147     if type(result) == str:
148         util.print_msg(result)
149     elif result is not None:
150         util.print_json(result)
151
152
153
154 def start_server():
155     network = Network(config)
156     if not network.start(wait=True):
157         print_msg("Not connected, aborting.")
158         sys.exit(1)
159     print_msg("Network daemon connected to " + network.interface.connection_msg)
160     from SimpleXMLRPCServer import SimpleXMLRPCServer
161     server = SimpleXMLRPCServer(('localhost',8000), allow_none=True, logRequests=False)
162     server.register_function(lambda: 'pong', 'ping')
163     server.register_function(network.synchronous_get, 'synchronous_get')
164     server.register_function(network.get_servers, 'get_servers')
165     server.register_function(network.main_server, 'main_server')
166     server.register_function(network.send, 'send')
167     server.register_function(network.subscribe, 'subscribe')
168     server.register_function(network.is_connected, 'is_connected')
169     server.register_function(network.is_up_to_date, 'is_up_to_date')
170     server.register_function(lambda: setattr(server,'running', False), 'stop')
171     return server
172
173 def start_daemon():
174     pid = os.fork()
175     if (pid == 0): # The first child.
176         os.chdir("/")
177         os.setsid()
178         os.umask(0)
179         pid2 = os.fork()
180         if (pid2 == 0):  # Second child
181             server = start_server()
182             server.running = True
183             while server.running:
184                 server.handle_request()
185             print_msg("Daemon stopped")
186         sys.exit(0)
187
188     time.sleep(2)
189
190
191 if __name__ == '__main__':
192
193     parser = arg_parser()
194     options, args = parser.parse_args()
195     if options.portable and options.wallet_path is None:
196         options.electrum_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data')
197
198     # config is an object passed to the various constructors (wallet, interface, gui)
199     if is_android:
200         config_options = {
201             'portable': True,
202             'verbose': True,
203             'gui': 'android',
204             'auto_cycle': True,
205         }
206     else:
207         config_options = eval(str(options))
208         for k, v in config_options.items():
209             if v is None:
210                 config_options.pop(k)
211
212     set_verbosity(config_options.get('verbose'))
213
214     config = SimpleConfig(config_options)
215
216     if len(args) == 0:
217         url = None
218         cmd = 'gui'
219     elif len(args) == 1 and re.match('^bitcoin:', args[0]):
220         url = args[0]
221         cmd = 'gui'
222     else:
223         cmd = args[0]
224
225     if cmd == 'gui':
226         gui_name = config.get('gui', 'classic')
227         if gui_name in ['lite', 'classic']:
228             gui_name = 'qt'
229         try:
230             gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui'])
231         except ImportError:
232             traceback.print_exc(file=sys.stdout)
233             sys.exit()
234             #sys.exit("Error: Unknown GUI: " + gui_name )
235
236         # network interface
237         if not options.offline:
238             network = Network(config)
239             network.start()
240         else:
241             network = None
242
243         gui = gui.ElectrumGui(config, network)
244         gui.main(url)
245
246         if network:
247             network.stop()
248
249         # we use daemon threads, their termination is enforced.
250         # this sleep command gives them time to terminate cleanly.
251         time.sleep(0.1)
252         sys.exit(0)
253
254     if cmd not in known_commands:
255         cmd = 'help'
256
257     cmd = known_commands[cmd]
258
259     # instanciate wallet for command-line
260     storage = WalletStorage(config)
261
262
263     if cmd.name in ['create', 'restore']:
264         if storage.file_exists:
265             sys.exit("Error: Remove the existing wallet first!")
266         if options.password is not None:
267             password = options.password
268         else:
269             password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):")
270
271         # if config.server is set, the user either passed the server on command line
272         # or chose it previously already. if he didn't pass a server on the command line,
273         # we just pick up a random one.
274         if not config.get('server'):
275             config.set_key('server', pick_random_server())
276
277         #fee = options.tx_fee if options.tx_fee else raw_input("fee (default:%s):" % (str(Decimal(wallet.fee)/100000000)))
278         #gap = options.gap_limit if options.gap_limit else raw_input("gap limit (default 5):")
279         #if fee:
280         #    wallet.set_fee(float(fee)*100000000)
281         #if gap:
282         #    wallet.change_gap_limit(int(gap))
283
284         if cmd.name == 'restore':
285             import getpass
286             seed = getpass.getpass(prompt="seed:", stream=None) if options.concealed else raw_input("seed:")
287             wallet = Wallet.from_seed(str(seed),storage)
288             if not wallet:
289                 sys.exit("Error: Invalid seed")
290             wallet.save_seed(password)
291             if not options.offline:
292                 network = Network(config)
293                 network.start()
294                 wallet.start_threads(network)
295                 print_msg("Recovering wallet...")
296                 wallet.restore(lambda x: x)
297                 if wallet.is_found():
298                     print_msg("Recovery successful")
299                 else:
300                     print_msg("Warning: Found no history for this wallet")
301             else:
302                 wallet.synchronize()
303                 print_msg("Warning: This wallet was restored offline. It may contain more addresses than displayed.")
304
305         else:
306             wallet = Wallet(storage)
307             wallet.init_seed(None)
308             wallet.save_seed(password)
309             wallet.synchronize()
310             print_msg("Your wallet generation seed is:\n\"%s\"" % wallet.get_mnemonic(password))
311             print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")
312
313         print_msg("Wallet saved in '%s'" % wallet.storage.path)
314
315         # terminate
316         sys.exit(0)
317
318
319     if cmd.name not in ['create', 'restore'] and cmd.requires_wallet and not storage.file_exists:
320         print_msg("Error: Wallet file not found.")
321         print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
322         sys.exit(0)
323
324
325     if cmd.requires_wallet:
326         wallet = Wallet(storage)
327     else:
328         wallet = None
329
330
331     # important warning
332     if cmd.name in ['dumpprivkey', 'dumpprivkeys']:
333         print_msg("WARNING: ALL your private keys are secret.")
334         print_msg("Exposing a single private key can compromise your entire wallet!")
335         print_msg("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
336
337     # commands needing password
338     if cmd.requires_password:
339         if wallet.seed == '':
340             seed = ''
341             password = None
342         elif wallet.use_encryption:
343             password = prompt_password('Password:', False)
344             if not password:
345                 print_msg("Error: Password required")
346                 sys.exit(1)
347             # check password
348             try:
349                 seed = wallet.get_seed(password)
350             except Exception:
351                 print_msg("Error: This password does not decode this wallet.")
352                 sys.exit(1)
353         else:
354             password = None
355             seed = wallet.get_seed(None)
356     else:
357         password = None
358
359     # add missing arguments, do type conversions
360     if cmd.name == 'importprivkey':
361         # See if they specificed a key on the cmd line, if not prompt
362         if len(args) == 1:
363             args[1] = prompt_password('Enter PrivateKey (will not echo):', False)
364
365     elif cmd.name == 'signrawtransaction':
366         args = [cmd, args[1], json.loads(args[2]) if len(args) > 2 else [], json.loads(args[3]) if len(args) > 3 else []]
367
368     elif cmd.name == 'createmultisig':
369         args = [cmd, int(args[1]), json.loads(args[2])]
370
371     elif cmd.name == 'createrawtransaction':
372         args = [cmd, json.loads(args[1]), json.loads(args[2])]
373
374     elif cmd.name == 'listaddresses':
375         args = [cmd, options.show_all, options.show_labels]
376
377     elif cmd.name in ['payto', 'mktx']:
378         domain = [options.from_addr] if options.from_addr else None
379         args = ['mktx', args[1], Decimal(args[2]), Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, domain]
380
381     elif cmd.name in ['paytomany', 'mksendmanytx']:
382         domain = [options.from_addr] if options.from_addr else None
383         outputs = []
384         for i in range(1, len(args), 2):
385             if len(args) < i+2:
386                 print_msg("Error: Mismatched arguments.")
387                 sys.exit(1)
388             outputs.append((args[i], Decimal(args[i+1])))
389         args = ['mksendmanytx', outputs, Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, domain]
390
391     elif cmd.name == 'help':
392         if len(args) < 2:
393             print_help(parser)
394
395     # check the number of arguments
396     if len(args) - 1 < cmd.min_args:
397         print_msg("Not enough arguments")
398         print_msg("Syntax:", cmd.syntax)
399         sys.exit(1)
400
401     if cmd.max_args >= 0 and len(args) - 1 > cmd.max_args:
402         print_msg("too many arguments", args)
403         print_msg("Syntax:", cmd.syntax)
404         sys.exit(1)
405
406     if cmd.max_args < 0:
407         if len(args) > cmd.min_args + 1:
408             message = ' '.join(args[cmd.min_args:])
409             print_msg("Warning: Final argument was reconstructed from several arguments:", repr(message))
410             args = args[0:cmd.min_args] + [message]
411
412
413
414     # run the command
415     if cmd.name == 'deseed':
416         if not wallet.seed:
417             print_msg("Error: This wallet has no seed")
418         else:
419             ns = wallet.storage.path + '.seedless'
420             print_msg("Warning: you are going to create a seedless wallet'\nIt will be saved in '%s'" % ns)
421             if raw_input("Are you sure you want to continue? (y/n) ") in ['y', 'Y', 'yes']:
422                 wallet.storage.path = ns
423                 wallet.seed = ''
424                 wallet.storage.put('seed', '', True)
425                 wallet.use_encryption = False
426                 wallet.storage.put('use_encryption', wallet.use_encryption, True)
427                 for k in wallet.imported_keys.keys():
428                     wallet.imported_keys[k] = ''
429                 wallet.storage.put('imported_keys', wallet.imported_keys, True)
430                 print_msg("Done.")
431             else:
432                 print_msg("Action canceled.")
433
434     elif cmd.name == 'getconfig':
435         key = args[1]
436         out = config.get(key)
437         print_msg(out)
438
439     elif cmd.name == 'setconfig':
440         key, value = args[1:3]
441         config.set_key(key, value, True)
442         print_msg(True)
443
444     elif cmd.name == 'password':
445         new_password = prompt_password('New password:')
446         wallet.update_password(password, new_password)
447
448     else:
449         run_command(cmd, password, args)
450
451
452     time.sleep(0.1)
453     sys.exit(0)