3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
22 from decimal import Decimal
25 protected_commands = ['payto', 'password', 'mktx', 'get_seed', 'importprivkey','signmessage', 'signrawtransaction','dumpprivkey' ]
29 def __init__(self, wallet, interface):
31 self.interface = interface
33 def _run(self, method, args, password_getter):
34 if method in protected_commands:
35 pw = apply(password_getter,())
38 f = eval('self.'+method)
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]
46 def listunspent(self):
47 print_json(self.wallet.get_unspent_coins())
49 def createrawtransaction(self, inputs, outputs):
50 # convert to own format
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)
58 def signrawtransaction(self, raw_tx, input_info, private_keys, password):
59 tx = Transaction(raw_tx)
60 unspent_coins = self.wallet.get_unspent_coins()
62 # convert private_keys to dict
64 for sec in private_keys:
65 address = bitcoin.address_from_private_key(sec)
69 for txin in tx.inputs:
70 # convert to own format
71 txin['tx_hash'] = txin['prevout_hash']
72 txin['index'] = txin['prevout_n']
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')
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']
86 # if neither, we might want to get it from the server..
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
98 elif txin.get("redeemScript"):
99 txin['address'] = bitcoin.hash_160_to_bc_address(bitcoin.hash_160(txin.get("redeemScript").decode('hex')), 5)
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)
105 private_keys[addr] = sec
106 txin['address'] = addr
108 tx.sign( private_keys )
109 print_json({ "hex":str(tx),"complete":tx.is_complete})
111 def decoderawtransaction(self, raw):
112 tx = Transaction(raw)
113 print_json( tx.deserialize() )
115 def sendrawtransaction(self, raw):
116 tx = Transaction(raw)
117 r, h = wallet.sendtx( tx )
120 def createmultisig(self, num, pubkeys):
121 assert isinstance(pubkeys, list)
122 print_json( Transaction.multisig_script(pubkeys, num) )
124 def freeze(self,addr):
125 print_msg(self.wallet.freeze(addr))
127 def unfreeze(self,addr):
128 print_msg(self.wallet.unfreeze(addr))
130 def prioritize(self, addr):
131 print_msg(self.wallet.prioritize(addr))
133 def unprioritize(self, addr):
134 print_msg(self.wallet.unprioritize(addr))
136 def dumpprivkey(self, addr, password):
137 sec = self.wallet.get_private_key(addr, password)
140 def validateaddress(self,addr):
141 is_valid = self.wallet.is_valid(addr)
142 out = { 'isvalid':is_valid }
144 is_mine = self.wallet.is_mine(addr)
145 out['address'] = addr
146 out['ismine'] = is_mine
148 out['pubkey'] = self.wallet.get_public_key(addr)
153 def balance(self, addresses = []):
155 c, u = self.wallet.get_balance()
157 print_msg(Decimal( c ) / 100000000 , Decimal( u ) / 100000000)
159 print_msg(Decimal( c ) / 100000000)
161 for addr in addresses:
162 c, u = wallet.get_addr_balance(addr)
164 print_msg("%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)))
166 print_msg("%s %s" % (addr, str(Decimal(c)/100000000)))
169 def get_seed(self, password):
171 seed = self.wallet.decode_seed(password)
172 print_msg(seed + ' "' + ' '.join(mnemonic.mn_encode(seed)) + '"')
174 def importprivkey(self, sec):
176 addr = wallet.import_key(sec,password)
178 print_msg("Keypair imported: ", addr)
179 except BaseException as e:
180 print_msg("Error: Keypair import failed: " + str(e))
183 def sign_message(self, address, message, password):
184 print_msg(self.wallet.sign_message(address, message, password))
187 def verify_message(self, address, signature, message):
189 EC_KEY.verify_message(address, signature, message)
191 except BaseException as e:
192 print_error("Verification error: {0}".format(e))
196 def mktx(self, to_address, amount, fee, change_addr, from_addr, password = None):
198 for k, v in self.wallet.labels.items():
201 print_msg("alias", to_address)
203 if change_addr and v == change_addr:
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)
210 out = {"hex":str(tx), "complete":tx.is_complete}
211 if not tx.is_complete:
212 out['input_info'] = repr(tx.input_info).replace(' ','')
216 def payto(self, to_address, amount, fee, change_addr, from_addr, password = None):
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 )
228 for item in self.wallet.get_tx_history():
229 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
231 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
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) )
239 print_msg("%17s"%time_str, " " + label + " " + format_satoshis(value)+ " "+ format_satoshis(balance))
240 print_msg("# balance: ", format_satoshis(balance))
243 def setlabel(self, tx, label):
244 self.wallet.labels[tx] = label
250 for addr in self.wallet.addressbook:
251 c[addr] = self.wallet.labels.get(addr)