electrum

Electrum Bitcoin wallet
git clone https://git.parazyd.org/electrum
Log | Files | Refs | Submodules

commit 3ddbbc1008685d80ad3b7ab1a5f83c769da946f9
parent 3195b94f2868107bc97949475ec5a8cf3d73e535
Author: ThomasV <thomasv@gitorious>
Date:   Thu, 28 May 2015 15:22:30 +0200

Parse arguments with argparse.
Move parser to commands.py

Diffstat:
Melectrum | 424+++++++++++++++++++++++++++++++++----------------------------------------------
Mlib/commands.py | 240++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
2 files changed, 337 insertions(+), 327 deletions(-)

diff --git a/electrum b/electrum @@ -19,7 +19,6 @@ from decimal import Decimal import json -import optparse import os import re import ast @@ -72,10 +71,11 @@ if is_bundle or is_local or is_android: from electrum import util -from electrum import SimpleConfig, Network, Wallet, WalletStorage, NetworkProxy, Commands, known_commands, pick_random_server +from electrum import SimpleConfig, Network, Wallet, WalletStorage, NetworkProxy from electrum.util import print_msg, print_error, print_stderr, print_json, set_verbosity, InvalidPassword from electrum.daemon import get_daemon from electrum.plugins import init_plugins +from electrum.commands import get_parser, known_commands, Commands # get password routine @@ -94,207 +94,93 @@ def prompt_password(prompt, confirm=True): return password -def arg_parser(): - usage = "%prog [options] command" - parser = optparse.OptionParser(usage=usage, add_help_option=False) - parser.add_option("-h", "--help", action="callback", callback=print_help_cb, help="show this help text") - parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk, text or stdio") - parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path") - parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline") - parser.add_option("-C", "--concealed", action="store_true", dest="concealed", default=False, help="don't echo seed to console when restoring") - parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses") - parser.add_option("-l", "--labels", action="store_true", dest="show_labels", default=False, help="show the labels of listed addresses") - parser.add_option("-f", "--fee", dest="tx_fee", default=None, help="set tx fee") - 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.") - 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") - 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)") - parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http") - parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information") - parser.add_option("-P", "--portable", action="store_true", dest="portable", default=False, help="portable wallet") - parser.add_option("-L", "--lang", dest="language", default=None, help="default language used in GUI") - parser.add_option("-G", "--gap", dest="gap_limit", default=None, help="gap limit") - 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)") - parser.add_option("-1", "--oneserver", action="store_true", dest="oneserver", default=False, help="connect to one server only") - parser.add_option("--mpk", dest="mpk", default=False, help="restore from master public key") - parser.add_option("-m", action="store_true", dest="hide_gui", default=False, help="hide GUI on startup") - parser.add_option("--nbits", dest="nbits", default="128", help="number of bits for make_seed") - parser.add_option("--entropy", dest="entropy", default="1", help="custom entropy for make_seed") - return parser - - -def print_help(parser): - parser.print_help() - print_msg("Type 'electrum help <command>' to see the help for a specific command") - print_msg("Type 'electrum --help' to see the list of options") - run_command(known_commands['help']) - - -def print_help_cb(self, opt, value, parser): - print_help(parser) - sys.exit(1) - - -def run_command(cmd, password=None, args=None): - if args is None: - args = [] # Do not use mutables as default values! - if cmd.requires_network and not options.offline: - s = get_daemon(config, False) - if not s: - print_msg("Network daemon is not running. Try 'electrum daemon start'") + +def run_gui(config): + url = config.get('url') + if url: + if os.path.exists(url): + # assume this is a payment request + url = "bitcoin:?r=file://"+ os.path.join(os.getcwd(), cmd) + + if not re.match('^bitcoin:', url): + print_stderr('unknown command:', url) sys.exit(1) + + gui_name = config.get('gui', 'qt') + if gui_name in ['lite', 'classic']: + gui_name = 'qt' + + try: + gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui']) + except ImportError: + traceback.print_exc(file=sys.stdout) + sys.exit() + + # network interface + if not config.get('offline'): + s = get_daemon(config, False) + if s: + print_msg("Connected to daemon") network = NetworkProxy(s, config) network.start() - while network.is_connecting(): - time.sleep(0.1) - if not network.is_connected(): - print_msg("daemon is not connected") - sys.exit(1) - if wallet: - wallet.start_threads(network) - wallet.update() else: network = None - cmd_runner = Commands(wallet, network) - func = getattr(cmd_runner, cmd.name) - cmd_runner.password = password - try: - result = func(*args[1:]) - except Exception: - traceback.print_exc(file=sys.stdout) - sys.exit(1) - + gui = gui.ElectrumGui(config, network) + gui.main(url) - if cmd.requires_network and not options.offline: - if wallet: - wallet.stop_threads() + if network: network.stop() + sys.exit(0) - if type(result) == str: - print_msg(result) - elif result is not None: - print_json(result) - - - -if __name__ == '__main__': - - # on osx, delete Process Serial Number arg generated for apps launched in Finder - sys.argv = filter(lambda x: not x.startswith('-psn'), sys.argv) - - wallet = None - parser = arg_parser() - options, args = parser.parse_args() - if options.portable and options.wallet_path is None: - options.electrum_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data') - - # config is an object passed to the various constructors (wallet, interface, gui) - if is_android: - config_options = { - 'portable': True, - 'verbose': True, - 'gui': 'android', - 'auto_connect': True, - } - else: - config_options = eval(str(options)) - for k, v in config_options.items(): - if v is None: - config_options.pop(k) - if config_options.get('server'): - config_options['auto_connect'] = False - - set_verbosity(config_options.get('verbose')) - config = SimpleConfig(config_options) - assert os.path.exists(requests.utils.DEFAULT_CA_BUNDLE_PATH) - if len(args) == 0: - url = None - cmd = 'gui' - elif len(args) == 1 and re.match('^bitcoin:', args[0]): - url = args[0] - cmd = 'gui' - elif len(args) == 1 and args[0] not in known_commands and os.path.exists(args[0]): - # fixme: assume this is a payment request - url = "bitcoin:?r=file://"+ os.path.join(os.getcwd(), args[0]) - cmd = 'gui' +def run_daemon(config): + cmd = config.get('subcommand') + if cmd not in ['start', 'stop', 'status']: + print_msg("syntax: electrum daemon <start|status|stop>") + sys.exit(1) + s = get_daemon(config, False) + if cmd == 'start': + if s: + print_msg("Daemon already running") + sys.exit(1) + get_daemon(config, True) + sys.exit(0) + elif cmd in ['status','stop']: + if not s: + print_msg("Daemon not running") + sys.exit(1) + network = NetworkProxy(s, config) + network.start() + if cmd == 'status': + print_json({ + 'path': network.config.path, + 'server': network.get_parameters()[0], + 'blockchain_height': network.get_local_height(), + 'server_height': network.get_server_height(), + 'nodes': network.get_interfaces(), + 'connected': network.is_connected() + }) + elif cmd == 'stop': + network.stop_daemon() + print_msg("Daemon stopped") + network.stop() else: - cmd = args[0] + print "unknown command \"%s\""% arg + sys.exit(0) - gui_name = config.get('gui', 'qt') if cmd == 'gui' else 'cmdline' - if gui_name in ['lite', 'classic']: - gui_name = 'qt' - # initialize plugins. - init_plugins(config, is_bundle or is_local or is_android, gui_name) - if gui_name != 'cmdline': - try: - gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui']) - except ImportError: - traceback.print_exc(file=sys.stdout) - sys.exit() - #sys.exit("Error: Unknown GUI: " + gui_name ) - - # network interface - if not options.offline: - s = get_daemon(config, False) - if s: - print_msg("Connected to daemon") - network = NetworkProxy(s, config) - network.start() - else: - network = None - gui = gui.ElectrumGui(config, network) - gui.main(url) - if network: - network.stop() +def run_cmdline(config): - sys.exit(0) + cmdname = config.get('cmd') + cmd = known_commands[cmdname] - if cmd == 'daemon': - arg = args[1] if len(args)>1 else None - if arg not in ['start', 'stop', 'status']: - print_msg("syntax: electrum daemon <start|status|stop>") - sys.exit(1) - s = get_daemon(config, False) - if arg == 'start': - if s: - print_msg("Daemon already running") - sys.exit(1) - get_daemon(config, True) - sys.exit(0) - elif arg in ['status','stop']: - if not s: - print_msg("Daemon not running") - sys.exit(1) - network = NetworkProxy(s, config) - network.start() - if arg == 'status': - print_json({ - 'path': network.config.path, - 'server': network.get_parameters()[0], - 'blockchain_height': network.get_local_height(), - 'server_height': network.get_server_height(), - 'nodes': network.get_interfaces(), - 'connected': network.is_connected() - }) - elif arg == 'stop': - network.stop_daemon() - print_msg("Daemon stopped") - network.stop() - else: - print "unknown command \"%s\""% arg - sys.exit(0) - - - if cmd not in known_commands: - cmd = 'help' - - cmd = known_commands[cmd] + # arguments passed to function + args = map(lambda x: config.get(x), cmd.params) # instanciate wallet for command-line storage = WalletStorage(config.get_wallet_path()) @@ -302,36 +188,28 @@ if __name__ == '__main__': if cmd.name in ['create', 'restore']: if storage.file_exists: sys.exit("Error: Remove the existing wallet first!") - if options.password is not None: - password = options.password - elif cmd.name == 'restore' and options.mpk: + if config.get('password') is not None: + password = config.get('password') + elif cmd.name == 'restore' and config.get('mpk'): password = None else: password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):") - # If config doesn't have a server, network.py will pick a random one - - #fee = options.tx_fee if options.tx_fee else raw_input("fee (default:%s):" % (str(Decimal(wallet.fee)/100000000))) - #gap = options.gap_limit if options.gap_limit else raw_input("gap limit (default 5):") - #if fee: - # wallet.set_fee(float(fee)*100000000) - #if gap: - # wallet.change_gap_limit(int(gap)) - if cmd.name == 'restore': - if options.mpk: - if Wallet.is_old_mpk(options.mpk): - wallet = Wallet.from_old_mpk(options.mpk, storage) - if Wallet.is_xpub(options.mpk): - wallet = Wallet.from_xpub(options.mpk, storage) + mpk = config.get('mpk') + if mpk: + if Wallet.is_old_mpk(mpk): + wallet = Wallet.from_old_mpk(mpk, storage) + if Wallet.is_xpub(mpk): + wallet = Wallet.from_xpub(mpk, storage) else: import getpass - seed = getpass.getpass(prompt="seed:", stream=None) if options.concealed else raw_input("seed:") + seed = getpass.getpass(prompt="seed:", stream=None) if config.get('concealed') else raw_input("seed:") if not Wallet.is_seed(seed): sys.exit("Error: Invalid seed") wallet = Wallet.from_seed(seed, password, storage) - if not options.offline: + if not config.get('offline'): s = get_daemon(config, False) network = NetworkProxy(s, config) network.start() @@ -356,25 +234,20 @@ if __name__ == '__main__': print_msg("Your wallet generation seed is:\n\"%s\"" % seed) print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.") - print_msg("Wallet saved in '%s'" % wallet.storage.path) - # terminate sys.exit(0) - if cmd.name not in ['create', 'restore'] and cmd.requires_wallet and not storage.file_exists: print_msg("Error: Wallet file not found.") print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option") sys.exit(0) - if cmd.requires_wallet: wallet = Wallet(storage) else: wallet = None - # important warning if cmd.name in ['dumpprivkey', 'dumpprivkeys']: print_stderr("WARNING: ALL your private keys are secret.") @@ -399,6 +272,25 @@ if __name__ == '__main__': else: password = None + # start network threads + if cmd.requires_network and not config.get('offline'): + s = get_daemon(config, False) + if not s: + print_msg("Network daemon is not running. Try 'electrum daemon start'") + sys.exit(1) + network = NetworkProxy(s, config) + network.start() + while network.is_connecting(): + time.sleep(0.1) + if not network.is_connected(): + print_msg("daemon is not connected") + sys.exit(1) + if wallet: + wallet.start_threads(network) + wallet.update() + else: + network = None + # add missing arguments, do type conversions if (cmd.name == 'importprivkey' and len(args)==1)\ or (cmd.name == 'signtxwithkey' and len(args)==2): @@ -406,56 +298,33 @@ if __name__ == '__main__': args.append(prompt_password('Enter PrivateKey (will not echo):', False)) elif cmd.name == 'createmultisig': - args = [cmd, int(args[1]), json.loads(args[2])] + args = [int(args[0]), json.loads(args[1])] elif cmd.name == 'createrawtransaction': - args = [cmd, json.loads(args[1]), json.loads(args[2])] + args = [json.loads(args[0]), json.loads(args[2])] elif cmd.name == 'listaddresses': - args = [cmd, options.show_all, options.show_labels] + args = [config.get('show_all'), config.get('show_labels')] elif cmd.name == 'make_seed': - args = [cmd, int(options.nbits), long(options.entropy), options.language] + args = [int(config.get('nbits')), long(config.get('entropy')), config.get('language')] elif cmd.name in ['payto', 'mktx']: - domain = [options.from_addr] if options.from_addr else None - args = ['mktx', args[1], Decimal(args[2]), Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, domain] + domain = [config.get('from_addr')] if config.get('from_addr') else None + args = [args[0], Decimal(args[1]), Decimal(config.get('tx_fee')) if config.get('tx_fee') else None, config.get('change_addr'), domain] elif cmd.name in ['paytomany', 'mksendmanytx']: - domain = [options.from_addr] if options.from_addr else None - outputs = [] - for i in range(1, len(args), 2): - if len(args) < i+2: - print_msg("Error: Mismatched arguments.") - sys.exit(1) - outputs.append((args[i], Decimal(args[i+1]))) - args = ['mksendmanytx', outputs, Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, domain] + domain = [config.get('from_addr')] if config.get('from_addr') else None + args = [args[0], Decimal(config.get('tx_fee')) if config.get('tx_fee') else None, config.get('change_addr'), domain] elif cmd.name == 'help': - if len(args) < 2: + if len(args) < 1: print_help(parser) sys.exit(1) - # check the number of arguments - if len(args) - 1 < cmd.min_args: - print_msg("Not enough arguments") - print_msg("Syntax:", cmd.syntax) - sys.exit(1) - - if cmd.max_args >= 0 and len(args) - 1 > cmd.max_args: - print_msg("too many arguments", args) - print_msg("Syntax:", cmd.syntax) - sys.exit(1) - - if cmd.max_args < 0: - if len(args) > cmd.min_args + 1: - message = ' '.join(args[cmd.min_args:]) - print_msg("Warning: Final argument was reconstructed from several arguments:", repr(message)) - args = args[0:cmd.min_args] + [message] - if cmd.name == 'check_seed': - args.append(long(options.entropy)) - args.append(options.language) + args.append(long(config.get('entropy'))) + args.append(config.get('language')) # run the command @@ -479,12 +348,12 @@ if __name__ == '__main__': print_msg("Action canceled.") elif cmd.name == 'getconfig': - key = args[1] + key = args[0] out = config.get(key) print_msg(out) elif cmd.name == 'setconfig': - key, value = args[1:3] + key, value = args[0:2] try: value = ast.literal_eval(value) except: @@ -497,6 +366,71 @@ if __name__ == '__main__': wallet.update_password(password, new_password) else: - run_command(cmd, password, args) + cmd_runner = Commands(wallet, network) + func = getattr(cmd_runner, cmd.name) + cmd_runner.password = password + try: + result = func(*args) + except Exception: + traceback.print_exc(file=sys.stdout) + sys.exit(1) + + if type(result) == str: + print_msg(result) + elif result is not None: + print_json(result) + + # shutdown wallet and network + if cmd.requires_network and not config.get('offline'): + if wallet: + wallet.stop_threads() + network.stop() + + + + +if __name__ == '__main__': + + # on osx, delete Process Serial Number arg generated for apps launched in Finder + sys.argv = filter(lambda x: not x.startswith('-psn'), sys.argv) + + # old 'help' syntax + if sys.argv[1] == 'help': + sys.argv.remove('help') + sys.argv.append('-h') + + parser = get_parser(run_gui, run_daemon, run_cmdline) + args = parser.parse_args() + + if args.portable and args.wallet_path is None: + args.electrum_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data') + + # config is an object passed to the various constructors (wallet, interface, gui) + if is_android: + config_options = { + 'portable': True, + 'verbose': True, + 'gui': 'android', + 'auto_connect': True, + } + else: + config_options = args.__dict__ + for k, v in config_options.items(): + if v is None: + config_options.pop(k) + if config_options.get('server'): + config_options['auto_connect'] = False + + set_verbosity(config_options.get('verbose')) + config = SimpleConfig(config_options) + + assert os.path.exists(requests.utils.DEFAULT_CA_BUNDLE_PATH) + + gui_name = config.get('gui', 'qt') if args.cmd == 'gui' else 'cmdline' + + # initialize plugins. + init_plugins(config, is_bundle or is_local or is_android, gui_name) + # call function attached to parser + args.func(config) sys.exit(0) diff --git a/lib/commands.py b/lib/commands.py @@ -16,9 +16,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. +import sys import datetime import time import copy +import argparse + from util import print_msg, format_satoshis, print_stderr from bitcoin import is_valid, hash_160_to_bc_address, hash_160 from decimal import Decimal @@ -27,92 +30,175 @@ from transaction import Transaction class Command: - def __init__(self, name, min_args, max_args, requires_network, requires_wallet, requires_password, description, syntax = '', options_syntax = ''): + def __init__(self, name, requires_network, requires_wallet, requires_password, params, options, description): self.name = name - self.min_args=min_args - self.max_args = max_args + self.params = params + self.options = options self.requires_network = requires_network self.requires_wallet = requires_wallet self.requires_password = requires_password self.description = description - self.syntax = syntax - self.options = options_syntax - known_commands = {} - def register_command(*args): global known_commands name = args[0] known_commands[name] = Command(*args) - -payto_options = ' --fee, -f: set transaction fee\n --fromaddr, -F: send from address -\n --changeaddr, -c: send change to address' -listaddr_options = " -a: show all addresses, including change addresses\n -l: include labels in results" -restore_options = " accepts a seed or master public key." -mksendmany_syntax = 'mksendmanytx <recipient> <amount> [<recipient> <amount> ...]' -payto_syntax = "payto <recipient> <amount> [label]\n<recipient> can be a bitcoin address or a label" -paytomany_syntax = "paytomany <recipient> <amount> [<recipient> <amount> ...]\n<recipient> can be a bitcoin address or a label" -signmessage_syntax = '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 "' -verifymessage_syntax = '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 "' - # command -# requires_network -# requires_wallet -# requires_password -register_command('contacts', 0, 0, False, True, False, 'Show your list of contacts') -register_command('create', 0, 0, False, True, False, 'Create a new wallet') -register_command('createmultisig', 2, 2, False, True, False, 'similar to bitcoind\'s command') -register_command('createrawtransaction', 2, 2, False, True, False, 'Create an unsigned transaction. The syntax is similar to bitcoind.') -register_command('deseed', 0, 0, False, True, False, 'Remove seed from wallet, creating a seedless, watching-only wallet.') -register_command('decoderawtransaction', 1, 1, False, False, False, 'similar to bitcoind\'s command') -register_command('getprivatekeys', 1, 1, False, True, True, 'Get the private keys of a given address', 'getprivatekeys <bitcoin address>') -register_command('dumpprivkeys', 0, 0, False, True, True, 'Dump all private keys in your wallet') -register_command('freeze', 1, 1, False, True, True, 'Freeze the funds at one of your wallet\'s addresses', 'freeze <address>') -register_command('getbalance', 0, 1, True, True, False, 'Return the balance of your wallet, or of one account in your wallet', 'getbalance [<account>]') -register_command('getservers', 0, 0, True, False, False, 'Return the list of available servers') -register_command('getversion', 0, 0, False, False, False, 'Return the version of your client', 'getversion') -register_command('getaddressbalance', 1, 1, True, False, False, 'Return the balance of an address', 'getaddressbalance <address>') -register_command('getaddresshistory', 1, 1, True, False, False, 'Return the transaction history of a wallet address', 'getaddresshistory <address>') -register_command('getconfig', 1, 1, False, False, False, 'Return a configuration variable', 'getconfig <name>') -register_command('getpubkeys', 1, 1, False, True, False, 'Return the public keys for a wallet address', 'getpubkeys <bitcoin address>') -register_command('getrawtransaction', 1, 1, True, False, False, 'Retrieve a transaction', 'getrawtransaction <txhash>') -register_command('getseed', 0, 0, False, True, True, 'Print the generation seed of your wallet.') -register_command('getmpk', 0, 0, False, True, False, 'Return your wallet\'s master public key', 'getmpk') -register_command('help', 0, 1, False, False, False, 'Prints this help') -register_command('history', 0, 0, True, True, False, 'Returns the transaction history of your wallet') -register_command('importprivkey', 1, 1, False, True, True, 'Import a private key', 'importprivkey <privatekey>') -register_command('ismine', 1, 1, False, True, False, 'Return true if and only if address is in wallet', 'ismine <address>') -register_command('listaddresses', 2, 2, False, True, False, 'Returns your list of addresses.', '', listaddr_options) -register_command('listunspent', 0, 0, True, True, False, 'Returns the list of unspent inputs in your wallet.') -register_command('getaddressunspent', 1, 1, True, False, False, 'Returns the list of unspent inputs for an address.') -register_command('mktx', 5, 5, False, True, True, 'Create a signed transaction', 'mktx <recipient> <amount> [label]', payto_options) -register_command('mksendmanytx', 4, 4, False, True, True, 'Create a signed transaction', mksendmany_syntax, payto_options) -register_command('payto', 5, 5, True, True, True, 'Create and broadcast a transaction.', payto_syntax, payto_options) -register_command('paytomany', 4, 4, True, True, True, 'Create and broadcast a transaction.', paytomany_syntax, payto_options) -register_command('password', 0, 0, False, True, True, 'Change your password') -register_command('restore', 0, 0, True, True, False, 'Restore a wallet', '', restore_options) -register_command('searchcontacts', 1, 1, False, True, False, 'Search through contacts, return matching entries', 'searchcontacts <query>') -register_command('setconfig', 2, 2, False, False, False, 'Set a configuration variable', 'setconfig <name> <value>') -register_command('setlabel', 2,-1, False, True, False, 'Assign a label to an item', 'setlabel <tx_hash> <label>') -register_command('sendrawtransaction', 1, 1, True, False, False, 'Broadcasts a transaction to the network.', 'sendrawtransaction <tx in hexadecimal>') -register_command('signtxwithkey', 1, 3, False, False, False, 'Sign a serialized transaction with a key','signtxwithkey <tx> <key>') -register_command('signtxwithwallet', 1, 3, False, True, True, 'Sign a serialized transaction with a wallet','signtxwithwallet <tx>') -register_command('signmessage', 2,-1, False, True, True, 'Sign a message with a key', signmessage_syntax) -register_command('unfreeze', 1, 1, False, True, False, 'Unfreeze the funds at one of your wallet\'s address', 'unfreeze <address>') -register_command('validateaddress', 1, 1, False, False, False, 'Check that the address is valid', 'validateaddress <address>') -register_command('verifymessage', 3,-1, False, False, False, 'Verifies a signature', verifymessage_syntax) - -register_command('encrypt', 2,-1, False, False, False, 'encrypt a message with pubkey','encrypt <pubkey> <message>') -register_command('decrypt', 2,-1, False, True, True, 'decrypt a message encrypted with pubkey','decrypt <pubkey> <message>') -register_command('getmerkle', 2, 2, True, False, False, 'Get Merkle branch of a transaction included in a block', 'getmerkle <txid> <height>') -register_command('getproof', 1, 1, True, False, False, 'Get Merkle branch of an address in the UTXO set', 'getproof <address>') -register_command('getutxoaddress', 2, 2, True, False, False, 'get the address of an unspent transaction output','getutxoaddress <txid> <pos>') -register_command('sweep', 2, 3, True, False, False, 'Sweep a private key.', 'sweep privkey addr [fee]') -register_command('make_seed', 3, 3, False, False, False, 'Create a seed.','options: --nbits --entropy --lang') -register_command('check_seed', 1,-1, False, False, False, 'Check that a seed was generated with external entropy. Option: --entropy --lang') +# requires_network +# requires_wallet +# requires_password +# args +# optional args +register_command('contacts', False, True, False, [], [], 'Show your list of contacts') +register_command('create', False, True, False, [], [], 'Create a new wallet') +register_command('createmultisig', False, True, False, ['num','pubkeys'], [], 'Create multisig address') +register_command('createrawtransaction', False, True, False, ['inputs', 'outputs'], [], 'Create an unsigned transaction. The syntax is similar to bitcoind.') +register_command('deseed', False, True, False, [], [], 'Remove seed from wallet, creating a seedless, watching-only wallet.') +register_command('decoderawtransaction', False, False, False, ['raw_tx'], [], 'Decode raw transaction') +register_command('getprivatekeys', False, True, True, ['address'], [], 'Get the private keys of a given address') +register_command('dumpprivkeys', False, True, True, [], [], 'Dump private keys from your wallet') +register_command('freeze', False, True, True, ['address'], [], 'Freeze the funds at one of your wallet\'s addresses') +register_command('getbalance', True, True, False, [], [], 'Return the balance of your wallet, or of one account in your wallet') +register_command('getservers', True, False, False, [], [], 'Return the list of available servers') +register_command('getaddressbalance', True, False, False, ['address'], [], 'Return the balance of an address') +register_command('getaddresshistory', True, False, False, ['address'], [], 'Return the transaction history of a wallet address') +register_command('getconfig', False, False, False, ['key'], [], 'Return a configuration variable') +register_command('getpubkeys', False, True, False, ['address'], [], 'Return the public keys for a wallet address') +register_command('getrawtransaction', True, False, False, ['txid'], [], 'Retrieve a transaction') +register_command('getseed', False, True, True, [], [], 'Print the generation seed of your wallet.') +register_command('getmpk', False, True, False, [], [], 'Return your wallet\'s master public key') +register_command('help', False, False, False, [], [], 'Print help on a command.') +register_command('history', True, True, False, [], [], 'Returns the transaction history of your wallet') +register_command('importprivkey', False, True, True, ['privatekey'], [], 'Import a private key') +register_command('ismine', False, True, False, ['address'], [], 'Return true if and only if address is in wallet') +register_command('listaddresses', False, True, False, [], ['show_all', 'show_labels'], 'Returns your list of addresses.') +register_command('listunspent', True, True, False, [], [], 'Returns the list of unspent inputs in your wallet.') +register_command('getaddressunspent', True, False, False, ['address'], [], 'Returns the list of unspent inputs for an address.') +register_command('mktx', False, True, True, ['recipient', 'amount'], ['tx_fee', 'from_addr', 'change_addr'], 'Create a signed transaction') +register_command('payto', True, True, True, ['recipient', 'amount'], ['tx_fee', 'from_addr', 'change_addr'], 'Create and broadcast a transaction.') +register_command('password', False, True, True, [], [], 'Change your password') +register_command('restore', True, True, False, [], ['gap_limit', 'mpk', 'concealed'], 'Restore a wallet') +register_command('searchcontacts', False, True, False, ['query'], [], 'Search through contacts, return matching entries') +register_command('setconfig', False, False, False, ['key', 'value'], [], 'Set a configuration variable') +register_command('setlabel', False, True, False, ['txid', 'label'], [], 'Assign a label to an item') +register_command('sendrawtransaction', True, False, False, ['raw_tx'], [], 'Broadcast a transaction to the network.') +register_command('signtxwithkey', False, False, False, ['raw_tx', 'key'], [], 'Sign a serialized transaction with a key') +register_command('signtxwithwallet', False, True, True, ['raw_tx'], [], 'Sign a serialized transaction with a wallet') +register_command('signmessage', False, True, True, ['address', 'message'], [], 'Sign a message with a key') +register_command('unfreeze', False, True, False, ['address'], [], 'Unfreeze the funds at one of your wallet\'s address') +register_command('validateaddress', False, False, False, ['address'], [], 'Check that the address is valid') +register_command('verifymessage', False, False, False, ['address', 'message'], [], 'Verify a signature') +register_command('version', False, False, False, [], [], 'Return the version of your client') +register_command('encrypt', False, False, False, ['pubkey', 'message'], [], 'Encrypt a message with a public key') +register_command('decrypt', False, True, True, ['pubkey', 'message'], [], 'Decrypt a message encrypted with a public key') +register_command('getmerkle', True, False, False, ['txid', 'height'], [], 'Get Merkle branch of a transaction included in a block') +register_command('getproof', True, False, False, ['address'], [], 'Get Merkle branch of an address in the UTXO set') +register_command('getutxoaddress', True, False, False, ['txid', 'pos'], [], 'Get the address of an unspent transaction output') +register_command('sweep', True, False, False, ['privkey', 'destination_address'], ['tx_fee'], 'Sweep a private key.') +register_command('make_seed', False, False, False, [], ['nbits', 'entropy', 'language'], 'Create a seed.') +register_command('check_seed', False, False, False, ['seed'], ['entropy'], 'Check that a seed was generated with external entropy.') +#register_command('mksendmanytx', False, True, True, 'Create a signed transaction', mksendmany_syntax, payto_options) +#register_command('paytomany', True, True, True, 'Create and broadcast a transaction.', paytomany_syntax, payto_options) + + + +command_options = { + 'password': ("-W", "--password", None, "Password"), + 'concealed': ("-C", "--concealed", False, "Don't echo seed to console when restoring"), + 'show_all': ("-a", "--all", False, "Show all addresses"), + 'show_labels': ("-l", "--labels", False, "Show the labels of listed addresses"), + 'tx_fee': ("-f", "--fee", None, "set tx fee"), + 'from_addr': ("-F", "--fromaddr", None, "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."), + 'change_addr': ("-c", "--changeaddr", None, "set the change address for payto/mktx. default is a spare address, or the source address if it's not in the wallet"), + 'nbits': (None, "--nbits", "128", "Number of bits of entropy"), + 'entropy': (None, "--entropy", "1", "Custom entropy"), + 'language': ("-L", "--lang", None, "Default language for wordlist"), + 'gap_limit': ("-G", "--gap", None, "Gap limit"), + 'mpk': (None, "--mpk", None, "Restore from master public key"), +} + + + +def set_default_subparser(self, name, args=None): + """see http://stackoverflow.com/questions/5176691/argparse-how-to-specify-a-default-subcommand""" + subparser_found = False + for arg in sys.argv[1:]: + if arg in ['-h', '--help']: # global help if no subparser + break + else: + for x in self._subparsers._actions: + if not isinstance(x, argparse._SubParsersAction): + continue + for sp_name in x._name_parser_map.keys(): + if sp_name in sys.argv[1:]: + subparser_found = True + if not subparser_found: + # insert default in first position, this implies no + # global options without a sub_parsers specified + if args is None: + sys.argv.insert(1, name) + else: + args.insert(0, name) + +argparse.ArgumentParser.set_default_subparser = set_default_subparser + +add_offline_option = lambda parser: parser.add_argument("-o", "--offline", action="store_true", dest="offline", default=False, help="Remain offline") +def add_wallet_options(p): + p.add_argument("-w", "--wallet", dest="wallet_path", help="wallet path") + p.add_argument("-P", "--portable", action="store_true", dest="portable", default=False, help="Portable wallet") + +def get_parser(run_gui, run_daemon, run_cmdline): + # parent parser, because set_default_subparser removes global options + parent_parser = argparse.ArgumentParser('parent', add_help=False) + parent_parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Show debugging information") + # connection + conn_parser = argparse.ArgumentParser(add_help=False) + conn_parser.add_argument("-1", "--oneserver", action="store_true", dest="oneserver", default=False, help="connect to one server only") + conn_parser.add_argument("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is either t (tcp) or s (ssl)") + conn_parser.add_argument("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http") + # create main parser + parser = argparse.ArgumentParser(parents=[parent_parser]) + subparsers = parser.add_subparsers(dest='cmd') + # gui + parser_gui = subparsers.add_parser('gui', parents=[parent_parser, conn_parser], description="Run Electrum's Graphical User Interface.", help="Run GUI (default)") + 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', 'text', 'stdio']) + parser_gui.add_argument("-m", action="store_true", dest="hide_gui", default=False, help="hide GUI on startup") + parser.add_argument("-L", "--lang", dest="language", default=None, help="default language used in GUI") + add_offline_option(parser) + add_wallet_options(parser) + # daemon + parser_daemon = subparsers.add_parser('daemon', help="Run Daemon") + parser_daemon.add_argument("subcommand", choices=['start', 'status', 'stop']) + parser_daemon.set_defaults(func=run_daemon) + # create a parser for each command + for cmdname in sorted(known_commands.keys()): + cmd = known_commands[cmdname] + parents = [parent_parser] + p = subparsers.add_parser(cmdname, parents=parents, description=cmd.description, help=cmd.description) + p.set_defaults(func=run_cmdline) + if cmd.requires_network: + add_offline_option(p) + if cmd.requires_wallet: + add_wallet_options(p) + if cmd.requires_password: + p.add_argument("-W", "--password", dest="password", default=None, help="password") + for optname in cmd.options: + a, b, default, help = command_options[optname] + action = "store_true" if type(default) is bool else 'store' + args = (a, b) if a else (b,) + p.add_argument(*args, dest=optname, action=action, default=default, help=help) + for param in cmd.params: + p.add_argument(param) + # default command is gui + parser.set_default_subparser('gui') + return parser + class Commands: @@ -265,7 +351,7 @@ class Commands: time.sleep(0.1) return self.network.get_servers() - def getversion(self): + def version(self): import electrum # Needs to stay here to prevent ciruclar imports return electrum.ELECTRUM_VERSION @@ -393,16 +479,6 @@ class Commands: out.append( item ) return out - def help(self, cmd=None): - if cmd not in known_commands: - print_msg("\nList of commands:", ', '.join(sorted(known_commands))) - else: - cmd = known_commands[cmd] - print_msg(cmd.description) - if cmd.syntax: print_msg("Syntax: " + cmd.syntax) - if cmd.options: print_msg("options:\n" + cmd.options) - return None - def getrawtransaction(self, tx_hash): if self.wallet: tx = self.wallet.transactions.get(tx_hash)