Cleanup main script, with semantic changes:

The --offline flag applies only to GUI.
Commands must use the daemon if a daemon is running, otherwise they are run offline.
Commands that only require the wallet do not have the require_network flag.
This commit is contained in:
ThomasV 2015-12-23 15:59:32 +01:00
parent 93573282bf
commit fb8f9e55ef
2 changed files with 72 additions and 73 deletions

124
electrum
View File

@ -321,84 +321,84 @@ if __name__ == '__main__':
config_options['url'] = uri
config = SimpleConfig(config_options)
cmd_name = config.get('cmd')
cmdname = config.get('cmd')
# initialize plugins.
gui_name = config.get('gui', 'qt') if cmd_name == 'gui' else 'cmdline'
gui_name = config.get('gui', 'qt') if cmdname == 'gui' else 'cmdline'
plugins = Plugins(config, is_bundle or is_local or is_android, gui_name)
# run non-RPC commands separately
if cmd_name in ['create', 'restore', 'deseed']:
if cmdname in ['create', 'restore', 'deseed']:
run_non_RPC(config)
sys.exit(0)
# check if a daemon is running
server = get_daemon(config)
# if no daemon is running, run the command offline
if cmd_name not in ['gui', 'daemon']:
init_cmdline(config_options)
if server is None: #not (cmd.requires_network or cmd.requires_wallet) or config.get('offline'):
result = run_offline_command(config, config_options)
print_msg(json_encode(result))
sys.exit(0)
# daemon is running
if server is not None:
cmdname = config_options.get('cmd')
if cmdname == 'daemon':
result = server.daemon(config_options)
elif cmdname == 'gui':
if cmdname == 'gui':
if server is not None:
result = server.gui(config_options)
else:
result = server.run_cmdline(config_options)
if type(result) in [str, unicode]:
print_msg(result)
elif type(result) is dict and result.get('error'):
print_stderr(result.get('error'))
elif result is not None:
print_msg(json_encode(result))
sys.exit(0)
# daemon is not running
if cmd_name == 'gui':
if not config.get('offline'):
network = Network(config)
network.start()
plugins.start()
else:
network = None
gui = init_gui(config, network, plugins)
daemon = Daemon(config, network, gui)
daemon.start()
gui.main()
sys.exit(0)
elif cmd_name == 'daemon':
subcommand = config.get('subcommand')
if subcommand in ['status', 'stop']:
print_msg("Daemon not running")
sys.exit(1)
elif subcommand == 'start':
p = os.fork()
if p == 0:
if not config.get('offline'):
network = Network(config)
network.start()
plugins.start()
daemon = Daemon(config, network)
if config.get('websocket_server'):
from electrum import websockets
websockets.WebSocketServer(config, network).start()
if config.get('requests_dir'):
util.check_www_dir(config.get('requests_dir'))
daemon.start()
daemon.join()
else:
print_stderr("starting daemon (PID %d)"%p)
sys.exit(0)
network = None
gui = init_gui(config, network, plugins)
daemon = Daemon(config, network, gui)
daemon.start()
gui.main()
sys.exit(0)
elif cmdname == 'daemon':
if server is not None:
result = server.daemon(config_options)
else:
print_msg("syntax: electrum daemon <start|status|stop>")
sys.exit(1)
subcommand = config.get('subcommand')
if subcommand in ['status', 'stop']:
print_msg("Daemon not running")
sys.exit(1)
elif subcommand == 'start':
p = os.fork()
if p == 0:
network = Network(config)
network.start()
plugins.start()
daemon = Daemon(config, network)
if config.get('websocket_server'):
from electrum import websockets
websockets.WebSocketServer(config, network).start()
if config.get('requests_dir'):
util.check_www_dir(config.get('requests_dir'))
daemon.start()
daemon.join()
sys.exit(0)
else:
print_stderr("starting daemon (PID %d)"%p)
sys.exit(0)
else:
print_msg("syntax: electrum daemon <start|status|stop>")
sys.exit(1)
else:
print_msg("Network daemon is not running. Try 'electrum daemon start'\nIf you want to run this command offline, use the -o flag.")
sys.exit(1)
# command line
init_cmdline(config_options)
if server is not None:
result = server.run_cmdline(config_options)
else:
cmd = known_commands[cmdname]
if cmd.requires_network:
print_msg("Network daemon is not running. Try 'electrum daemon start'")
sys.exit(1)
else:
result = run_offline_command(config, config_options)
# print result
if type(result) in [str, unicode]:
print_msg(result)
elif type(result) is dict and result.get('error'):
print_stderr(result.get('error'))
elif result is not None:
print_msg(json_encode(result))
sys.exit(0)

View File

@ -160,7 +160,7 @@ class Commands:
"""
return self.network.synchronous_get(('blockchain.address.get_history', [address]))
@command('nw')
@command('w')
def listunspent(self):
"""List unspent outputs. Returns the list of unspent transaction
outputs in your wallet."""
@ -276,10 +276,9 @@ class Commands:
"""Return the public keys for a wallet address. """
return self.wallet.get_public_keys(address)
@command('nw')
@command('w')
def getbalance(self, account=None):
"""Return the balance of your wallet. If run with the --offline flag,
returns the last known balance."""
"""Return the balance of your wallet. """
if account is None:
c, u, x = self.wallet.get_balance()
else:
@ -421,21 +420,21 @@ class Commands:
self.wallet.sign_transaction(tx, self._password)
return tx
@command('wpn')
@command('wp')
def payto(self, destination, amount, tx_fee=None, from_addr=None, change_addr=None, nocheck=False, unsigned=False):
"""Create a transaction. """
domain = [from_addr] if from_addr else None
tx = self._mktx([(destination, amount)], tx_fee, change_addr, domain, nocheck, unsigned)
return tx.as_dict()
@command('wpn')
@command('wp')
def paytomany(self, outputs, tx_fee=None, from_addr=None, change_addr=None, nocheck=False, unsigned=False):
"""Create a multi-output transaction. """
domain = [from_addr] if from_addr else None
tx = self._mktx(outputs, tx_fee, change_addr, domain, nocheck, unsigned)
return tx.as_dict()
@command('wn')
@command('w')
def history(self):
"""Wallet history. Returns the transaction history of your wallet."""
balance = 0
@ -505,7 +504,7 @@ class Commands:
out.append(item)
return out
@command('nw')
@command('w')
def gettransaction(self, txid):
"""Retrieve a transaction. """
tx = self.wallet.transactions.get(txid) if self.wallet else None
@ -538,7 +537,7 @@ class Commands:
out['status'] = pr_str[out.get('status', PR_UNKNOWN)]
return out
@command('wn')
@command('w')
def getrequest(self, key):
"""Return a payment request"""
r = self.wallet.get_payment_request(key, self.config)
@ -551,7 +550,7 @@ class Commands:
# """<Not implemented>"""
# pass
@command('wn')
@command('w')
def listrequests(self, pending=False, expired=False, paid=False):
"""List the payment requests you made."""
out = self.wallet.get_sorted_requests(self.config)
@ -734,7 +733,6 @@ def get_parser():
group.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Show debugging information")
group.add_argument("-P", "--portable", action="store_true", dest="portable", default=False, help="Use local 'electrum_data' directory")
group.add_argument("-w", "--wallet", dest="wallet_path", help="wallet path")
group.add_argument("-o", "--offline", action="store_true", dest="offline", default=False, help="Run offline")
# create main parser
parser = argparse.ArgumentParser(
parents=[parent_parser],
@ -745,6 +743,7 @@ def get_parser():
parser_gui.add_argument("url", nargs='?', default=None, help="bitcoin URI (or bip70 file)")
#parser_gui.set_defaults(func=run_gui)
parser_gui.add_argument("-g", "--gui", dest="gui", help="select graphical user interface", choices=['qt', 'lite', 'gtk', 'kivy', 'text', 'stdio', 'jsonrpc'])
parser_gui.add_argument("-o", "--offline", action="store_true", dest="offline", default=False, help="Run offline")
parser_gui.add_argument("-m", action="store_true", dest="hide_gui", default=False, help="hide GUI on startup")
parser_gui.add_argument("-L", "--lang", dest="language", default=None, help="default language used in GUI")
add_network_options(parser_gui)