rm unneeded import
[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 protected_commands = ['payto', 'password', 'mktx', 'get_seed', 'importprivkey','signmessage', 'signrawtransaction','dumpprivkey' ]
26
27 class Commands:
28
29     def __init__(self, wallet, interface):
30         self.wallet = wallet
31         self.interface = interface
32
33     def _run(self, method, args, password_getter):
34         if method in protected_commands:
35             pw = apply(password_getter,())
36             args += (pw,)
37             
38         f = eval('self.'+method)
39         apply(f,args)
40
41     def get_history(self, addr):
42         h = self.wallet.get_history(addr)
43         if h is None: h = self.wallet.interface.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
44         print_json(h)
45
46     def listunspent(self):
47         print_json(self.wallet.get_unspent_coins())
48
49     def createrawtransaction(self, inputs, outputs):
50         # convert to own format
51         for i in inputs:
52             i['tx_hash'] = i['txid']
53             i['index'] = i['vout']
54         outputs = map(lambda x: (x[0],int(1e8*x[1])), outputs.items())
55         tx = Transaction.from_io(inputs, outputs)
56         print_msg( tx )
57
58     def signrawtransaction(self, raw_tx, input_info, private_keys, password):
59         tx = Transaction(raw_tx)
60         unspent_coins = self.wallet.get_unspent_coins()
61
62         # convert private_keys to dict 
63         pk = {}
64         for sec in private_keys:
65             address = bitcoin.address_from_private_key(sec)
66             pk[address] = sec
67         private_keys = pk
68
69         for txin in tx.inputs:
70             # convert to own format
71             txin['tx_hash'] = txin['prevout_hash']
72             txin['index'] = txin['prevout_n']
73
74             for item in input_info:
75                 if item.get('txid') == txin['tx_hash'] and item.get('vout') == txin['index']:
76                     txin['raw_output_script'] = item['scriptPubKey']
77                     txin['redeemScript'] = item.get('redeemScript')
78                     txin['electrumKeyID'] = item.get('electrumKeyID')
79                     break
80             else:
81                 for item in unspent_coins:
82                     if txin['tx_hash'] == item['tx_hash'] and txin['index'] == item['index']:
83                         txin['raw_output_script'] = item['raw_output_script']
84                         break
85                 else:
86                     # if neither, we might want to get it from the server..
87                     raise
88
89             # find the address:
90             import deserialize
91             if txin.get('electrumKeyID'):
92                 n, for_change = txin.get('electrumKeyID')
93                 sec = wallet.sequence.get_private_key(n, for_change, seed)
94                 address = bitcoin.address_from_private_key(sec)
95                 txin['address'] = address
96                 private_keys[address] = sec
97
98             elif txin.get("redeemScript"):
99                 txin['address'] = bitcoin.hash_160_to_bc_address(bitcoin.hash_160(txin.get("redeemScript").decode('hex')), 5)
100
101             elif txin.get("raw_output_script"):
102                 addr = deserialize.get_address_from_output_script(txin.get("raw_output_script").decode('hex'))
103                 sec = wallet.get_private_key(addr, password)
104                 if sec: 
105                     private_keys[addr] = sec
106                     txin['address'] = addr
107
108         tx.sign( private_keys )
109         print_json({ "hex":str(tx),"complete":tx.is_complete})
110
111     def decoderawtransaction(self, raw):
112         tx = Transaction(raw)
113         print_json( tx.deserialize() )
114
115     def sendrawtransaction(self, raw):
116         tx = Transaction(raw)
117         r, h = wallet.sendtx( tx )
118         print_msg(h)
119
120     def createmultisig(self, num, pubkeys):
121         assert isinstance(pubkeys, list)
122         print_json( Transaction.multisig_script(pubkeys, num) )
123     
124     def freeze(self,addr):
125         print_msg(self.wallet.freeze(addr))
126         
127     def unfreeze(self,addr):
128         print_msg(self.wallet.unfreeze(addr))
129
130     def prioritize(self, addr):
131         print_msg(self.wallet.prioritize(addr))
132
133     def unprioritize(self, addr):
134         print_msg(self.wallet.unprioritize(addr))
135
136     def dumpprivkey(self, addr, password):
137         sec = self.wallet.get_private_key(addr, password)
138         print_msg( sec )
139
140     def validateaddress(self,addr):
141         is_valid = self.wallet.is_valid(addr)
142         out = { 'isvalid':is_valid }
143         if is_valid:
144             is_mine = self.wallet.is_mine(addr)
145             out['address'] = addr
146             out['ismine'] = is_mine
147             if is_mine:
148                 out['pubkey'] = self.wallet.get_public_key(addr)
149             
150         print_json(out)
151
152         
153     def balance(self, addresses = []):
154         if addresses == []:
155             c, u = self.wallet.get_balance()
156             if u:
157                 print_msg(Decimal( c ) / 100000000 , Decimal( u ) / 100000000)
158             else:
159                 print_msg(Decimal( c ) / 100000000)
160         else:
161             for addr in addresses:
162                 c, u = wallet.get_addr_balance(addr)
163                 if u:
164                     print_msg("%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)))
165                 else:
166                     print_msg("%s %s" % (addr, str(Decimal(c)/100000000)))
167
168
169     def get_seed(self, password):
170         import mnemonic
171         seed = self.wallet.decode_seed(password)
172         print_msg(seed + ' "' + ' '.join(mnemonic.mn_encode(seed)) + '"')
173
174     def importprivkey(self, sec):
175         try:
176             addr = wallet.import_key(sec,password)
177             wallet.save()
178             print_msg("Keypair imported: ", addr)
179         except BaseException as e:
180             print_msg("Error: Keypair import failed: " + str(e))
181
182
183     def sign_message(self, address, message, password):
184         print_msg(self.wallet.sign_message(address, message, password))
185
186
187     def verify_message(self, address, signature, message):
188         try:
189             EC_KEY.verify_message(address, signature, message)
190             print_msg(True)
191         except BaseException as e:
192             print_error("Verification error: {0}".format(e))
193             print_msg(False)
194
195
196     def mktx(self, to_address, amount, fee, change_addr, from_addr, password = None):
197             
198         for k, v in self.wallet.labels.items():
199             if v == to_address:
200                 to_address = k
201                 print_msg("alias", to_address)
202                 break
203             if change_addr and v == change_addr:
204                 change_addr = k
205
206         amount = int(10000000*amount)
207         if fee: fee = int(10000000*fee)
208         tx = self.wallet.mktx( [(to_address, amount)], password, fee , change_addr, from_addr)
209
210         out = {"hex":str(tx), "complete":tx.is_complete}
211         if not tx.is_complete: 
212             out['input_info'] = repr(tx.input_info).replace(' ','')
213         print_json(out)
214
215
216     def payto(self, to_address, amount, fee, change_addr, from_addr, password = None):
217
218         amount = int(10000000*amount)
219         if fee: fee = int(10000000*fee)
220         tx = self.wallet.mktx( [(to_address, amount)], password, fee, change_addr, from_addr )
221         r, h = wallet.sendtx( tx )
222         print_msg(h)
223
224
225     def history(self):
226         import datetime
227         balance = 0
228         for item in self.wallet.get_tx_history():
229             tx_hash, conf, is_mine, value, fee, balance, timestamp = item
230             try:
231                 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
232             except:
233                 time_str = "----"
234
235             label, is_default_label = self.wallet.get_label(tx_hash)
236             if not label: label = tx_hash
237             else: label = label + ' '*(64 - len(label) )
238
239             print_msg("%17s"%time_str, "  " + label + "  " + format_satoshis(value)+ "  "+ format_satoshis(balance))
240         print_msg("# balance: ", format_satoshis(balance))
241
242
243     def setlabel(self, tx, label):
244         self.wallet.labels[tx] = label
245         self.wallet.save()
246             
247
248     def contacts(self):
249         c = {}
250         for addr in self.wallet.addressbook:
251             c[addr] = self.wallet.labels.get(addr)
252         print_json(c)
253