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
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
38 'Broadcasts a transaction to the network. \nSyntax: sendrawtransaction <tx in hexadecimal>',
40 "Changes your password",
42 """Shows your list of addresses.
44 -a: show all addresses, including change addresses""",
46 'history':"Shows the transaction history",
47 'setlabel':'Assign a label to an item\nSyntax: label <tx_hash> <label>',
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
54 "Print the generation seed of your wallet.",
56 'Import a private key\nSyntax: importprivkey <privatekey>',
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 "',
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 "',
62 "Run python eval() on an object\nSyntax: eval <expression>\nExample: eval \"wallet.aliases\"",
64 "Get config parameter.",
66 "Set config parameter.",
68 "Create a seedless, watching-only wallet.",
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'
86 offline_commands = [ 'password', 'mktx',
87 'setlabel', 'contacts',
88 'help', 'validateaddress',
89 'signmessage', 'verifymessage',
90 'eval', 'set', 'get', 'create', 'addresses',
91 'importprivkey', 'get_seed',
94 'prioritize','unprioritize',
95 'dumpprivkey','dumpprivkeys','listunspent',
96 'createmultisig', 'createrawtransaction', 'decoderawtransaction', 'signrawtransaction'
99 protected_commands = ['payto', 'password', 'mktx', 'get_seed', 'importprivkey','signmessage', 'signrawtransaction', 'dumpprivkey', 'dumpprivkeys' ]
103 def __init__(self, wallet, interface, callback = None):
105 self.interface = interface
106 self.callback = callback
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)
115 apply(self.callback, ())
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]
123 def listunspent(self):
125 l = copy.deepcopy(self.wallet.get_unspent_coins())
126 for i in l: i["value"] = i["value"]*1e-8
129 def createrawtransaction(self, inputs, outputs):
130 # convert to own format
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)
138 def signrawtransaction(self, raw_tx, input_info, private_keys):
139 tx = Transaction(raw_tx)
140 unspent_coins = self.wallet.get_unspent_coins()
142 # convert private_keys to dict
144 for sec in private_keys:
145 address = bitcoin.address_from_private_key(sec)
149 for txin in tx.inputs:
150 # convert to own format
151 txin['tx_hash'] = txin['prevout_hash']
152 txin['index'] = txin['prevout_n']
154 for item in input_info:
155 if item.get('txid') == txin['tx_hash'] and item.get('vout') == txin['index']:
156 txin['raw_output_script'] = item['scriptPubKey']
157 txin['redeemScript'] = item.get('redeemScript')
158 txin['electrumKeyID'] = item.get('electrumKeyID')
161 for item in unspent_coins:
162 if txin['tx_hash'] == item['tx_hash'] and txin['index'] == item['index']:
163 txin['raw_output_script'] = item['raw_output_script']
166 # if neither, we might want to get it from the server..
171 if txin.get('electrumKeyID'):
172 n, for_change = txin.get('electrumKeyID')
173 sec = wallet.sequence.get_private_key(n, for_change, seed)
174 address = bitcoin.address_from_private_key(sec)
175 txin['address'] = address
176 private_keys[address] = sec
178 elif txin.get("redeemScript"):
179 txin['address'] = bitcoin.hash_160_to_bc_address(bitcoin.hash_160(txin.get("redeemScript").decode('hex')), 5)
181 elif txin.get("raw_output_script"):
182 addr = deserialize.get_address_from_output_script(txin.get("raw_output_script").decode('hex'))
183 sec = wallet.get_private_key(addr, self.password)
185 private_keys[addr] = sec
186 txin['address'] = addr
188 tx.sign( private_keys )
191 def decoderawtransaction(self, raw):
192 tx = Transaction(raw)
193 return tx.deserialize()
195 def sendrawtransaction(self, raw):
196 tx = Transaction(raw)
197 r, h = wallet.sendtx( tx )
200 def createmultisig(self, num, pubkeys):
201 assert isinstance(pubkeys, list)
202 return Transaction.multisig_script(pubkeys, num)
204 def freeze(self,addr):
205 return self.wallet.freeze(addr)
207 def unfreeze(self,addr):
208 return self.wallet.unfreeze(addr)
210 def prioritize(self, addr):
211 return self.wallet.prioritize(addr)
213 def unprioritize(self, addr):
214 return self.wallet.unprioritize(addr)
216 def dumpprivkey(self, addr):
217 return self.wallet.get_private_key(addr, self.password)
219 def dumpprivkeys(self, addresses):
220 return self.wallet.get_private_keys(addresses, self.password)
222 def validateaddress(self,addr):
223 is_valid = self.wallet.is_valid(addr)
224 out = { 'isvalid':is_valid }
226 is_mine = self.wallet.is_mine(addr)
227 out['address'] = addr
228 out['ismine'] = is_mine
230 out['pubkey'] = self.wallet.get_public_key(addr)
235 def balance(self, addresses = []):
237 c, u = self.wallet.get_balance()
240 for addr in addresses:
241 cc, uu = wallet.get_addr_balance(addr)
245 out = { "confirmed": str(Decimal(c)/100000000) }
246 if u: out["unconfirmed"] = str(Decimal(u)/100000000)
252 seed = self.wallet.decode_seed(self.password)
253 return { "hex":seed, "mnemonic": ' '.join(mnemonic.mn_encode(seed)) }
255 def importprivkey(self, sec):
257 addr = wallet.import_key(sec,self.password)
259 out = "Keypair imported: ", addr
260 except BaseException as e:
261 out = "Error: Keypair import failed: " + str(e)
265 def sign_message(self, address, message):
266 return self.wallet.sign_message(address, message, self.password)
269 def verify_message(self, address, signature, message):
271 EC_KEY.verify_message(address, signature, message)
273 except BaseException as e:
274 print_error("Verification error: {0}".format(e))
278 def _mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
279 for k, v in self.wallet.labels.items():
282 print_msg("alias", to_address)
284 if change_addr and v == change_addr:
287 amount = int(10000000*amount)
288 if fee: fee = int(10000000*fee)
289 return self.wallet.mktx( [(to_address, amount)], self.password, fee , change_addr, from_addr)
292 def mktx(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
293 tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
297 def payto(self, to_address, amount, fee = None, change_addr = None, from_addr = None):
298 tx = self._mktx(to_address, amount, fee, change_addr, from_addr)
299 r, h = wallet.sendtx( tx )
307 for item in self.wallet.get_tx_history():
308 tx_hash, conf, is_mine, value, fee, balance, timestamp = item
310 time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
314 label, is_default_label = self.wallet.get_label(tx_hash)
315 if not label: label = tx_hash
316 else: label = label + ' '*(64 - len(label) )
318 out.append( "%16s"%time_str + " " + label + " " + format_satoshis(value)+ " "+ format_satoshis(balance) )
323 def setlabel(self, tx, label):
324 self.wallet.labels[tx] = label
330 for addr in self.wallet.addressbook:
331 c[addr] = self.wallet.labels.get(addr)
335 def addresses(self, show_all):
337 for addr in self.wallet.all_addresses():
338 if show_all or not self.wallet.is_change(addr):
340 flags = self.wallet.get_address_flags(addr)
341 label = self.wallet.labels.get(addr,'')
342 if label: label = "\"%s\""%label
343 b = format_satoshis(self.wallet.get_addr_balance(addr)[0])
345 out.append( flags + ' ' + m_addr + ' ' + b + ' ' + label )