f3cf783ad2254a84184bf8d8f271b87ad015ffcb
[electrum-nvc.git] / lib / commands.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19 import datetime
20 import time
21 import copy
22 from util import print_msg, format_satoshis
23 from bitcoin import is_valid, hash_160_to_bc_address, hash_160
24 from decimal import Decimal
25 import bitcoin
26 from transaction import Transaction
27
28
29 class Command:
30     def __init__(self, name, min_args, max_args, requires_network, requires_wallet, requires_password, description, syntax = '', options_syntax = ''):
31         self.name = name
32         self.min_args=min_args
33         self.max_args = max_args
34         self.requires_network = requires_network
35         self.requires_wallet = requires_wallet
36         self.requires_password = requires_password
37         self.description = description
38         self.syntax = syntax
39         self.options = options_syntax
40
41
42 known_commands = {}
43
44
45 def register_command(*args):
46     global known_commands
47     name = args[0]
48     known_commands[name] = Command(*args)
49
50
51
52 payto_options = ' --fee, -f: set transaction fee\n --fromaddr, -F: send from address -\n --changeaddr, -c: send change to address'
53 listaddr_options = " -a: show all addresses, including change addresses\n -l: include labels in results"
54 restore_options = " accepts a seed or master public key."
55 mksendmany_syntax = 'mksendmanytx <recipient> <amount> [<recipient> <amount> ...]'
56 payto_syntax = "payto <recipient> <amount> [label]\n<recipient> can be a bitcoin address or a label"
57 paytomany_syntax = "paytomany <recipient> <amount> [<recipient> <amount> ...]\n<recipient> can be a bitcoin address or a label"
58 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 "'
59 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 "'
60
61
62 #                command
63 #                                              requires_network
64 #                                                     requires_wallet
65 #                                                            requires_password
66 register_command('contacts',             0, 0, False, True,  False, 'Show your list of contacts')
67 register_command('create',               0, 0, False, True,  False, 'Create a new wallet')
68 register_command('createmultisig',       2, 2, False, True,  False, 'similar to bitcoind\'s command')
69 register_command('createrawtransaction', 2, 2, False, True,  False, 'similar to bitcoind\'s command')
70 register_command('deseed',               0, 0, False, True,  False, 'Remove seed from wallet, creating a seedless, watching-only wallet.')
71 register_command('decoderawtransaction', 1, 1, False, False, False, 'similar to bitcoind\'s command')
72 register_command('getprivatekeys',       1, 1, False, True,  True,  'Get the private keys of a given address', 'getprivatekeys <bitcoin address>')
73 register_command('dumpprivkeys',         0, 0, False, True,  True,  'Dump all private keys in your wallet')
74 register_command('freeze',               1, 1, False, True,  True,  'Freeze the funds at one of your wallet\'s addresses', 'freeze <address>')
75 register_command('getbalance',           0, 1, True,  True,  False, 'Return the balance of your wallet, or of one account in your wallet', 'getbalance [<account>]')
76 register_command('getservers',           0, 0, True,  False, False, 'Return the list of available servers')
77 register_command('getversion',           0, 0, False, False, False, 'Return the version of your client', 'getversion')
78 register_command('getaddressbalance',    1, 1, True,  False, False, 'Return the balance of an address', 'getaddressbalance <address>')
79 register_command('getaddresshistory',    1, 1, True,  False, False, 'Return the transaction history of a wallet address', 'getaddresshistory <address>')
80 register_command('getconfig',            1, 1, False, False, False, 'Return a configuration variable', 'getconfig <name>')
81 register_command('getpubkeys',           1, 1, False, True,  False, 'Return the public keys for a wallet address', 'getpubkeys <bitcoin address>')
82 register_command('getrawtransaction',    1, 1, True,  False, False, 'Retrieve a transaction', 'getrawtransaction <txhash>')
83 register_command('getseed',              0, 0, False, True,  True,  'Print the generation seed of your wallet.')
84 register_command('getmpk',               0, 0, False, True,  False, 'Return your wallet\'s master public key', 'getmpk')
85 register_command('help',                 0, 1, False, False, False, 'Prints this help')
86 register_command('history',              0, 0, True,  True,  False, 'Returns the transaction history of your wallet')
87 register_command('importprivkey',        1, 1, False, True,  True,  'Import a private key', 'importprivkey <privatekey>')
88 register_command('listaddresses',        2, 2, False, True,  False, 'Returns your list of addresses.', '', listaddr_options)
89 register_command('listunspent',          0, 0, True,  True,  False, 'Returns the list of unspent inputs in your wallet.')
90 register_command('getaddressunspent',    1, 1, True,  False, False, 'Returns the list of unspent inputs for an address.')
91 register_command('mktx',                 5, 5, False, True,  True,  'Create a signed transaction', 'mktx <recipient> <amount> [label]', payto_options)
92 register_command('mksendmanytx',         4, 4, False, True,  True,  'Create a signed transaction', mksendmany_syntax, payto_options)
93 register_command('payto',                5, 5, True,  True,  True,  'Create and broadcast a transaction.', payto_syntax, payto_options)
94 register_command('paytomany',            4, 4, True,  True,  True,  'Create and broadcast a transaction.', paytomany_syntax, payto_options)
95 register_command('password',             0, 0, False, True,  True,  'Change your password')
96 register_command('restore',              0, 0, True,  True,  False, 'Restore a wallet', '', restore_options)
97 register_command('setconfig',            2, 2, False, False, False, 'Set a configuration variable', 'setconfig <name> <value>')
98 register_command('setlabel',             2,-1, False, True,  False, 'Assign a label to an item', 'setlabel <tx_hash> <label>')
99 register_command('sendrawtransaction',   1, 1, True,  False, False, 'Broadcasts a transaction to the network.', 'sendrawtransaction <tx in hexadecimal>')
100 register_command('signrawtransaction',   1, 3, False, True,  True,  'Sign a serailized transaction','signrawtransaction <tx in hexadecimal>')
101 register_command('signmessage',          2,-1, False, True,  True,  'Sign a message with a key', signmessage_syntax)
102 register_command('unfreeze',             1, 1, False, True,  False, 'Unfreeze the funds at one of your wallet\'s address', 'unfreeze <address>')
103 register_command('validateaddress',      1, 1, False, False, False, 'Check that the address is valid', 'validateaddress <address>')
104 register_command('verifymessage',        3,-1, False, False, False, 'Verifies a signature', verifymessage_syntax)
105
106 register_command('encrypt',              2,-1, False, False, False, 'encrypt a message with pubkey','encrypt <pubkey> <message>')
107 register_command('decrypt',              2,-1, False, True, True,   'decrypt a message encrypted with pubkey','decrypt <pubkey> <message>')
108 register_command('daemon',               1, 1, True, False, False,  '<stop|status>')
109 register_command('getproof',             1, 1, True, False, False, 'get merkle proof', 'getproof <address>')
110 register_command('getutxoaddress',       2, 2, True, False, False, 'get the address of an unspent transaction output','getutxoaddress <txid> <pos>')
111 register_command('sweep',                2, 3, True, False, False, 'Sweep a private key.', 'sweep privkey addr [fee]')
112
113
114 class Commands:
115
116     def __init__(self, wallet, network, callback = None):
117         self.wallet = wallet
118         self.network = network
119         self._callback = callback
120         self.password = None
121
122     def _run(self, method, args, password_getter):
123         cmd = known_commands[method]
124         if cmd.requires_password and self.wallet.use_encryption:
125             self.password = apply(password_getter,())
126         f = getattr(self, method)
127         result = f(*args)
128         self.password = None
129         if self._callback:
130             apply(self._callback, ())
131         return result
132
133     def getaddresshistory(self, addr):
134         return self.network.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
135
136     def daemon(self, arg):
137         if arg=='stop':
138             return self.network.stop()
139         elif arg=='status':
140             return {
141                 'server':self.network.main_server(),
142                 'connected':self.network.is_connected()
143             }
144         else:
145             return "unknown command \"%s\""% arg
146
147     def listunspent(self):
148         l = copy.deepcopy(self.wallet.get_unspent_coins())
149         for i in l: i["value"] = str(Decimal(i["value"])/100000000)
150         return l
151
152     def getaddressunspent(self, addr):
153         return self.network.synchronous_get([ ('blockchain.address.listunspent',[addr]) ])[0]
154
155     def getutxoaddress(self, txid, num):
156         r = self.network.synchronous_get([ ('blockchain.utxo.get_address',[txid, num]) ])
157         if r:
158             return {'address':r[0] }
159
160     def createrawtransaction(self, inputs, outputs):
161         for i in inputs:
162             i['prevout_hash'] = i['txid']
163             i['prevout_n'] = i['vout']
164         outputs = map(lambda x: (x[0],int(1e8*x[1])), outputs.items())
165         tx = Transaction.from_io(inputs, outputs)
166         return tx
167
168     def signrawtransaction(self, raw_tx, private_keys):
169         tx = Transaction(raw_tx)
170         self.wallet.signrawtransaction(tx, private_keys, self.password)
171         return tx
172
173     def decoderawtransaction(self, raw):
174         tx = Transaction(raw)
175         return tx.deserialize()
176
177     def sendrawtransaction(self, raw):
178         tx = Transaction(raw)
179         return self.network.synchronous_get([('blockchain.transaction.broadcast', [str(tx)])])[0]
180
181     def createmultisig(self, num, pubkeys):
182         assert isinstance(pubkeys, list)
183         redeem_script = Transaction.multisig_script(pubkeys, num)
184         address = hash_160_to_bc_address(hash_160(redeem_script.decode('hex')), 5)
185         return {'address':address, 'redeemScript':redeem_script}
186
187     def freeze(self,addr):
188         return self.wallet.freeze(addr)
189
190     def unfreeze(self,addr):
191         return self.wallet.unfreeze(addr)
192
193     def getprivatekeys(self, addr):
194         return self.wallet.get_private_key(addr, self.password)
195
196     def dumpprivkeys(self, addresses = None):
197         if addresses is None:
198             addresses = self.wallet.addresses(True)
199         return [self.wallet.get_private_key(address, self.password) for address in addresses]
200
201     def validateaddress(self, addr):
202         isvalid = is_valid(addr)
203         out = { 'isvalid':isvalid }
204         if isvalid:
205             out['address'] = addr
206         return out
207
208     def getpubkeys(self, addr):
209         out = { 'address':addr }
210         out['pubkeys'] = self.wallet.get_public_keys(addr)
211         return out
212
213     def getbalance(self, account= None):
214         if account is None:
215             c, u = self.wallet.get_balance()
216         else:
217             c, u = self.wallet.get_account_balance(account)
218
219         out = { "confirmed": str(Decimal(c)/100000000) }
220         if u: out["unconfirmed"] = str(Decimal(u)/100000000)
221         return out
222
223     def getaddressbalance(self, addr):
224         out = self.network.synchronous_get([ ('blockchain.address.get_balance',[addr]) ])[0]
225         out["confirmed"] =  str(Decimal(out["confirmed"])/100000000)
226         out["unconfirmed"] =  str(Decimal(out["unconfirmed"])/100000000)
227         return out
228
229     def getproof(self, addr):
230         p = self.network.synchronous_get([ ('blockchain.address.get_proof',[addr]) ])[0]
231         out = []
232         for i,s in p:
233             out.append(i)
234         return out
235
236     def getservers(self):
237         while not self.network.is_up_to_date():
238             time.sleep(0.1)
239         return self.network.get_servers()
240
241     def getversion(self):
242         import electrum  # Needs to stay here to prevent ciruclar imports
243         return electrum.ELECTRUM_VERSION
244
245     def getmpk(self):
246         return self.wallet.get_master_public_keys()
247
248     def getseed(self):
249         mnemonic = self.wallet.get_mnemonic(self.password)
250         return { 'mnemonic':mnemonic, 'version':self.wallet.seed_version }
251
252     def importprivkey(self, sec):
253         try:
254             addr = self.wallet.import_key(sec,self.password)
255             out = "Keypair imported: ", addr
256         except Exception as e:
257             out = "Error: Keypair import failed: " + str(e)
258         return out
259
260     def sweep(self, privkey, to_address, fee = 0.0001):
261         fee = int(Decimal(fee)*100000000)
262         return Transaction.sweep([privkey], self.network, to_address, fee)
263
264     def signmessage(self, address, message):
265         return self.wallet.sign_message(address, message, self.password)
266
267     def verifymessage(self, address, signature, message):
268         return bitcoin.verify_message(address, signature, message)
269
270     def _mktx(self, outputs, fee = None, change_addr = None, domain = None):
271         for to_address, amount in outputs:
272             if not is_valid(to_address):
273                 raise Exception("Invalid Bitcoin address", to_address)
274
275         if change_addr:
276             if not is_valid(change_addr):
277                 raise Exception("Invalid Bitcoin address", change_addr)
278
279         if domain is not None:
280             for addr in domain:
281                 if not is_valid(addr):
282                     raise Exception("invalid Bitcoin address", addr)
283
284                 if not self.wallet.is_mine(addr):
285                     raise Exception("address not in wallet", addr)
286
287         for k, v in self.wallet.labels.items():
288             if change_addr and v == change_addr:
289                 change_addr = k
290
291         final_outputs = []
292         for to_address, amount in outputs:
293             for k, v in self.wallet.labels.items():
294                 if v == to_address:
295                     to_address = k
296                     print_msg("alias", to_address)
297                     break
298
299             amount = int(100000000*amount)
300             final_outputs.append(('address', to_address, amount))
301
302         if fee: fee = int(100000000*fee)
303         return self.wallet.mktx(final_outputs, self.password, fee , change_addr, domain)
304
305     def mktx(self, to_address, amount, fee = None, change_addr = None, domain = None):
306         tx = self._mktx([(to_address, amount)], fee, change_addr, domain)
307         return tx
308
309     def mksendmanytx(self, outputs, fee = None, change_addr = None, domain = None):
310         tx = self._mktx(outputs, fee, change_addr, domain)
311         return tx
312
313     def payto(self, to_address, amount, fee = None, change_addr = None, domain = None):
314         tx = self._mktx([(to_address, amount)], fee, change_addr, domain)
315         r, h = self.wallet.sendtx( tx )
316         return h
317
318     def paytomany(self, outputs, fee = None, change_addr = None, domain = None):
319         tx = self._mktx(outputs, fee, change_addr, domain)
320         r, h = self.wallet.sendtx( tx )
321         return h
322
323     def history(self):
324         balance = 0
325         out = []
326         for item in self.wallet.get_tx_history():
327             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
328             try:
329                 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
330             except Exception:
331                 time_str = "----"
332
333             label, is_default_label = self.wallet.get_label(tx_hash)
334
335             out.append({'txid':tx_hash, 'date':"%16s"%time_str, 'label':label, 'value':format_satoshis(value)})
336         return out
337
338     def setlabel(self, key, label):
339         self.wallet.set_label(key, label)
340
341     def contacts(self):
342         c = {}
343         for addr in self.wallet.addressbook:
344             c[addr] = self.wallet.labels.get(addr)
345         return c
346
347     def listaddresses(self, show_all = False, show_label = False):
348         out = []
349         for addr in self.wallet.addresses(True):
350             if show_all or not self.wallet.is_change(addr):
351                 if show_label:
352                     item = { 'address': addr }
353                     if show_label:
354                         label = self.wallet.labels.get(addr,'')
355                         if label:
356                             item['label'] = label
357                 else:
358                     item = addr
359                 out.append( item )
360         return out
361
362     def help(self, cmd=None):
363         if cmd not in known_commands:
364             print_msg("\nList of commands:", ', '.join(sorted(known_commands)))
365         else:
366             cmd = known_commands[cmd]
367             print_msg(cmd.description)
368             if cmd.syntax: print_msg("Syntax: " + cmd.syntax)
369             if cmd.options: print_msg("options:\n" + cmd.options)
370         return None
371
372     def getrawtransaction(self, tx_hash):
373         if self.wallet:
374             tx = self.wallet.transactions.get(tx_hash)
375             if tx:
376                 return tx
377
378         r = self.network.synchronous_get([ ('blockchain.transaction.get',[tx_hash]) ])[0]
379         if r:
380             return Transaction(r)
381         else:
382             return "unknown transaction"
383
384     def encrypt(self, pubkey, message):
385         return bitcoin.encrypt_message(message, pubkey)
386
387     def decrypt(self, pubkey, message):
388         return self.wallet.decrypt_message(pubkey, message, self.password)