better error messages
[electrum-nvc.git] / lib / wallet.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 import sys, base64, os, re, hashlib, copy, operator, ast, threading, random
21 import aes, ecdsa
22 from ecdsa.util import string_to_number, number_to_string
23
24 ############ functions from pywallet ##################### 
25
26 addrtype = 0
27
28 def hash_160(public_key):
29     try:
30         md = hashlib.new('ripemd160')
31         md.update(hashlib.sha256(public_key).digest())
32         return md.digest()
33     except:
34         import ripemd
35         md = ripemd.new(hashlib.sha256(public_key).digest())
36         return md.digest()
37
38
39 def public_key_to_bc_address(public_key):
40     h160 = hash_160(public_key)
41     return hash_160_to_bc_address(h160)
42
43 def hash_160_to_bc_address(h160):
44     vh160 = chr(addrtype) + h160
45     h = Hash(vh160)
46     addr = vh160 + h[0:4]
47     return b58encode(addr)
48
49 def bc_address_to_hash_160(addr):
50     bytes = b58decode(addr, 25)
51     return bytes[1:21]
52
53 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
54 __b58base = len(__b58chars)
55
56 def b58encode(v):
57     """ encode v, which is a string of bytes, to base58.                
58     """
59
60     long_value = 0L
61     for (i, c) in enumerate(v[::-1]):
62         long_value += (256**i) * ord(c)
63
64     result = ''
65     while long_value >= __b58base:
66         div, mod = divmod(long_value, __b58base)
67         result = __b58chars[mod] + result
68         long_value = div
69     result = __b58chars[long_value] + result
70
71     # Bitcoin does a little leading-zero-compression:
72     # leading 0-bytes in the input become leading-1s
73     nPad = 0
74     for c in v:
75         if c == '\0': nPad += 1
76         else: break
77
78     return (__b58chars[0]*nPad) + result
79
80 def b58decode(v, length):
81     """ decode v into a string of len bytes
82     """
83     long_value = 0L
84     for (i, c) in enumerate(v[::-1]):
85         long_value += __b58chars.find(c) * (__b58base**i)
86
87     result = ''
88     while long_value >= 256:
89         div, mod = divmod(long_value, 256)
90         result = chr(mod) + result
91         long_value = div
92     result = chr(long_value) + result
93
94     nPad = 0
95     for c in v:
96         if c == __b58chars[0]: nPad += 1
97         else: break
98
99     result = chr(0)*nPad + result
100     if length is not None and len(result) != length:
101         return None
102
103     return result
104
105
106 def Hash(data):
107     return hashlib.sha256(hashlib.sha256(data).digest()).digest()
108
109 def EncodeBase58Check(vchIn):
110     hash = Hash(vchIn)
111     return b58encode(vchIn + hash[0:4])
112
113 def DecodeBase58Check(psz):
114     vchRet = b58decode(psz, None)
115     key = vchRet[0:-4]
116     csum = vchRet[-4:]
117     hash = Hash(key)
118     cs32 = hash[0:4]
119     if cs32 != csum:
120         return None
121     else:
122         return key
123
124 def PrivKeyToSecret(privkey):
125     return privkey[9:9+32]
126
127 def SecretToASecret(secret):
128     vchIn = chr(addrtype+128) + secret
129     return EncodeBase58Check(vchIn)
130
131 def ASecretToSecret(key):
132     vch = DecodeBase58Check(key)
133     if vch and vch[0] == chr(addrtype+128):
134         return vch[1:]
135     else:
136         return False
137
138 ########### end pywallet functions #######################
139
140 # URL decode
141 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
142 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
143
144
145 def int_to_hex(i, length=1):
146     s = hex(i)[2:].rstrip('L')
147     s = "0"*(2*length - len(s)) + s
148     return s.decode('hex')[::-1].encode('hex')
149
150
151 # AES
152 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
153 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
154
155
156
157 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
158 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
159 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
160 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
161 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
162 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
163 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
164 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
165 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
166 oid_secp256k1 = (1,3,132,0,10)
167 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
168
169
170 def filter(s): 
171     out = re.sub('( [^\n]*|)\n','',s)
172     out = out.replace(' ','')
173     out = out.replace('\n','')
174     return out
175
176 def raw_tx( inputs, outputs, for_sig = None ):
177     s  = int_to_hex(1,4)                                     +   '     version\n' 
178     s += int_to_hex( len(inputs) )                           +   '     number of inputs\n'
179     for i in range(len(inputs)):
180         _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
181         s += p_hash.decode('hex')[::-1].encode('hex')        +  '     prev hash\n'
182         s += int_to_hex(p_index,4)                           +  '     prev index\n'
183         if for_sig is None:
184             sig = sig + chr(1)                               # hashtype
185             script  = int_to_hex( len(sig))                  +  '     push %d bytes\n'%len(sig)
186             script += sig.encode('hex')                      +  '     sig\n'
187             pubkey = chr(4) + pubkey
188             script += int_to_hex( len(pubkey))               +  '     push %d bytes\n'%len(pubkey)
189             script += pubkey.encode('hex')                   +  '     pubkey\n'
190         elif for_sig==i:
191             script = p_script                                +  '     scriptsig \n'
192         else:
193             script=''
194         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
195         s += script
196         s += "ffffffff"                                      +  '     sequence\n'
197     s += int_to_hex( len(outputs) )                          +  '     number of outputs\n'
198     for output in outputs:
199         addr, amount = output
200         s += int_to_hex( amount, 8)                          +  '     amount: %d\n'%amount 
201         script = '76a9'                                      # op_dup, op_hash_160
202         script += '14'                                       # push 0x14 bytes
203         script += bc_address_to_hash_160(addr).encode('hex')
204         script += '88ac'                                     # op_equalverify, op_checksig
205         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
206         s += script                                          +  '     script \n'
207     s += int_to_hex(0,4)                                     # lock time
208     if for_sig is not None: s += int_to_hex(1, 4)            # hash type
209     return s
210
211
212
213
214 def format_satoshis(x, is_diff=False, num_zeros = 0):
215     from decimal import Decimal
216     s = Decimal(x)
217     sign, digits, exp = s.as_tuple()
218     digits = map(str, digits)
219     while len(digits) < 9:
220         digits.insert(0,'0')
221     digits.insert(-8,'.')
222     s = ''.join(digits).rstrip('0')
223     if sign: 
224         s = '-' + s
225     elif is_diff:
226         s = "+" + s
227
228     p = s.find('.')
229     s += "0"*( 1 + num_zeros - ( len(s) - p ))
230     s += " "*( 9 - ( len(s) - p ))
231     s = " "*( 5 - ( p )) + s
232     return s
233
234
235 from version import ELECTRUM_VERSION, SEED_VERSION
236 from interface import DEFAULT_SERVERS
237
238
239
240
241 class Wallet:
242     def __init__(self, gui_callback = lambda: None):
243
244         self.electrum_version = ELECTRUM_VERSION
245         self.seed_version = SEED_VERSION
246         self.gui_callback = gui_callback
247
248         self.gap_limit = 5           # configuration
249         self.fee = 100000
250         self.num_zeros = 0
251         self.master_public_key = ''
252
253         # saved fields
254         self.use_encryption = False
255         self.addresses = []          # receiving addresses visible for user
256         self.change_addresses = []   # addresses used as change
257         self.seed = ''               # encrypted
258         self.history = {}
259         self.labels = {}             # labels for addresses and transactions
260         self.aliases = {}            # aliases for addresses
261         self.authorities = {}        # trusted addresses
262         self.frozen_addresses = []
263         
264         self.receipts = {}           # signed URIs
265         self.receipt = None          # next receipt
266         self.addressbook = []        # outgoing addresses, for payments
267
268         # not saved
269         self.tx_history = {}
270
271         self.imported_keys = {}
272         self.remote_url = None
273
274         self.was_updated = True
275         self.blocks = -1
276         self.banner = ''
277
278         # there is a difference between self.up_to_date and self.is_up_to_date()
279         # self.is_up_to_date() returns true when all requests have been answered and processed
280         # self.up_to_date is true when the wallet is synchronized (stronger requirement)
281         self.up_to_date_event = threading.Event()
282         self.up_to_date_event.clear()
283         self.up_to_date = False
284         self.lock = threading.Lock()
285         self.tx_event = threading.Event()
286
287         self.pick_random_server()
288
289
290
291     def pick_random_server(self):
292         self.server = random.choice( DEFAULT_SERVERS )         # random choice when the wallet is created
293
294     def is_up_to_date(self):
295         return self.interface.responses.empty() and not self.interface.unanswered_requests
296
297     def set_server(self, server):
298         # raise an error if the format isnt correct
299         a,b,c = server.split(':')
300         b = int(b)
301         assert c in ['t','h','n']
302         # set the server
303         if server != self.server:
304             self.server = server
305             self.save()
306             self.interface.is_connected = False  # this exits the polling loop
307             self.interface.poke()
308
309     def set_path(self, wallet_path):
310
311         if wallet_path is not None:
312             self.path = wallet_path
313         else:
314             # backward compatibility: look for wallet file in the default data directory
315             if "HOME" in os.environ:
316                 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
317             elif "LOCALAPPDATA" in os.environ:
318                 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
319             elif "APPDATA" in os.environ:
320                 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
321             else:
322                 raise BaseException("No home directory found in environment variables.")
323
324             if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
325             self.path = os.path.join( wallet_dir, 'electrum.dat' )
326
327     def import_key(self, keypair, password):
328         address, key = keypair.split(':')
329         if not self.is_valid(address):
330             raise BaseException('Invalid Bitcoin address')
331         if address in self.all_addresses():
332             raise BaseException('Address already in wallet')
333         b = ASecretToSecret( key )
334         if not b: return False
335         secexp = int( b.encode('hex'), 16)
336         private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
337         # sanity check
338         public_key = private_key.get_verifying_key()
339         if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ):
340             raise BaseException('Address does not match private key')
341         self.imported_keys[address] = self.pw_encode( key, password )
342
343     def new_seed(self, password):
344         seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
345         #self.init_mpk(seed)
346         # encrypt
347         self.seed = self.pw_encode( seed, password )
348
349
350     def init_mpk(self,seed):
351         # public key
352         curve = SECP256k1
353         secexp = self.stretch_key(seed)
354         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
355         self.master_public_key = master_private_key.get_verifying_key().to_string()
356
357     def all_addresses(self):
358         return self.addresses + self.change_addresses + self.imported_keys.keys()
359
360     def is_mine(self, address):
361         return address in self.all_addresses()
362
363     def is_change(self, address):
364         return address in self.change_addresses
365
366     def is_valid(self,addr):
367         ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
368         if not ADDRESS_RE.match(addr): return False
369         try:
370             h = bc_address_to_hash_160(addr)
371         except:
372             return False
373         return addr == hash_160_to_bc_address(h)
374
375     def stretch_key(self,seed):
376         oldseed = seed
377         for i in range(100000):
378             seed = hashlib.sha256(seed + oldseed).digest()
379         return string_to_number( seed )
380
381     def get_sequence(self,n,for_change):
382         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
383
384     def get_private_key_base58(self, address, password):
385         pk = self.get_private_key(address, password)
386         if pk is None: return None
387         return SecretToASecret( pk )
388
389     def get_private_key(self, address, password):
390         """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
391         order = generator_secp256k1.order()
392         
393         if address in self.imported_keys.keys():
394             b = self.pw_decode( self.imported_keys[address], password )
395             if not b: return None
396             b = ASecretToSecret( b )
397             secexp = int( b.encode('hex'), 16)
398         else:
399             if address in self.addresses:
400                 n = self.addresses.index(address)
401                 for_change = False
402             elif address in self.change_addresses:
403                 n = self.change_addresses.index(address)
404                 for_change = True
405             else:
406                 raise BaseException("unknown address")
407             try:
408                 seed = self.pw_decode( self.seed, password)
409             except:
410                 raise BaseException("Invalid password")
411             if not seed: return None
412             secexp = self.stretch_key(seed)
413             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
414
415         pk = number_to_string(secexp,order)
416         return pk
417
418     def msg_magic(self, message):
419         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
420
421     def sign_message(self, address, message, password):
422         private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
423         public_key = private_key.get_verifying_key()
424         signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
425         assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
426         for i in range(4):
427             sig = base64.b64encode( chr(27+i) + signature )
428             try:
429                 self.verify_message( address, sig, message)
430                 return sig
431             except:
432                 continue
433         else:
434             raise BaseException("error: cannot sign message")
435         
436             
437     def verify_message(self, address, signature, message):
438         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
439         from ecdsa import numbertheory, ellipticcurve, util
440         import msqr
441         curve = curve_secp256k1
442         G = generator_secp256k1
443         order = G.order()
444         # extract r,s from signature
445         sig = base64.b64decode(signature)
446         if len(sig) != 65: raise BaseException("Wrong encoding")
447         r,s = util.sigdecode_string(sig[1:], order)
448         recid = ord(sig[0]) - 27
449         # 1.1
450         x = r + (recid/2) * order
451         # 1.3
452         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
453         beta = msqr.modular_sqrt(alpha, curve.p())
454         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
455         # 1.4 the constructor checks that nR is at infinity
456         R = ellipticcurve.Point(curve, x, y, order)
457         # 1.5 compute e from message:
458         h = Hash( self.msg_magic( message ) )
459         e = string_to_number(h)
460         minus_e = -e % order
461         # 1.6 compute Q = r^-1 (sR - eG)
462         inv_r = numbertheory.inverse_mod(r,order)
463         Q = inv_r * ( s * R + minus_e * G )
464         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
465         # check that Q is the public key
466         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
467         # check that we get the original signing address
468         addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
469         # print addr
470         if address != addr:
471             print "bad signature"
472             raise BaseException("Bad signature")
473     
474
475     def create_new_address(self, for_change):
476         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
477         curve = SECP256k1
478         n = len(self.change_addresses) if for_change else len(self.addresses)
479         z = self.get_sequence(n,for_change)
480         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
481         pubkey_point = master_public_key.pubkey.point + z*curve.generator
482         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
483         address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
484         if for_change:
485             self.change_addresses.append(address)
486         else:
487             self.addresses.append(address)
488
489         self.history[address] = []
490         print address
491         return address
492
493
494
495     def synchronize(self):
496         if not self.master_public_key:
497             return []
498
499         new_addresses = []
500         while True:
501             if self.change_addresses == []:
502                 new_addresses.append( self.create_new_address(True) )
503                 continue
504             a = self.change_addresses[-1]
505             if self.history.get(a):
506                 new_addresses.append( self.create_new_address(True) )
507             else:
508                 break
509
510         n = self.gap_limit
511         while True:
512             if len(self.addresses) < n:
513                 new_addresses.append( self.create_new_address(False) )
514                 continue
515             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
516                 break
517             else:
518                 new_addresses.append( self.create_new_address(False) )
519
520         if self.remote_url:
521             num = self.get_remote_number()
522             while len(self.addresses)<num:
523                 new_addresses.append( self.create_new_address(False) )
524
525         return new_addresses
526
527
528     def get_remote_number(self):
529         import jsonrpclib
530         server = jsonrpclib.Server(self.remote_url)
531         out = server.getnum()
532         return out
533
534     def get_remote_mpk(self):
535         import jsonrpclib
536         server = jsonrpclib.Server(self.remote_url)
537         out = server.getkey()
538         return out
539
540     def is_found(self):
541         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
542
543     def fill_addressbook(self):
544         for tx in self.tx_history.values():
545             if tx['value']<0:
546                 for i in tx['outputs']:
547                     if not self.is_mine(i) and i not in self.addressbook:
548                         self.addressbook.append(i)
549         # redo labels
550         self.update_tx_labels()
551
552
553     def save(self):
554         s = {
555             'seed_version':self.seed_version,
556             'use_encryption':self.use_encryption,
557             'master_public_key': self.master_public_key.encode('hex'),
558             'fee':self.fee,
559             'server':self.server,
560             'seed':self.seed,
561             'addresses':self.addresses,
562             'change_addresses':self.change_addresses,
563             'history':self.history, 
564             'labels':self.labels,
565             'contacts':self.addressbook,
566             'imported_keys':self.imported_keys,
567             'aliases':self.aliases,
568             'authorities':self.authorities,
569             'receipts':self.receipts,
570             'num_zeros':self.num_zeros,
571             'frozen_addresses':self.frozen_addresses,
572             }
573         f = open(self.path,"w")
574         f.write( repr(s) )
575         f.close()
576
577     def read(self):
578         import interface
579
580         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
581         self.file_exists = False
582         try:
583             f = open(self.path,"r")
584             data = f.read()
585             f.close()
586         except:
587             return
588         data = interface.old_to_new(data)
589         try:
590             d = ast.literal_eval( data )
591             self.seed_version = d.get('seed_version')
592             self.master_public_key = d.get('master_public_key').decode('hex')
593             self.use_encryption = d.get('use_encryption')
594             self.fee = int( d.get('fee') )
595             self.seed = d.get('seed')
596             self.server = d.get('server')
597             #blocks = d.get('blocks')
598             self.addresses = d.get('addresses')
599             self.change_addresses = d.get('change_addresses')
600             self.history = d.get('history')
601             self.labels = d.get('labels')
602             self.addressbook = d.get('contacts')
603             self.imported_keys = d.get('imported_keys',{})
604             self.aliases = d.get('aliases',{})
605             self.authorities = d.get('authorities',{})
606             self.receipts = d.get('receipts',{})
607             self.num_zeros = d.get('num_zeros',0)
608             self.frozen_addresses = d.get('frozen_addresses',[])
609         except:
610             raise BaseException("cannot read wallet file")
611
612         self.update_tx_history()
613
614         if self.seed_version != SEED_VERSION:
615             raise BaseException(upgrade_msg)
616
617         if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
618
619         self.file_exists = True
620
621
622         
623
624     def get_addr_balance(self, addr):
625         assert self.is_mine(addr)
626         h = self.history.get(addr,[])
627         c = u = 0
628         for item in h:
629             v = item['value']
630             if item['height']:
631                 c += v
632             else:
633                 u += v
634         return c, u
635
636     def get_balance(self):
637         conf = unconf = 0
638         for addr in self.all_addresses(): 
639             c, u = self.get_addr_balance(addr)
640             conf += c
641             unconf += u
642         return conf, unconf
643
644
645     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
646         """ todo: minimize tx size """
647         total = 0
648         fee = self.fee if fixed_fee is None else fixed_fee
649
650         coins = []
651         domain = [from_addr] if from_addr else self.all_addresses()
652         for i in self.frozen_addresses:
653             if i in domain: domain.remove(i)
654
655         for addr in domain:
656             h = self.history.get(addr)
657             if h is None: continue
658             for item in h:
659                 if item.get('raw_output_script'):
660                     coins.append( (addr,item))
661
662         coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
663         inputs = []
664         for c in coins: 
665             addr, item = c
666             v = item.get('value')
667             total += v
668             inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
669             fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
670             if total >= amount + fee: break
671         else:
672             #print "not enough funds: %d %d"%(total, fee)
673             inputs = []
674         return inputs, total, fee
675
676     def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
677         outputs = [ (to_addr, amount) ]
678         change_amount = total - ( amount + fee )
679         if change_amount != 0:
680             # normally, the update thread should ensure that the last change address is unused
681             if not change_addr:
682                 change_addr = self.change_addresses[-1]
683             outputs.append( ( change_addr,  change_amount) )
684         return outputs
685
686     def sign_inputs( self, inputs, outputs, password ):
687         s_inputs = []
688         for i in range(len(inputs)):
689             addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
690             private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
691             public_key = private_key.get_verifying_key()
692             pubkey = public_key.to_string()
693             tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
694             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
695             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
696             s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
697         return s_inputs
698
699     def pw_encode(self, s, password):
700         if password:
701             secret = Hash(password)
702             return EncodeAES(secret, s)
703         else:
704             return s
705
706     def pw_decode(self, s, password):
707         if password is not None:
708             secret = Hash(password)
709             d = DecodeAES(secret, s)
710             if s == self.seed:
711                 try:
712                     d.decode('hex')
713                 except:
714                     raise BaseException("Invalid password")
715             return d
716         else:
717             return s
718
719     def get_status(self, address):
720         h = self.history.get(address)
721         if not h:
722             status = None
723         else:
724             lastpoint = h[-1]
725             status = lastpoint['block_hash']
726             if status == 'mempool': 
727                 status = status + ':%d'% len(h)
728         return status
729
730     def receive_status_callback(self, addr, status):
731         with self.lock:
732             if self.get_status(addr) != status:
733                 #print "updating status for", addr, status
734                 self.interface.get_history(addr)
735
736     def receive_history_callback(self, addr, data): 
737         #print "updating history for", addr
738         with self.lock:
739             self.history[addr] = data
740             self.update_tx_history()
741             self.save()
742
743     def get_tx_history(self):
744         lines = self.tx_history.values()
745         lines = sorted(lines, key=operator.itemgetter("timestamp"))
746         return lines
747
748     def update_tx_history(self):
749         self.tx_history= {}
750         for addr in self.all_addresses():
751             h = self.history.get(addr)
752             if h is None: continue
753             for tx in h:
754                 tx_hash = tx['tx_hash']
755                 line = self.tx_history.get(tx_hash)
756                 if not line:
757                     self.tx_history[tx_hash] = copy.copy(tx)
758                     line = self.tx_history.get(tx_hash)
759                 else:
760                     line['value'] += tx['value']
761                 if line['height'] == 0:
762                     line['timestamp'] = 1e12
763         self.update_tx_labels()
764
765     def update_tx_labels(self):
766         for tx in self.tx_history.values():
767             default_label = ''
768             if tx['value']<0:
769                 for o_addr in tx['outputs']:
770                     if not self.is_change(o_addr):
771                         dest_label = self.labels.get(o_addr)
772                         if dest_label:
773                             default_label = 'to: ' + dest_label
774                         else:
775                             default_label = 'to: ' + o_addr
776             else:
777                 for o_addr in tx['outputs']:
778                     if self.is_mine(o_addr) and not self.is_change(o_addr):
779                         break
780                 else:
781                     for o_addr in tx['outputs']:
782                         if self.is_mine(o_addr):
783                             break
784                     else:
785                         o_addr = None
786
787                 if o_addr:
788                     dest_label = self.labels.get(o_addr)
789                     if dest_label:
790                         default_label = 'at: ' + dest_label
791                     else:
792                         default_label = 'at: ' + o_addr
793
794             tx['default_label'] = default_label
795
796     def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
797         if not self.is_valid(to_address):
798             raise BaseException("Invalid address")
799         inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
800         if not inputs:
801             raise BaseException("Not enough funds")
802         outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
803         s_inputs = self.sign_inputs( inputs, outputs, password )
804
805         tx = filter( raw_tx( s_inputs, outputs ) )
806         if to_address not in self.addressbook:
807             self.addressbook.append(to_address)
808         if label: 
809             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
810             self.labels[tx_hash] = label
811
812         return tx
813
814     def sendtx(self, tx):
815         tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
816         self.tx_event.clear()
817         self.interface.send([('blockchain.transaction.broadcast', [tx])])
818         self.tx_event.wait()
819         out = self.tx_result 
820         if out != tx_hash:
821             return False, "error: " + out
822         if self.receipt:
823             self.receipts[tx_hash] = self.receipt
824             self.receipt = None
825         return True, out
826
827
828     def read_alias(self, alias):
829         # this might not be the right place for this function.
830         import urllib
831
832         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
833         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
834         if m1:
835             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
836         elif m2:
837             url = 'http://' + alias + '/bitcoin.id'
838         else:
839             return ''
840         try:
841             lines = urllib.urlopen(url).readlines()
842         except:
843             return ''
844
845         # line 0
846         line = lines[0].strip().split(':')
847         if len(line) == 1:
848             auth_name = None
849             target = signing_addr = line[0]
850         else:
851             target, auth_name, signing_addr, signature = line
852             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
853             print msg, signature
854             self.verify_message(signing_addr, signature, msg)
855         
856         # other lines are signed updates
857         for line in lines[1:]:
858             line = line.strip()
859             if not line: continue
860             line = line.split(':')
861             previous = target
862             print repr(line)
863             target, signature = line
864             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
865
866         if not self.is_valid(target):
867             raise BaseException("Invalid bitcoin address")
868
869         return target, signing_addr, auth_name
870
871     def update_password(self, seed, old_password, new_password):
872         if new_password == '': new_password = None
873         self.use_encryption = (new_password != None)
874         self.seed = self.pw_encode( seed, new_password)
875         for k in self.imported_keys.keys():
876             a = self.imported_keys[k]
877             b = self.pw_decode(a, old_password)
878             c = self.pw_encode(b, new_password)
879             self.imported_keys[k] = c
880         self.save()
881
882     def get_alias(self, alias, interactive = False, show_message=None, question = None):
883         try:
884             target, signing_address, auth_name = self.read_alias(alias)
885         except BaseException, e:
886             # raise exception if verify fails (verify the chain)
887             if interactive:
888                 show_message("Alias error: " + str(e))
889             return
890
891         print target, signing_address, auth_name
892
893         if auth_name is None:
894             a = self.aliases.get(alias)
895             if not a:
896                 msg = "Warning: the alias '%s' is self-signed.\nThe signing address is %s.\n\nDo you want to add this alias to your list of contacts?"%(alias,signing_address)
897                 if interactive and question( msg ):
898                     self.aliases[alias] = (signing_address, target)
899                 else:
900                     target = None
901             else:
902                 if signing_address != a[0]:
903                     msg = "Warning: the key of alias '%s' has changed since your last visit! It is possible that someone is trying to do something nasty!!!\nDo you accept to change your trusted key?"%alias
904                     if interactive and question( msg ):
905                         self.aliases[alias] = (signing_address, target)
906                     else:
907                         target = None
908         else:
909             if signing_address not in self.authorities.keys():
910                 msg = "The alias: '%s' links to %s\n\nWarning: this alias was signed by an unknown key.\nSigning authority: %s\nSigning address: %s\n\nDo you want to add this key to your list of trusted keys?"%(alias,target,auth_name,signing_address)
911                 if interactive and question( msg ):
912                     self.authorities[signing_address] = auth_name
913                 else:
914                     target = None
915
916         if target:
917             self.aliases[alias] = (signing_address, target)
918             
919         return target
920
921
922     def parse_url(self, url, show_message, question):
923         o = url[8:].split('?')
924         address = o[0]
925         if len(o)>1:
926             params = o[1].split('&')
927         else:
928             params = []
929
930         amount = label = message = signature = identity = ''
931         for p in params:
932             k,v = p.split('=')
933             uv = urldecode(v)
934             if k == 'amount': amount = uv
935             elif k == 'message': message = uv
936             elif k == 'label': label = uv
937             elif k == 'signature':
938                 identity, signature = uv.split(':')
939                 url = url.replace('&%s=%s'%(k,v),'')
940             else: 
941                 print k,v
942
943         if signature:
944             if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
945                 signing_address = self.get_alias(identity, True, show_message, question)
946             elif self.is_valid(identity):
947                 signing_address = identity
948             else:
949                 signing_address = None
950             if not signing_address:
951                 return
952             try:
953                 self.verify_message(signing_address, signature, url )
954                 self.receipt = (signing_address, signature, url)
955             except:
956                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
957                 address = amount = label = identity = message = ''
958
959         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
960             payto_address = self.get_alias(address, True, show_message, question)
961             if payto_address:
962                 address = address + ' <' + payto_address + '>'
963
964         return address, amount, label, message, signature, identity, url
965
966
967     def update(self):
968         self.interface.poke()
969         self.up_to_date_event.wait(10000000000)
970
971
972     def start_session(self, interface):
973         self.interface = interface
974         self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
975         self.interface.subscribe(self.all_addresses())
976
977
978
979