parse_URI: amount is in satoshis
[electrum-nvc.git] / lib / commands.py
index 2cf1996..5e6d9dc 100644 (file)
@@ -16,6 +16,7 @@
 # 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 time
 from util import *
 from bitcoin import *
 from decimal import Decimal
@@ -62,16 +63,17 @@ register_command('createmultisig',       2, 2, False, True,  False, 'similar to
 register_command('createrawtransaction', 2, 2, False, True,  False, 'similar to bitcoind\'s command')
 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('dumpprivkey',          1, 1, False, True,  True,  'Dumps a specified private key for a given address', 'dumpprivkey <bitcoin address>')
-register_command('dumpprivkeys',         0, 0, False, True,  True,  'dump all private keys')
+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('getaddressbalance',    1, 1, True,  True,  False, 'Return the balance of an address', 'getbalance <address>')
-register_command('getaddresshistory',    1, 1, True,  True,  False, 'Return the transaction history of a wallet address', 'getaddresshistory <address>')
+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, 2, True,  False, False, 'Retrieve a transaction', 'getrawtransaction <txhash> <height>')
+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')
@@ -79,6 +81,7 @@ register_command('history',              0, 0, True,  True,  False, 'Returns the
 register_command('importprivkey',        1, 1, False, True,  True,  'Import a private key', 'importprivkey <privatekey>')
 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)
@@ -94,6 +97,13 @@ register_command('unfreeze',             1, 1, False, True,  False, 'Unfreeze th
 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('daemon',               1, 1, True, False, False,  '<stop|status>')
+register_command('getproof',             1, 1, True, False, False, 'get merkle proof', '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]')
+
 
 
 
@@ -105,6 +115,7 @@ class Commands:
         self._callback = callback
         self.password = None
 
+
     def _run(self, method, args, password_getter):
         cmd = known_commands[method]
         if cmd.requires_password and self.wallet.use_encryption:
@@ -116,11 +127,22 @@ class Commands:
             apply(self._callback, ())
         return result
 
+
     def getaddresshistory(self, addr):
-        assert self.wallet.is_mine(addr)
-        h = self.wallet.get_history(addr)
-        if h is None: h = self.network.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
-        return h
+        return self.network.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
+
+
+    def daemon(self, arg):
+        if arg=='stop':
+            return self.network.stop()
+        elif arg=='status':
+            return { 
+                'server':self.network.main_server(), 
+                'connected':self.network.is_connected()
+            }
+        else:
+            return "unknown command \"%s\""% arg
+
 
     def listunspent(self):
         import copy
@@ -128,15 +150,26 @@ class Commands:
         for i in l: i["value"] = str(Decimal(i["value"])/100000000)
         return l
 
+
+    def getaddressunspent(self, addr):
+        return self.network.synchronous_get([ ('blockchain.address.listunspent',[addr]) ])[0]
+
+
+    def getutxoaddress(self, txid, num):
+        r = self.network.synchronous_get([ ('blockchain.utxo.get_address',[txid, num]) ])
+        if r: 
+            return {'address':r[0] }
+
+
     def createrawtransaction(self, inputs, outputs):
-        # convert to own format
         for i in inputs:
-            i['tx_hash'] = i['txid']
-            i['index'] = i['vout']
+            i['prevout_hash'] = i['txid']
+            i['prevout_n'] = i['vout']
         outputs = map(lambda x: (x[0],int(1e8*x[1])), outputs.items())
         tx = Transaction.from_io(inputs, outputs)
         return tx
 
+
     def signrawtransaction(self, raw_tx, input_info, private_keys):
         tx = Transaction(raw_tx)
         self.wallet.signrawtransaction(tx, input_info, private_keys, self.password)
@@ -148,8 +181,7 @@ class Commands:
 
     def sendrawtransaction(self, raw):
         tx = Transaction(raw)
-        r, h = self.wallet.sendtx( tx )
-        return h
+        return self.network.synchronous_get([('blockchain.transaction.broadcast', [str(tx)])])[0]
 
     def createmultisig(self, num, pubkeys):
         assert isinstance(pubkeys, list)
@@ -163,7 +195,7 @@ class Commands:
     def unfreeze(self,addr):
         return self.wallet.unfreeze(addr)
 
-    def dumpprivkey(self, addr):
+    def getprivatekeys(self, addr):
         return self.wallet.get_private_key(addr, self.password)
 
     def dumpprivkeys(self, addresses = None):
@@ -179,15 +211,11 @@ class Commands:
         return out
 
     def getpubkeys(self, addr):
-        assert is_valid(addr) and self.wallet.is_mine(addr)
         out = { 'address':addr }
-        account, sequence = self.wallet.get_address_index(addr)
-        if account != -1:
-            a = self.wallet.accounts[account]
-            out['pubkeys'] = a.get_pubkeys( sequence )
-
+        out['pubkeys'] = self.wallet.getpubkeys(addr)
         return out
 
+
     def getbalance(self, account= None):
         if account is None:
             c, u = self.wallet.get_balance()
@@ -199,21 +227,34 @@ class Commands:
         return out
 
     def getaddressbalance(self, addr):
-        c, u = self.wallet.get_addr_balance(addr)
-        out = { "confirmed": str(Decimal(c)/100000000) }
-        if u: out["unconfirmed"] = str(Decimal(u)/100000000)
+        out = self.network.synchronous_get([ ('blockchain.address.get_balance',[addr]) ])[0]
+        out["confirmed"] =  str(Decimal(out["confirmed"])/100000000)
+        out["unconfirmed"] =  str(Decimal(out["unconfirmed"])/100000000)
+        return out
+
+
+    def getproof(self, addr):
+        p = self.network.synchronous_get([ ('blockchain.address.get_proof',[addr]) ])[0]
+        out = []
+        for i,s in p:
+            out.append(i)
         return out
 
     def getservers(self):
+        while not self.network.is_up_to_date():
+            time.sleep(0.1)
         return self.network.get_servers()
 
+    def getversion(self):
+        import electrum 
+        return electrum.ELECTRUM_VERSION
     def getmpk(self):
         return self.wallet.get_master_public_key()
 
     def getseed(self):
         mnemonic = self.wallet.get_mnemonic(self.password)
-        seed = self.wallet.get_seed(self.password)
-        return { 'mnemonic':mnemonic, 'seed':seed, 'version':self.wallet.seed_version }
+        return { 'mnemonic':mnemonic, 'version':self.wallet.seed_version }
 
     def importprivkey(self, sec):
         try:
@@ -224,6 +265,11 @@ class Commands:
         return out
 
 
+    def sweep(self, privkey, to_address, fee = 0.0001):
+        fee = int(Decimal(fee)*100000000)
+        return Transaction.sweep([privkey], self.network, to_address, fee)
+
+
     def signmessage(self, address, message):
         return self.wallet.sign_message(address, message, self.password)
 
@@ -301,10 +347,8 @@ class Commands:
                 time_str = "----"
 
             label, is_default_label = self.wallet.get_label(tx_hash)
-            if not label: label = tx_hash
-            else: label = label + ' '*(64 - len(label) )
 
-            out.append( "%16s"%time_str + "  " + label + "  " + format_satoshis(value)+ "  "+ format_satoshis(balance) )
+            out.append({'txid':tx_hash, 'date':"%16s"%time_str, 'label':label, 'value':format_satoshis(value)})
         return out
 
 
@@ -346,11 +390,27 @@ class Commands:
             if cmd.options: print_msg("options:\n" + cmd.options)
         return None
 
-    def getrawtransaction(self, tx_hash, height = 0):
-        tx = self.wallet.transactions.get(tx_hash)
-        if tx:
-            return tx
-        height = int(height)
-        return self.network.retrieve_transaction(tx_hash, height)
+
+    def getrawtransaction(self, tx_hash):
+        import transaction
+        if self.wallet:
+            tx = self.wallet.transactions.get(tx_hash)
+            if tx:
+                return tx
+
+        r = self.network.synchronous_get([ ('blockchain.transaction.get',[tx_hash]) ])[0]
+        if r:
+            return transaction.Transaction(r)
+        else:
+            return "unknown transaction"
+
+
+    def encrypt(self, pubkey, message):
+        return bitcoin.encrypt_message(message, pubkey)
+
+
+    def decrypt(self, pubkey, message):
+        return self.wallet.decrypt_message(pubkey, message, self.password)
+