move commands list to commands.py
[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
20 from util import *
21 from bitcoin import *
22 from decimal import Decimal
23 import bitcoin
24
25 known_commands = {
26     'help':'Prints this help',
27     'validateaddress':'Check that the address is valid', 
28     'balance': "Display the balance of your wallet or of an address.\nSyntax: balance [<address>]", 
29     'contacts': "Show your list of contacts", 
30     'create':'Create a wallet', 
31     'restore':'Restore a wallet', 
32     'payto':"""Create and broadcast a transaction.
33 Syntax: payto <recipient> <amount> [label]
34 <recipient> can be a bitcoin address or a label
35 options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address -\n  --changeaddr, -c: send change to address
36             """,
37     'sendrawtransaction':
38             'Broadcasts a transaction to the network. \nSyntax: sendrawtransaction <tx in hexadecimal>',
39     'password': 
40             "Changes your password",
41     'addresses':  
42             """Shows your list of addresses.
43 options:
44   -a: show all addresses, including change addresses""",
45
46     'history':"Shows the transaction history",
47     'setlabel':'Assign a label to an item\nSyntax: label <tx_hash> <label>',
48     'mktx':
49         """Create a signed transaction, password protected.
50 Syntax: mktx <recipient> <amount> [label]
51 options:\n  --fee, -f: set transaction fee\n  --fromaddr, -s: send from address -\n  --changeaddr, -c: send change to address
52         """,
53     'get_seed':
54             "Print the generation seed of your wallet.",
55     'importprivkey': 
56             'Import a private key\nSyntax: importprivkey <privatekey>',
57     'signmessage':
58             '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 "',
59     'verifymessage':
60              '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 "',
61     'eval':  
62              "Run python eval() on an object\nSyntax: eval <expression>\nExample: eval \"wallet.aliases\"",
63     'get': 
64              "Get config parameter.",
65     'set': 
66              "Set config parameter.",
67     'deseed':
68             "Create a seedless, watching-only wallet.",
69     'freeze':'',
70     'unfreeze':'',
71     'prioritize':'',
72     'unprioritize':'',
73     'dumpprivkey':'similar to bitcoind\'s command',
74     'dumpprivkeys':'dump all private keys',
75     'listunspent':'similar to bitcoind\'s command',
76     'createmultisig':'similar to bitcoind\'s command',
77     'createrawtransaction':'similar to bitcoind\'s command',
78     'decoderawtransaction':'similar to bitcoind\'s command',
79     'signrawtransaction':'similar to bitcoind\'s command',
80     'get_history': 'get history for an address'
81     
82     }
83
84
85
86 offline_commands = [ 'password', 'mktx',
87                      'setlabel', 'contacts',
88                      'help', 'validateaddress',
89                      'signmessage', 'verifymessage',
90                      'eval', 'set', 'get', 'create', 'addresses',
91                      'importprivkey', 'get_seed',
92                      'deseed',
93                      'freeze','unfreeze',
94                      'prioritize','unprioritize',
95                      'dumpprivkey','listunspent',
96                      'createmultisig', 'createrawtransaction', 'decoderawtransaction', 'signrawtransaction'
97                      ]
98
99 protected_commands = ['payto', 'password', 'mktx', 'get_seed', 'importprivkey','signmessage', 'signrawtransaction', 'dumpprivkey', 'dumpprivkeys' ]
100
101 class Commands:
102
103     def __init__(self, wallet, interface):
104         self.wallet = wallet
105         self.interface = interface
106
107     def _run(self, method, args, password_getter):
108         if method in protected_commands:
109             self.password = apply(password_getter,())
110         f = eval('self.'+method)
111         apply(f,args)
112         self.password = None
113
114     def get_history(self, addr):
115         h = self.wallet.get_history(addr)
116         if h is None: h = self.wallet.interface.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
117         print_json(h)
118
119     def listunspent(self):
120         l = self.wallet.get_unspent_coins()
121         for i in l: i["value"] = i["value"]*1e-8
122         print_json(l)
123
124     def createrawtransaction(self, inputs, outputs):
125         # convert to own format
126         for i in inputs:
127             i['tx_hash'] = i['txid']
128             i['index'] = i['vout']
129         outputs = map(lambda x: (x[0],int(1e8*x[1])), outputs.items())
130         tx = Transaction.from_io(inputs, outputs)
131         print_msg( tx )
132
133     def signrawtransaction(self, raw_tx, input_info, private_keys):
134         tx = Transaction(raw_tx)
135         unspent_coins = self.wallet.get_unspent_coins()
136
137         # convert private_keys to dict 
138         pk = {}
139         for sec in private_keys:
140             address = bitcoin.address_from_private_key(sec)
141             pk[address] = sec
142         private_keys = pk
143
144         for txin in tx.inputs:
145             # convert to own format
146             txin['tx_hash'] = txin['prevout_hash']
147             txin['index'] = txin['prevout_n']
148
149             for item in input_info:
150                 if item.get('txid') == txin['tx_hash'] and item.get('vout') == txin['index']:
151                     txin['raw_output_script'] = item['scriptPubKey']
152                     txin['redeemScript'] = item.get('redeemScript')
153                     txin['electrumKeyID'] = item.get('electrumKeyID')
154                     break
155             else:
156                 for item in unspent_coins:
157                     if txin['tx_hash'] == item['tx_hash'] and txin['index'] == item['index']:
158                         txin['raw_output_script'] = item['raw_output_script']
159                         break
160                 else:
161                     # if neither, we might want to get it from the server..
162                     raise
163
164             # find the address:
165             import deserialize
166             if txin.get('electrumKeyID'):
167                 n, for_change = txin.get('electrumKeyID')
168                 sec = wallet.sequence.get_private_key(n, for_change, seed)
169                 address = bitcoin.address_from_private_key(sec)
170                 txin['address'] = address
171                 private_keys[address] = sec
172
173             elif txin.get("redeemScript"):
174                 txin['address'] = bitcoin.hash_160_to_bc_address(bitcoin.hash_160(txin.get("redeemScript").decode('hex')), 5)
175
176             elif txin.get("raw_output_script"):
177                 addr = deserialize.get_address_from_output_script(txin.get("raw_output_script").decode('hex'))
178                 sec = wallet.get_private_key(addr, self.password)
179                 if sec: 
180                     private_keys[addr] = sec
181                     txin['address'] = addr
182
183         tx.sign( private_keys )
184         print_json({ "hex":str(tx),"complete":tx.is_complete})
185
186     def decoderawtransaction(self, raw):
187         tx = Transaction(raw)
188         print_json( tx.deserialize() )
189
190     def sendrawtransaction(self, raw):
191         tx = Transaction(raw)
192         r, h = wallet.sendtx( tx )
193         print_msg(h)
194
195     def createmultisig(self, num, pubkeys):
196         assert isinstance(pubkeys, list)
197         print_json( Transaction.multisig_script(pubkeys, num) )
198     
199     def freeze(self,addr):
200         print_msg(self.wallet.freeze(addr))
201         
202     def unfreeze(self,addr):
203         print_msg(self.wallet.unfreeze(addr))
204
205     def prioritize(self, addr):
206         print_msg(self.wallet.prioritize(addr))
207
208     def unprioritize(self, addr):
209         print_msg(self.wallet.unprioritize(addr))
210
211     def dumpprivkey(self, addr):
212         print_msg( self.wallet.get_private_key(addr, self.password) )
213
214     def dumpprivkeys(self, addresses):
215         print_json( self.wallet.get_private_keys(addresses, self.password) )
216
217
218     def validateaddress(self,addr):
219         is_valid = self.wallet.is_valid(addr)
220         out = { 'isvalid':is_valid }
221         if is_valid:
222             is_mine = self.wallet.is_mine(addr)
223             out['address'] = addr
224             out['ismine'] = is_mine
225             if is_mine:
226                 out['pubkey'] = self.wallet.get_public_key(addr)
227             
228         print_json(out)
229
230         
231     def balance(self, addresses = []):
232         if addresses == []:
233             c, u = self.wallet.get_balance()
234             if u:
235                 print_msg(Decimal( c ) / 100000000 , Decimal( u ) / 100000000)
236             else:
237                 print_msg(Decimal( c ) / 100000000)
238         else:
239             for addr in addresses:
240                 c, u = wallet.get_addr_balance(addr)
241                 if u:
242                     print_msg("%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)))
243                 else:
244                     print_msg("%s %s" % (addr, str(Decimal(c)/100000000)))
245
246
247     def get_seed(self):
248         import mnemonic
249         seed = self.wallet.decode_seed(self.password)
250         print_msg(seed + ' "' + ' '.join(mnemonic.mn_encode(seed)) + '"')
251
252     def importprivkey(self, sec):
253         try:
254             addr = wallet.import_key(sec,self.password)
255             wallet.save()
256             print_msg("Keypair imported: ", addr)
257         except BaseException as e:
258             print_msg("Error: Keypair import failed: " + str(e))
259
260
261     def sign_message(self, address, message):
262         print_msg(self.wallet.sign_message(address, message, self.password))
263
264
265     def verify_message(self, address, signature, message):
266         try:
267             EC_KEY.verify_message(address, signature, message)
268             print_msg(True)
269         except BaseException as e:
270             print_error("Verification error: {0}".format(e))
271             print_msg(False)
272
273
274     def _mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
275         for k, v in self.wallet.labels.items():
276             if v == to_address:
277                 to_address = k
278                 print_msg("alias", to_address)
279                 break
280             if change_addr and v == change_addr:
281                 change_addr = k
282
283         amount = int(10000000*amount)
284         if fee: fee = int(10000000*fee)
285         return self.wallet.mktx( [(to_address, amount)], self.password, fee , change_addr, from_addr)
286
287
288     def mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
289         tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
290         out = {"hex":str(tx), "complete":tx.is_complete}
291         if not tx.is_complete: 
292             out['input_info'] = repr(tx.input_info).replace(' ','')
293         print_json(out)
294
295
296     def payto(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
297         tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
298         r, h = wallet.sendtx( tx )
299         print_msg(h)
300
301
302     def history(self):
303         import datetime
304         balance = 0
305         for item in self.wallet.get_tx_history():
306             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
307             try:
308                 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
309             except:
310                 time_str = "----"
311
312             label, is_default_label = self.wallet.get_label(tx_hash)
313             if not label: label = tx_hash
314             else: label = label + ' '*(64 - len(label) )
315
316             print_msg("%17s"%time_str, "  " + label + "  " + format_satoshis(value)+ "  "+ format_satoshis(balance))
317         print_msg("# balance: ", format_satoshis(balance))
318
319
320     def setlabel(self, tx, label):
321         self.wallet.labels[tx] = label
322         self.wallet.save()
323             
324
325     def contacts(self):
326         c = {}
327         for addr in self.wallet.addressbook:
328             c[addr] = self.wallet.labels.get(addr)
329         print_json(c)
330
331
332     def addresses(self, show_all):
333         for addr in self.wallet.all_addresses():
334             if show_all or not self.wallet.is_change(addr):
335
336                 flags = self.wallet.get_address_flags(addr)
337                 label = self.wallet.labels.get(addr,'')
338                 if label: label = "\"%s\""%label
339                 b = format_satoshis(self.wallet.get_addr_balance(addr)[0])
340                 m_addr = "%34s"%addr
341                 print_msg(flags, m_addr, b, label)
342