3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
20 import sys, os, time, ast
27 sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
32 sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
37 from electrum import *
39 from decimal import Decimal
42 'help':'Prints this help',
43 'validateaddress':'Check that the address is valid',
44 'balance': "Display the balance of your wallet or of an address.\nSyntax: balance [<address>]",
45 'contacts': "Show your list of contacts",
46 'create':'Create a wallet',
47 'restore':'Restore a wallet',
48 'payto':"""Create and broadcast a transaction.
49 Syntax: payto <recipient> <amount> [label]
50 <recipient> can be a bitcoin address or a label
51 options:\n --fee, -f: set transaction fee\n --fromaddr, -s: send from address -\n --changeaddr, -c: send change to address
54 'Broadcasts a transaction to the network. \nSyntax: sendrawtransaction <tx in hexadecimal>',
56 "Changes your password",
58 """Shows your list of addresses.
60 -a: show all addresses, including change addresses
62 -b: show the balance of addresses""",
64 'history':"Shows the transaction history",
65 'setlabel':'Assign a label to an item\nSyntax: label <tx_hash> <label>',
67 """Create a signed transaction, password protected.
68 Syntax: mktx <recipient> <amount> [label]
69 options:\n --fee, -f: set transaction fee\n --fromaddr, -s: send from address -\n --changeaddr, -c: send change to address
72 "Print the generation seed of your wallet.",
74 'Import a private key\nSyntax: importprivkey <privatekey>',
76 'Signs a message with a key\nSyntax: 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 "',
78 'Verifies a signature\nSyntax: 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 "',
80 "Run python eval() on an object\nSyntax: eval <expression>\nExample: eval \"wallet.aliases\"",
82 "Get config parameter.",
84 "Set config parameter.",
86 "Create a seedless, watching-only wallet.",
91 'dumpprivkey':'similar to bitcoind\'s command',
92 'dumpprivkeys':'dump all private keys',
93 'listunspent':'similar to bitcoind\'s command',
94 'createmultisig':'similar to bitcoind\'s command',
95 'createrawtransaction':'similar to bitcoind\'s command',
96 'decoderawtransaction':'similar to bitcoind\'s command',
97 'signrawtransaction':'similar to bitcoind\'s command',
98 'get_history': 'get history for an address'
104 offline_commands = [ 'password', 'mktx',
105 'setlabel', 'contacts',
106 'help', 'validateaddress',
107 'signmessage', 'verifymessage',
108 'eval', 'set', 'get', 'create', 'addresses',
109 'importprivkey', 'get_seed',
112 'prioritize','unprioritize',
113 'dumpprivkey','listunspent',
114 'createmultisig', 'createrawtransaction', 'decoderawtransaction', 'signrawtransaction'
119 # get password routine
120 def prompt_password(prompt, confirm=True):
122 if sys.stdin.isatty():
123 password = getpass.getpass(prompt)
124 if password and confirm:
125 password2 = getpass.getpass("Confirm: ")
126 if password != password2:
127 sys.exit("Error: Passwords do not match.")
129 password = raw_input(prompt)
135 usage = "usage: %prog [options] command\nCommands: "+ (', '.join(known_commands))
136 parser = optparse.OptionParser(prog=usage)
137 parser.add_option("-g", "--gui", dest="gui", help="User interface: qt, lite, gtk or text")
138 parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
139 parser.add_option("-o", "--offline", action="store_true", dest="offline", default=False, help="remain offline")
140 parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses")
141 parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance at listed addresses")
142 parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee")
143 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.")
144 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")
145 parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h")
146 parser.add_option("-p", "--proxy", dest="proxy", default=None, help="set proxy [type:]host[:port], where type is socks4,socks5 or http")
147 parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
148 parser.add_option("-P", "--portable", action="store_true", dest="portable", default=False, help="portable wallet")
149 parser.add_option("-L", "--lang", dest="language", default=None, help="defaut language used in GUI")
150 parser.add_option("-u", "--usb", dest="bitkey", action="store_true", help="Turn on support for hardware wallets (EXPERIMENTAL)")
154 if __name__ == '__main__':
156 parser = arg_parser()
157 options, args = parser.parse_args()
158 set_verbosity(options.verbose)
160 # config is an object passed to the various constructors (wallet, interface, gui)
161 if 'ANDROID_DATA' in os.environ:
162 config_options = {'wallet_path':"/sdcard/electrum.dat", 'portable':True, 'verbose':True, 'gui':'android'}
164 config_options = eval(str(options))
165 for k, v in config_options.items():
166 if v is None: config_options.pop(k)
168 # Wallet migration on Electrum 1.7
169 # Todo: In time we could remove this again
170 if platform.system() == "Windows":
171 util.check_windows_wallet_migration()
173 config = SimpleConfig(config_options)
174 wallet = Wallet(config)
179 elif len(args)==1 and re.match('^bitcoin:', args[0]):
184 firstarg = args[1] if len(args) > 1 else ''
186 #this entire if/else block is just concerned with importing the
187 #right GUI toolkit based the GUI command line option given
189 pref_gui = config.get('gui','classic')
191 if pref_gui == 'gtk':
193 import lib.gui as gui
195 import electrum.gui as gui
196 elif pref_gui in ['classic', 'qt']:
198 import lib.gui_qt as gui
200 import electrum.gui_qt as gui
201 elif pref_gui == 'lite':
203 import lib.gui_lite as gui
205 import electrum.gui_lite as gui
206 elif pref_gui == 'text':
208 import lib.gui_text as gui
210 import electrum.gui_text as gui
211 elif pref_gui == 'android':
213 import lib.gui_android as gui
215 import electrum.gui_android as gui
217 sys.exit("Error: Unknown GUI: " + pref_gui )
220 interface = Interface(config, True)
221 wallet.interface = interface
223 if interface.is_connected:
224 interface.send([('server.peers.subscribe',[])])
226 set_language(config.get('language'))
227 gui = gui.ElectrumGui(wallet, config)
229 found = config.wallet_file_exists
231 a = gui.restore_or_create()
234 s = gui.network_dialog()
237 wallet.init_seed(None)
239 # ask for seed and gap.
240 sg = gui.seed_dialog()
244 wallet.gap_limit = gap
247 wallet.sequence.master_public_key = seed
249 wallet.init_seed(str(seed))
252 # generate the first addresses, in case we are offline
253 if s is None or a == 'create':
259 verifier = WalletVerifier(interface, config)
260 wallet.set_verifier(verifier)
261 synchronizer = WalletSynchronizer(wallet, config)
264 if not found and a == 'restore' and s is not None:
266 keep_it = gui.restore_wallet()
267 wallet.fill_addressbook()
270 traceback.print_exc(file=sys.stdout)
273 if not keep_it: exit()
276 gui.password_dialog()
287 # we use daemon threads, their termination is enforced.
288 # this sleep command gives them time to terminate cleanly.
292 if cmd not in known_commands:
295 if not config.wallet_file_exists and cmd not in ['help','create','restore']:
296 print_msg("Error: Wallet file not found.")
297 print_msg("Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option")
300 if cmd in ['create', 'restore']:
301 if config.wallet_file_exists:
302 sys.exit("Error: Remove the existing wallet first!")
303 password = prompt_password("Password (hit return if you do not wish to encrypt your wallet):")
305 server = config.get('server')
306 if not server: server = pick_random_server()
307 w_host, w_port, w_protocol = server.split(':')
308 host = raw_input("server (default:%s):"%w_host)
309 port = raw_input("port (default:%s):"%w_port)
310 protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol)
311 fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) )
312 gap = raw_input("gap limit (default 5):")
313 if host: w_host = host
314 if port: w_port = port
315 if protocol: w_protocol = protocol
316 wallet.config.set_key('server', w_host + ':' + w_port + ':' +w_protocol)
317 if fee: wallet.fee = float(fee)
318 if gap: wallet.gap_limit = int(gap)
321 seed = raw_input("seed:")
325 print_error("Warning: Not hex, trying decode.")
326 seed = mnemonic_decode( seed.split(' ') )
328 sys.exit("Error: No seed")
332 wallet.sequence.master_public_key = seed
334 wallet.seed = str(seed)
335 wallet.init_mpk( wallet.seed )
337 if not options.offline:
338 interface = Interface(config)
340 wallet.interface = interface
342 verifier = WalletVerifier(interface, config)
343 wallet.set_verifier(verifier)
345 print_msg("Recovering wallet...")
346 WalletSynchronizer(wallet, config).start()
348 if wallet.is_found():
349 print_msg("Recovery successful")
351 print_msg("Warning: Found no history for this wallet")
354 wallet.fill_addressbook()
356 print_msg("Wallet saved in '%s'"%wallet.config.path)
358 wallet.init_seed(None)
359 wallet.synchronize() # there is no wallet thread
361 print_msg("Your wallet generation seed is: " + wallet.seed)
362 print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")
363 print_msg("Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:")
364 print_msg("\""+' '.join(mnemonic_encode(wallet.seed))+"\"")
365 print_msg("Wallet saved in '%s'"%wallet.config.path)
368 wallet.update_password(wallet.seed, None, password)
372 if cmd not in offline_commands and not options.offline:
373 interface = Interface(config)
374 interface.register_callback('connected', lambda: sys.stderr.write("Connected to " + interface.connection_msg + "\n"))
376 wallet.interface = interface
377 verifier = WalletVerifier(interface, config)
378 wallet.set_verifier(verifier)
379 synchronizer = WalletSynchronizer(wallet, config)
387 if cmd in ['dumpprivkey', 'dumpprivkeys']:
388 print_msg("WARNING: ALL your private keys are secret.")
389 print_msg("Exposing a single private key can compromise your entire wallet!")
390 print_msg("In particular, DO NOT use 'redeem private key' services proposed by third parties.")
392 # commands needing password
393 if cmd in protected_commands:
394 if wallet.use_encryption:
395 password = prompt_password('Password:', False)
397 print_msg("Error: Password required")
401 seed = wallet.decode_seed(password)
403 print_msg("Error: This password does not decode this wallet.")
412 # check and format the arguments
413 if cmd == 'importprivkey':
414 # See if they specificed a key on the cmd line, if not prompt
416 args[1] = prompt_password('Enter PrivateKey (will not echo):', False)
418 elif cmd == 'signmessage':
420 print_msg("Error: Invalid usage of signmessage.")
421 print_msg(known_commands[cmd])
424 message = ' '.join(args[2:])
426 print_msg("Warning: Message was reconstructed from several arguments:", repr(message))
427 args = [ cmd, address, message ]
429 elif cmd == 'verifymessage':
433 message = ' '.join(args[3:])
435 print_msg("Error: Not all parameters were given, displaying help instead.")
436 print_msg(known_commands[cmd])
439 print_msg("Warning: Message was reconstructed from several arguments:", repr(message))
440 args = [ cmd, address, signature, message]
442 elif cmd == 'signrawtransaction':
443 args = [ cmd, args[1], ast.literal_eval(args[2]) if len(args)>2 else [], ast.literal_eval(args[3]) if len(args)>3 else []]
445 elif cmd == 'createmultisig':
446 args = [ cmd, int(args[1]), ast.literal_eval(args[2])]
448 elif cmd == 'createrawtransaction':
449 args = [ cmd, ast.literal_eval(args[1]), ast.literal_eval(args[2])]
451 elif cmd == 'dumpprivkeys':
452 args = [cmd, wallet.all_addresses() if options.show_all else wallet.addresses + wallet.imported_keys.keys() ]
454 elif cmd=='addresses':
455 args = [cmd, options.show_all]
457 elif cmd == 'setlabel':
460 label = ' '.join(args[2:])
462 print_msg("Error. Syntax: label <tx_hash> <text>")
464 args = [ cmd, tx, label ]
466 elif cmd in ['payto', 'mktx']:
468 #is_temporary = False
470 if options.from_addr:
471 from_addr = options.from_addr
472 if from_addr not in wallet.all_addresses():
474 raise BaseException("address not in wallet")
478 amount = Decimal(args[2])
480 label = ' '.join(args[3:])
482 options.tx_fee = Decimal(options.tx_fee)
487 #if from_addr and is_temporary:
488 # if from_addr.find(":") == -1:
489 # keypair = from_addr + ":" + prompt_password('Private key:', False)
491 # keypair = from_addr
492 # from_addr = keypair.split(':')[0]
493 # if not wallet.import_key(keypair,password):
494 # print_msg("Error: Invalid key pair")
496 # wallet.history[from_addr] = interface.retrieve_history(from_addr)
497 # wallet.update_tx_history()
498 # change_addr = from_addr
500 if options.change_addr:
501 change_addr = options.change_addr
503 args = [ 'mktx', to_address, amount, options.tx_fee, options.change_addr, from_addr ]
506 # wallet.imported_keys.pop(from_addr)
507 # del(wallet.history[from_addr])
515 if cmd2 not in known_commands:
517 print_msg("Type 'electrum help <command>' to see the help for a specific command")
518 print_msg("Type 'electrum --help' to see the list of options")
519 print_msg("List of commands:", ', '.join(known_commands))
521 print_msg(known_commands[cmd2])
523 elif cmd == 'deseed':
525 print_msg("Error: This wallet has no seed")
527 ns = wallet.config.path + '.seedless'
528 print_msg("Warning: you are going to create a seedless wallet'\nIt will be saved in '%s'"%ns)
529 if raw_input("Are you sure you want to continue? (y/n) ") in ['y','Y','yes']:
530 wallet.config.path = ns
532 wallet.config.set_key('seed','', True)
533 for k in wallet.imported_keys.keys(): wallet.imported_keys[k] = ''
537 print_msg("Action canceled.")
540 print_msg(eval(args[1]))
545 print_msg(wallet.config.get(key))
548 key, value = args[1:3]
549 if key not in ['seed', 'seed_version', 'master_public_key', 'use_encryption']:
550 wallet.config.set_key(key, value, True)
556 elif cmd == 'password':
557 new_password = prompt_password('New password:')
558 wallet.update_password(seed, password, new_password)
563 cmd_runner = Commands(wallet, interface)
564 func = eval('cmd_runner.' + cmd)
566 cmd_runner.password = password
570 if cmd not in offline_commands and not options.offline: