Fixed download URL (from github to electrum.bitcoin.cz)
[electrum-nvc.git] / electrum
index dcaefb3..4ce9fdd 100755 (executable)
--- a/electrum
+++ b/electrum
@@ -17,7 +17,7 @@
 # along with this program. If not, see <http://www.gnu.org/licenses/>.
 
 import re
-import sys, os
+import sys, os, time
 import optparse
 
 try:
@@ -67,10 +67,11 @@ options:
 Syntax: mktx <recipient> <amount> [label]
 options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address -\n  --changeaddr, -c: send change to address
         """,
+    'signtx':"Sign an unsigned transaction created by a deseeded wallet\nSyntax: signtx <filename>",
     'seed':
             "Print the generation seed of your wallet.",
-    'import': 
-            'Imports a key pair\nSyntax: import <address>:<privatekey>',
+    'importprivkey': 
+            'Import a private key\nSyntax: importprivkey <privatekey>',
     'signmessage':
             '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 "',
     'verifymessage':
@@ -93,18 +94,18 @@ options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address
 
 
 
-offline_commands = [ 'password', 'mktx',
+offline_commands = [ 'password', 'mktx', 'signtx',
                      'label', 'contacts',
                      'help', 'validateaddress',
                      'signmessage', 'verifymessage',
                      'eval', 'set', 'get', 'create', 'addresses',
-                     'import', 'seed',
+                     'importprivkey', 'seed',
                      'deseed','reseed',
                      'freeze','unfreeze',
                      'prioritize','unprioritize']
 
 
-protected_commands = ['payto', 'password', 'mktx', 'seed', 'import','signmessage' ]
+protected_commands = ['payto', 'password', 'mktx', 'signtx', 'seed', 'importprivkey','signmessage' ]
 
 # get password routine
 def prompt_password(prompt, confirm=True):
@@ -136,6 +137,9 @@ def arg_parser():
     parser.add_option("-s", "--server", dest="server", default=None, help="set server host:port:protocol, where protocol is t or h")
     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="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
 
 
@@ -147,7 +151,7 @@ if __name__ == '__main__':
 
     # config is an object passed to the various constructors (wallet, interface, gui)
     if 'ANDROID_DATA' in os.environ:
-        config_options = {'wallet_path':"/sdcard/electrum.dat", 'blockchain_headers_path':'/sdcard/sl4a/e4a-%s'%ELECTRUM_VERSION, 'gui':'android'}
+        config_options = {'wallet_path':"/sdcard/electrum.dat", 'portable':True, 'verbose':True, 'gui':'android'}
     else:
         config_options = eval(str(options))
         for k, v in config_options.items():
@@ -202,8 +206,10 @@ if __name__ == '__main__':
         interface = Interface(config, True)
         wallet.interface = interface
         interface.start()
-        interface.send([('server.peers.subscribe',[])])
+        if interface.is_connected:
+            interface.send([('server.peers.subscribe',[])])
 
+        set_language(config.get('language'))
         gui = gui.ElectrumGui(wallet, config)
 
         found = config.wallet_file_exists
@@ -218,8 +224,18 @@ if __name__ == '__main__':
                 wallet.init_mpk( wallet.seed )
             else:
                 # ask for seed and gap.
-                if not gui.seed_dialog(): exit()
-                wallet.init_mpk( wallet.seed )
+                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 = None
+                    wallet.master_public_key = seed
+                else:
+                    wallet.seed = str(seed)
+                    wallet.init_mpk( wallet.seed )
+            
 
             # generate the first addresses, in case we are offline
             if s is None or a == 'create':
@@ -230,7 +246,8 @@ if __name__ == '__main__':
 
         verifier = WalletVerifier(interface, config)
         wallet.set_verifier(verifier)
-        WalletSynchronizer(wallet, config).start()
+        synchronizer = WalletSynchronizer(wallet, config)
+        synchronizer.start()
 
         if not found and a == 'restore' and s is not None:
             try:
@@ -250,6 +267,14 @@ if __name__ == '__main__':
         verifier.start()
         gui.main(url)
         wallet.save()
+
+        verifier.stop()
+        synchronizer.stop()
+        interface.stop()
+
+        # we use daemon threads, their termination is enforced.
+        # this sleep command gives them time to terminate cleanly. 
+        time.sleep(0.1)
         sys.exit(0)
 
     if cmd not in known_commands:
@@ -290,10 +315,14 @@ if __name__ == '__main__':
             if not seed:
                 sys.exit("Error: No seed")
 
-            wallet.seed = str(seed)
-            wallet.init_mpk( wallet.seed )
-            if not options.offline:
+            if len(seed) == 128:
+                wallet.seed = None
+                wallet.master_public_key = seed
+            else:
+                wallet.seed = str(seed)
+                wallet.init_mpk( wallet.seed )
 
+            if not options.offline:
                 interface = Interface(config)
                 interface.start()
                 wallet.interface = interface
@@ -343,10 +372,11 @@ if __name__ == '__main__':
     # open session
     if cmd not in offline_commands and not options.offline:
         interface = Interface(config)
-        interface.register_callback('connected', lambda: print_error("Connected to " + interface.connection_msg))
+        interface.register_callback('connected', lambda: sys.stderr.write("Connected to " + interface.connection_msg + "\n"))
         interface.start()
         wallet.interface = interface
-        WalletSynchronizer(wallet, config).start()
+        synchronizer = WalletSynchronizer(wallet, config)
+        synchronizer.start()
         wallet.update()
         wallet.save()
 
@@ -366,26 +396,33 @@ if __name__ == '__main__':
 
     # commands needing password
     if cmd in protected_commands or ( cmd=='addresses' and options.show_keys):
-        password = prompt_password('Password:', False) if wallet.use_encryption and not is_temporary else None
-        # check password
-        try:
-            wallet.pw_decode( wallet.seed, password)
-        except:
-            print_error("Error: This password does not decode this wallet.")
-            exit(1)
+        if wallet.use_encryption and not is_temporary:
+            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
+            seed = wallet.seed
 
-    if cmd == 'import':
+    if cmd == 'importprivkey':
         # See if they specificed a key on the cmd line, if not prompt
         if len(args) > 1:
-            keypair = args[1]
+            sec = args[1]
         else:
-            keypair = prompt_password('Enter Address:PrivateKey (will not echo):', False)
+            sec = prompt_password('Enter PrivateKey (will not echo):', False)
         try:
-            wallet.import_key(keypair,password)
+            addr = wallet.import_key(sec,password)
             wallet.save()
-            print_msg("Keypair imported")
-        except BaseException(e):
-            print_error("Error: Keypair import failed: " + str(e))
+            print_msg("Keypair imported: ", addr)
+        except BaseException as e:
+            print_msg("Error: Keypair import failed: " + str(e))
 
     if cmd == 'help':
         cmd2 = firstarg
@@ -398,14 +435,13 @@ if __name__ == '__main__':
             print_msg(known_commands[cmd2])
 
     elif cmd == 'seed':
-        seed = wallet.pw_decode( wallet.seed, password)
         print_msg(seed + ' "' + ' '.join(mnemonic_encode(seed)) + '"')
 
     elif cmd == 'deseed':
         if not wallet.seed:
-            print_error("Error: This wallet has no seed")
+            print_msg("Error: This wallet has no seed")
         elif wallet.use_encryption:
-            print_error("Error: This wallet is encrypted")
+            print_msg("Error: This wallet is encrypted")
         else:
             ns = wallet.config.path + '.seed'
             print_msg("Warning: you are going to extract the seed from '%s'\nThe seed will be saved in '%s'"%(wallet.config.path,ns))
@@ -418,7 +454,7 @@ if __name__ == '__main__':
                 wallet.save()
                 print_msg("Done.")
             else:
-                print_error("Action canceled.")
+                print_msg("Action canceled.")
 
     elif cmd == 'reseed':
         if wallet.seed:
@@ -448,7 +484,7 @@ if __name__ == '__main__':
                 wallet.save()
                 print_msg("Done: " + wallet.config.path)
             else:
-                print_error("Error: Master public key does not match")
+                print_msg("Error: Master public key does not match")
 
     elif cmd == 'validateaddress':
         addr = args[1]
@@ -536,7 +572,7 @@ if __name__ == '__main__':
             tx = args[1]
             label = ' '.join(args[2:])
         except:
-            print_error("Error. Syntax:  label <tx_hash> <text>")
+            print_msg("Error. Syntax:  label <tx_hash> <text>")
             sys.exit(1)
         wallet.labels[tx] = label
         wallet.save()
@@ -549,7 +585,7 @@ if __name__ == '__main__':
                 keypair = from_addr
                 from_addr = keypair.split(':')[0]
             if not wallet.import_key(keypair,password):
-                print_error("Error: Invalid key pair")
+                print_msg("Error: Invalid key pair")
                 exit(1)
             wallet.history[from_addr] = interface.retrieve_history(from_addr)
             wallet.update_tx_history()
@@ -566,7 +602,7 @@ if __name__ == '__main__':
             if change_addr and v == change_addr:
                 change_addr = k
         try:
-            tx = wallet.mktx( to_address, amount, label, password,
+            tx = wallet.mktx( [(to_address, amount)], label, password,
                 fee = options.tx_fee, change_addr = change_addr, from_addr = from_addr )
         except:
             import traceback
@@ -584,23 +620,29 @@ if __name__ == '__main__':
             del(wallet.history[from_addr])
         wallet.save()
 
+    elif cmd == 'signtx':
+        import ast
+        filename = args[1]
+        f = open(filename, 'r')
+        d = ast.literal_eval(f.read())
+        f.close()
+        inputs = d['inputs']
+        outputs = d['outputs']
+        tx = wallet.signed_tx( inputs, outputs, password )
+        print_msg(tx)
+
     elif cmd == 'sendtx':
         tx = args[1]
         r, h = wallet.sendtx( tx )
         print_msg(h)
 
     elif cmd == 'password':
-        try:
-            seed = wallet.pw_decode( wallet.seed, password)
-        except ValueError:
-            sys.exit("Error: Password does not decrypt this wallet.")
-
         new_password = prompt_password('New password:')
         wallet.update_password(seed, password, new_password)
 
     elif cmd == 'signmessage':
         if len(args) < 3:
-            print_error("Error: Invalid usage of signmessage.")
+            print_msg("Error: Invalid usage of signmessage.")
             print_msg(known_commands[cmd])
             sys.exit(1)
         address = args[1]
@@ -615,7 +657,7 @@ if __name__ == '__main__':
             signature = args[2]
             message = ' '.join(args[3:])
         except:
-            print_error("Error: Not all parameters were given, displaying help instead.")
+            print_msg("Error: Not all parameters were given, displaying help instead.")
             print_msg(known_commands[cmd])
             sys.exit(1)
         if len(args) > 4:
@@ -643,3 +685,6 @@ if __name__ == '__main__':
         addr = args[1]
         print_msg(wallet.unprioritize(addr))
 
+
+    if cmd not in offline_commands and not options.offline:
+        synchronizer.stop()