electrum-bitcoinprivate/electrum

431 lines
16 KiB
Plaintext
Raw Normal View History

2011-11-04 10:00:37 -07:00
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 re
2013-03-02 07:29:14 -08:00
import pkgutil
2013-02-27 09:11:45 -08:00
import sys, os, time, json
import optparse
import platform
from decimal import Decimal
try:
import ecdsa
except ImportError:
sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
try:
import aes
except ImportError:
sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
# load local module as electrum
if os.path.exists("lib"):
import imp
fp, pathname, description = imp.find_module('lib')
imp.load_module('electrum', fp, pathname, description)
fp, pathname, description = imp.find_module('gui')
2013-03-02 09:03:29 -08:00
imp.load_module('electrum_gui', fp, pathname, description)
2013-03-02 07:29:14 -08:00
2012-02-02 23:02:12 -08:00
from electrum import *
2012-03-23 05:55:27 -07:00
# get password routine
def prompt_password(prompt, confirm=True):
import getpass
if sys.stdin.isatty():
password = getpass.getpass(prompt)
if password and confirm:
password2 = getpass.getpass("Confirm: ")
if password != password2:
sys.exit("Error: Passwords do not match.")
else:
password = raw_input(prompt)
if not password:
password = None
return password
def arg_parser():
2012-05-14 08:35:38 -07:00
usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands))
parser = optparse.OptionParser(prog=usage)
2012-10-17 06:33:59 -07:00
parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text")
parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
2012-05-13 01:19:28 -07:00
parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline")
2011-11-14 11:35:54 -08:00
parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance of listed addresses")
parser.add_option("-l", "--labels", action="store_true", dest="show_labels", default=False, help="show the labels of listed addresses")
2011-12-18 13:49:33 -08:00
parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", 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 t or h")
2012-10-01 09:14:50 -07:00
parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
2012-11-04 03:27:01 -08:00
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="defaut language used in GUI")
parser.add_option("-u", "--usb", dest="bitkey", action="store_true", help="Turn on support for hardware wallets (EXPERIMENTAL)")
return parser
2012-11-18 02:34:52 -08:00
2011-11-04 10:00:37 -07:00
2012-11-18 02:34:52 -08:00
if __name__ == '__main__':
parser = arg_parser()
options, args = parser.parse_args()
2012-11-04 03:27:01 -08:00
set_verbosity(options.verbose)
# config is an object passed to the various constructors (wallet, interface, gui)
2012-11-18 02:34:52 -08:00
if 'ANDROID_DATA' in os.environ:
config_options = {'wallet_path':"/sdcard/electrum.dat", 'portable':True, 'verbose':True, 'gui':'android'}
2012-11-18 02:34:52 -08:00
else:
config_options = eval(str(options))
for k, v in config_options.items():
if v is None: config_options.pop(k)
2012-11-18 02:34:52 -08:00
# Wallet migration on Electrum 1.7
# Todo: In time we could remove this again
if platform.system() == "Windows":
util.check_windows_wallet_migration()
config = SimpleConfig(config_options)
wallet = Wallet(config)
2013-03-02 07:29:14 -08:00
2012-03-12 09:55:33 -07:00
2012-02-14 03:45:39 -08:00
if len(args)==0:
url = None
cmd = 'gui'
elif len(args)==1 and re.match('^bitcoin:', args[0]):
url = args[0]
cmd = 'gui'
else:
cmd = args[0]
2012-02-11 04:14:12 -08:00
2013-03-02 09:03:29 -08:00
if cmd == 'gui':
gui_name = config.get('gui','classic')
try:
2013-03-02 09:10:22 -08:00
gui = __import__('electrum_gui.gui_' + gui_name, fromlist=['electrum_gui'])
2013-03-02 09:03:29 -08:00
except ImportError:
sys.exit("Error: Unknown GUI: " + gui_name )
2012-10-22 02:34:21 -07:00
interface = Interface(config, True)
wallet.interface = interface
2013-03-10 01:24:42 -08:00
interface.start(wait = False)
interface.send([('server.peers.subscribe',[])])
gui = gui.ElectrumGui(wallet, config)
found = config.wallet_file_exists
if not found:
a = gui.restore_or_create()
if not a: exit()
2012-11-20 12:36:06 -08:00
# select a server.
s = gui.network_dialog()
if a =='create':
wallet.init_seed(None)
else:
# ask for seed and gap.
2013-01-08 05:29:42 -08:00
sg = gui.seed_dialog()
if not sg: exit()
seed, gap = sg
if not seed: exit()
wallet.gap_limit = gap
if len(seed) == 128:
wallet.seed = ''
wallet.init_sequence(str(seed))
2013-01-08 05:29:42 -08:00
else:
wallet.init_seed(str(seed))
2013-01-08 05:29:42 -08:00
# generate the first addresses, in case we are offline
2012-11-23 10:31:45 -08:00
if s is None or a == 'create':
wallet.synchronize()
2012-11-20 12:46:45 -08:00
if a == 'create':
# display seed
gui.show_seed()
2012-11-04 11:53:27 -08:00
verifier = WalletVerifier(interface, config)
wallet.set_verifier(verifier)
2012-11-24 11:31:07 -08:00
synchronizer = WalletSynchronizer(wallet, config)
synchronizer.start()
2012-02-14 00:52:03 -08:00
if not found and a == 'restore' and s is not None:
try:
2012-11-20 12:36:06 -08:00
keep_it = gui.restore_wallet()
wallet.fill_addressbook()
except:
import traceback
traceback.print_exc(file=sys.stdout)
exit()
2012-11-20 12:36:06 -08:00
if not keep_it: exit()
2012-11-20 12:46:45 -08:00
if not found:
gui.password_dialog()
2012-11-20 12:36:06 -08:00
wallet.save()
verifier.start()
2012-02-14 03:45:39 -08:00
gui.main(url)
2011-11-09 14:21:27 -08:00
wallet.save()
2012-11-24 11:31:07 -08:00
2012-11-05 14:10:38 -08:00
verifier.stop()
synchronizer.stop()
2012-11-24 11:31:07 -08:00
interface.stop()
# we use daemon threads, their termination is enforced.
# this sleep command gives them time to terminate cleanly.
time.sleep(0.1)
2011-11-10 00:34:27 -08:00
sys.exit(0)
2011-11-04 10:00:37 -07:00
2012-01-15 09:45:30 -08:00
if cmd not in known_commands:
cmd = 'help'
if not config.wallet_file_exists and cmd not in ['help','create','restore']:
2012-11-23 09:48:56 -08:00
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")
2011-11-16 07:26:06 -08:00
sys.exit(0)
if cmd in ['create', 'restore']:
if config.wallet_file_exists:
sys.exit("Error: Remove the existing wallet first!")
password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):")
2011-11-04 10:00:37 -07:00
server = config.get('server')
if not server: server = pick_random_server()
w_host, w_port, w_protocol = server.split(':')
2012-03-30 21:39:23 -07:00
host = raw_input("server (default:%s):"%w_host)
port = raw_input("port (default:%s):"%w_port)
protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol)
2012-02-05 22:48:52 -08:00
fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) )
gap = raw_input("gap limit (default 5):")
2012-03-30 21:39:23 -07:00
if host: w_host = host
if port: w_port = port
if protocol: w_protocol = protocol
wallet.config.set_key('server', w_host + ':' + w_port + ':' +w_protocol)
if fee: wallet.fee = float(fee)
if gap: wallet.gap_limit = int(gap)
if cmd == 'restore':
seed = raw_input("seed:")
try:
seed.decode('hex')
except:
print_error("Warning: Not hex, trying decode.")
2012-11-04 10:40:17 -08:00
seed = mnemonic_decode( seed.split(' ') )
if not seed:
sys.exit("Error: No seed")
2013-01-08 12:30:03 -08:00
if len(seed) == 128:
wallet.seed = None
2013-03-07 07:45:55 -08:00
wallet.init_sequence(str(seed))
2013-01-08 12:30:03 -08:00
else:
wallet.seed = str(seed)
wallet.init_mpk( wallet.seed )
2012-11-04 12:12:08 -08:00
2013-01-08 12:30:03 -08:00
if not options.offline:
2012-11-04 12:12:08 -08:00
interface = Interface(config)
2013-03-10 01:24:42 -08:00
interface.start(wait=True)
2012-11-04 12:12:08 -08:00
wallet.interface = interface
verifier = WalletVerifier(interface, config)
wallet.set_verifier(verifier)
2012-11-23 09:48:56 -08:00
print_msg("Recovering wallet...")
WalletSynchronizer(wallet, config).start()
2012-05-13 01:19:28 -07:00
wallet.update()
if wallet.is_found():
2012-11-23 09:48:56 -08:00
print_msg("Recovery successful")
2012-05-13 01:19:28 -07:00
else:
2012-11-23 09:48:56 -08:00
print_msg("Warning: Found no history for this wallet")
2012-09-20 02:46:11 -07:00
else:
wallet.synchronize()
2012-05-13 01:19:28 -07:00
wallet.fill_addressbook()
wallet.save()
2012-11-23 09:48:56 -08:00
print_msg("Wallet saved in '%s'"%wallet.config.path)
else:
wallet.init_seed(None)
wallet.synchronize() # there is no wallet thread
2012-02-21 08:13:34 -08:00
wallet.save()
2012-11-23 09:48:56 -08:00
print_msg("Your wallet generation seed is: " + wallet.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("Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:")
print_msg("\""+' '.join(mnemonic_encode(wallet.seed))+"\"")
print_msg("Wallet saved in '%s'"%wallet.config.path)
2012-05-16 23:49:30 -07:00
if password:
wallet.update_password(wallet.seed, None, password)
2011-11-04 10:00:37 -07:00
2013-02-28 08:21:30 -08:00
# terminate
sys.exit(0)
2011-11-11 15:07:41 -08:00
2013-02-27 00:04:22 -08:00
# important warning
if cmd in ['dumpprivkey', 'dumpprivkeys']:
2012-11-23 09:48:56 -08:00
print_msg("WARNING: ALL your private keys are secret.")
print_msg("Exposing a single private key can compromise your entire wallet!")
print_msg("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
2011-11-14 11:35:54 -08:00
# commands needing password
if cmd in protected_commands:
if wallet.use_encryption:
password = prompt_password('Password:', False)
if not password:
print_msg("Error: Password required")
exit(1)
# check password
try:
seed = wallet.decode_seed(password)
except:
print_msg("Error: This password does not decode this wallet.")
exit(1)
else:
password = None
2013-01-06 06:57:01 -08:00
seed = wallet.seed
else:
password = None
# add missing arguments, do type conversions
if cmd == 'importprivkey':
# See if they specificed a key on the cmd line, if not prompt
if len(args) == 1:
args[1] = prompt_password('Enter PrivateKey (will not echo):', False)
elif cmd == 'signrawtransaction':
2013-02-27 09:11:45 -08:00
args = [ cmd, args[1], json.loads(args[2]) if len(args)>2 else [], json.loads(args[3]) if len(args)>3 else []]
elif cmd == 'createmultisig':
2013-02-27 09:11:45 -08:00
args = [ cmd, int(args[1]), json.loads(args[2])]
elif cmd == 'createrawtransaction':
2013-02-27 09:11:45 -08:00
args = [ cmd, json.loads(args[1]), json.loads(args[2])]
2013-03-04 08:36:49 -08:00
elif cmd == 'listaddresses':
args = [cmd, options.show_all, options.show_balance, options.show_labels]
elif cmd in ['payto', 'mktx']:
args = [ 'mktx', args[1], Decimal(args[2]), Decimal(options.tx_fee) if options.tx_fee else None, options.change_addr, options.from_addr ]
2013-03-04 08:36:49 -08:00
elif cmd == 'help':
if len(args) < 2:
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")
# check the number of arguments
min_args, max_args, description, syntax, options_syntax = known_commands[cmd]
if len(args) - 1 < min_args:
print_msg("Not enough arguments")
print_msg("Syntax:", syntax)
sys.exit(1)
if max_args >= 0 and len(args) - 1 > max_args:
print_msg("too many arguments", args)
print_msg("Syntax:", syntax)
sys.exit(1)
if max_args < 0:
if len(args) > min_args:
message = ' '.join(args[min_args:])
print_msg("Warning: Final argument was reconstructed from several arguments:", repr(message))
args = args[0:min_args] + [ message ]
# open session
if cmd not in offline_commands and not options.offline:
interface = Interface(config)
interface.register_callback('connected', lambda: sys.stderr.write("Connected to " + interface.connection_msg + "\n"))
interface.start()
wallet.interface = interface
verifier = WalletVerifier(interface, config)
wallet.set_verifier(verifier)
synchronizer = WalletSynchronizer(wallet, config)
synchronizer.start()
wallet.update()
wallet.save()
# run the command
2011-11-16 07:12:13 -08:00
2013-03-04 08:36:49 -08:00
if cmd == 'deseed':
2012-05-12 16:32:28 -07:00
if not wallet.seed:
2012-11-27 14:32:39 -08:00
print_msg("Error: This wallet has no seed")
2012-05-12 15:43:22 -07:00
else:
ns = wallet.config.path + '.seedless'
print_msg("Warning: you are going to create a seedless wallet'\nIt will be saved in '%s'"%ns)
2012-05-12 16:32:28 -07:00
if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
wallet.config.path = ns
2012-05-12 16:32:28 -07:00
wallet.seed = ''
2013-02-27 09:01:58 -08:00
wallet.use_encryption = False
2013-02-24 12:31:11 -08:00
wallet.config.set_key('seed','', True)
for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = ''
2012-05-12 16:32:28 -07:00
wallet.save()
2012-11-23 09:48:56 -08:00
print_msg("Done.")
2012-05-12 16:32:28 -07:00
else:
2012-11-27 14:32:39 -08:00
print_msg("Action canceled.")
2012-05-12 16:32:28 -07:00
2012-02-06 09:13:33 -08:00
elif cmd == 'eval':
2012-11-23 09:48:56 -08:00
print_msg(eval(args[1]))
2012-02-06 09:55:25 -08:00
wallet.save()
elif cmd == 'getconfig':
2012-10-26 08:35:35 -07:00
key = args[1]
2012-11-23 09:48:56 -08:00
print_msg(wallet.config.get(key))
2012-10-26 08:35:35 -07:00
elif cmd == 'setconfig':
2012-10-20 01:23:34 -07:00
key, value = args[1:3]
if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']:
2012-10-20 01:23:34 -07:00
wallet.config.set_key(key, value, True)
2012-11-23 09:48:56 -08:00
print_msg(True)
2012-10-20 01:23:34 -07:00
else:
2012-11-23 09:48:56 -08:00
print_msg(False)
2012-10-20 01:23:34 -07:00
2011-11-04 10:00:37 -07:00
elif cmd == 'password':
new_password = prompt_password('New password:')
wallet.update_password(seed, password, new_password)
2011-11-04 10:00:37 -07:00
else:
cmd_runner = Commands(wallet, interface)
func = eval('cmd_runner.' + cmd)
2013-02-27 01:24:53 -08:00
cmd_runner.password = password
try:
result = func(*args[1:])
except BaseException, e:
print_msg("Error: " + str(e))
sys.exit(1)
2013-02-27 01:24:53 -08:00
if type(result) == str:
util.print_msg(result)
2013-03-04 08:36:49 -08:00
elif result is not None:
2013-02-27 01:24:53 -08:00
util.print_json(result)
2013-02-20 04:10:32 -08:00
2012-11-05 14:10:38 -08:00
if cmd not in offline_commands and not options.offline:
2013-02-25 13:21:07 -08:00
verifier.stop()
2012-11-05 14:10:38 -08:00
synchronizer.stop()
2013-02-25 13:21:07 -08:00
interface.stop()
time.sleep(0.1)
sys.exit(0)