rename 'addresses' command as 'listadresses'. use json syntax.
[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     'listaddresses':
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', 'listaddresses',
91                      'importprivkey', 'get_seed',
92                      'deseed',
93                      'freeze','unfreeze',
94                      'prioritize','unprioritize',
95                      'dumpprivkey','dumpprivkeys','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, callback = None):
104         self.wallet = wallet
105         self.interface = interface
106         self._callback = callback
107
108     def _run(self, method, args, password_getter):
109         if method in protected_commands:
110             self.password = apply(password_getter,())
111         f = eval('self.'+method)
112         result = apply(f,args)
113         self.password = None
114         if self._callback:
115             apply(self._callback, ())
116         return result
117
118     def get_history(self, addr):
119         h = self.wallet.get_history(addr)
120         if h is None: h = self.wallet.interface.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
121         return h
122
123     def listunspent(self):
124         import copy
125         l = copy.deepcopy(self.wallet.get_unspent_coins())
126         for i in l: i["value"] = str(Decimal(i["value"])/100000000)
127         return l
128
129     def createrawtransaction(self, inputs, outputs):
130         # convert to own format
131         for i in inputs:
132             i['tx_hash'] = i['txid']
133             i['index'] = i['vout']
134         outputs = map(lambda x: (x[0],int(1e8*x[1])), outputs.items())
135         tx = Transaction.from_io(inputs, outputs)
136         return tx.as_dict()
137
138     def signrawtransaction(self, raw_tx, input_info, private_keys):
139         tx = Transaction(raw_tx)
140         self.wallet.signrawtransaction(tx, input_info, private_keys, self.password)
141         return tx.as_dict()
142
143     def decoderawtransaction(self, raw):
144         tx = Transaction(raw)
145         return tx.deserialize()
146
147     def sendrawtransaction(self, raw):
148         tx = Transaction(raw)
149         r, h = wallet.sendtx( tx )
150         return h
151
152     def createmultisig(self, num, pubkeys):
153         assert isinstance(pubkeys, list)
154         return Transaction.multisig_script(pubkeys, num)
155     
156     def freeze(self,addr):
157         return self.wallet.freeze(addr)
158         
159     def unfreeze(self,addr):
160         return self.wallet.unfreeze(addr)
161
162     def prioritize(self, addr):
163         return self.wallet.prioritize(addr)
164
165     def unprioritize(self, addr):
166         return self.wallet.unprioritize(addr)
167
168     def dumpprivkey(self, addr):
169         return self.wallet.get_private_key(addr, self.password)
170
171     def dumpprivkeys(self, addresses = None):
172         if addresses is None:
173             addresses = self.wallet.all_addresses()
174         return self.wallet.get_private_keys(addresses, self.password)
175
176     def validateaddress(self,addr):
177         is_valid = self.wallet.is_valid(addr)
178         out = { 'isvalid':is_valid }
179         if is_valid:
180             is_mine = self.wallet.is_mine(addr)
181             out['address'] = addr
182             out['ismine'] = is_mine
183             if is_mine:
184                 out['pubkey'] = self.wallet.get_public_key(addr)
185             
186         return out
187
188         
189     def balance(self, addresses = []):
190         if addresses == []:
191             c, u = self.wallet.get_balance()
192         else:
193             c = u = 0
194             for addr in addresses:
195                 cc, uu = wallet.get_addr_balance(addr)
196                 c += cc
197                 u += uu
198
199         out = { "confirmed": str(Decimal(c)/100000000) }
200         if u: out["unconfirmed"] = str(Decimal(u)/100000000)
201         return out
202
203
204     def get_seed(self):
205         import mnemonic
206         seed = self.wallet.decode_seed(self.password)
207         return { "hex":seed, "mnemonic": ' '.join(mnemonic.mn_encode(seed)) }
208
209     def importprivkey(self, sec):
210         try:
211             addr = wallet.import_key(sec,self.password)
212             wallet.save()
213             out = "Keypair imported: ", addr
214         except BaseException as e:
215             out = "Error: Keypair import failed: " + str(e)
216         return out
217
218
219     def sign_message(self, address, message):
220         return self.wallet.sign_message(address, message, self.password)
221
222
223     def verify_message(self, address, signature, message):
224         try:
225             EC_KEY.verify_message(address, signature, message)
226             return True
227         except BaseException as e:
228             print_error("Verification error: {0}".format(e))
229             return False
230
231
232     def _mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
233         for k, v in self.wallet.labels.items():
234             if v == to_address:
235                 to_address = k
236                 print_msg("alias", to_address)
237                 break
238             if change_addr and v == change_addr:
239                 change_addr = k
240
241         amount = int(10000000*amount)
242         if fee: fee = int(10000000*fee)
243         return self.wallet.mktx( [(to_address, amount)], self.password, fee , change_addr, from_addr)
244
245
246     def mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
247         tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
248         return tx.as_dict()
249
250
251     def payto(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
252         tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
253         r, h = wallet.sendtx( tx )
254         return h
255
256
257     def history(self):
258         import datetime
259         balance = 0
260         out = []
261         for item in self.wallet.get_tx_history():
262             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
263             try:
264                 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
265             except:
266                 time_str = "----"
267
268             label, is_default_label = self.wallet.get_label(tx_hash)
269             if not label: label = tx_hash
270             else: label = label + ' '*(64 - len(label) )
271
272             out.append( "%16s"%time_str + "  " + label + "  " + format_satoshis(value)+ "  "+ format_satoshis(balance) )
273         return out
274
275
276
277     def setlabel(self, tx, label):
278         self.wallet.labels[tx] = label
279         self.wallet.save()
280             
281
282     def contacts(self):
283         c = {}
284         for addr in self.wallet.addressbook:
285             c[addr] = self.wallet.labels.get(addr)
286         return c
287
288
289     def listaddresses(self, show_all = False, show_balance = False, show_label = False):
290         out = []
291         for addr in self.wallet.all_addresses():
292             if show_all or not self.wallet.is_change(addr):
293                 if show_balance or show_label:
294                     item = { 'address': addr }
295                     if show_balance:
296                         item['balance'] = str(Decimal(self.wallet.get_addr_balance(addr)[0])/100000000)
297                     if show_label:
298                         label = self.wallet.labels.get(addr,'')
299                         if label:
300                             item['label'] = label
301                 else:
302                     item = addr
303                 out.append( item )
304         return out
305                          
306