do not use deprecated BaseException.message
[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 = str( Decimal(x) /100000000 )
217     if is_diff and x>0:
218         s = "+" + s
219     if not '.' in s: s += '.'
220     p = s.find('.')
221     s += "0"*( 1 + num_zeros - ( len(s) - p ))
222     s += " "*( 9 - ( len(s) - p ))
223     s = " "*( 5 - ( p )) + s
224     return s
225
226
227 from version import ELECTRUM_VERSION, SEED_VERSION
228 from interface import DEFAULT_SERVERS
229
230
231
232
233 class Wallet:
234     def __init__(self, gui_callback = lambda: None):
235
236         self.electrum_version = ELECTRUM_VERSION
237         self.seed_version = SEED_VERSION
238         self.gui_callback = gui_callback
239
240         self.gap_limit = 5           # configuration
241         self.fee = 100000
242         self.num_zeros = 0
243         self.master_public_key = ''
244
245         # saved fields
246         self.use_encryption = False
247         self.addresses = []          # receiving addresses visible for user
248         self.change_addresses = []   # addresses used as change
249         self.seed = ''               # encrypted
250         self.history = {}
251         self.labels = {}             # labels for addresses and transactions
252         self.aliases = {}            # aliases for addresses
253         self.authorities = {}        # trusted addresses
254         self.frozen_addresses = []
255         
256         self.receipts = {}           # signed URIs
257         self.receipt = None          # next receipt
258         self.addressbook = []        # outgoing addresses, for payments
259
260         # not saved
261         self.tx_history = {}
262
263         self.imported_keys = {}
264         self.remote_url = None
265
266         self.was_updated = True
267         self.blocks = -1
268         self.banner = ''
269
270         # there is a difference between self.up_to_date and self.is_up_to_date()
271         # self.is_up_to_date() returns true when all requests have been answered and processed
272         # self.up_to_date is true when the wallet is synchronized (stronger requirement)
273         self.up_to_date_event = threading.Event()
274         self.up_to_date_event.clear()
275         self.up_to_date = False
276         self.lock = threading.Lock()
277         self.tx_event = threading.Event()
278
279         self.pick_random_server()
280
281
282
283     def pick_random_server(self):
284         self.server = random.choice( DEFAULT_SERVERS )         # random choice when the wallet is created
285
286     def is_up_to_date(self):
287         return self.interface.responses.empty() and not self.interface.unanswered_requests
288
289     def set_server(self, server):
290         # raise an error if the format isnt correct
291         a,b,c = server.split(':')
292         b = int(b)
293         assert c in ['t','h','n']
294         # set the server
295         if server != self.server:
296             self.server = server
297             self.save()
298             self.interface.is_connected = False  # this exits the polling loop
299             self.interface.poke()
300
301     def set_path(self, wallet_path):
302
303         if wallet_path is not None:
304             self.path = wallet_path
305         else:
306             # backward compatibility: look for wallet file in the default data directory
307             if "HOME" in os.environ:
308                 wallet_dir = os.path.join( os.environ["HOME"], '.electrum')
309             elif "LOCALAPPDATA" in os.environ:
310                 wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' )
311             elif "APPDATA" in os.environ:
312                 wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' )
313             else:
314                 raise BaseException("No home directory found in environment variables.")
315
316             if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir )
317             self.path = os.path.join( wallet_dir, 'electrum.dat' )
318
319     def import_key(self, keypair, password):
320         address, key = keypair.split(':')
321         if not self.is_valid(address): return False
322         if address in self.all_addresses(): return False
323         b = ASecretToSecret( key )
324         if not b: return False
325         secexp = int( b.encode('hex'), 16)
326         private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 )
327         # sanity check
328         public_key = private_key.get_verifying_key()
329         if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False
330         self.imported_keys[address] = self.pw_encode( key, password )
331         return True
332
333     def new_seed(self, password):
334         seed = "%032x"%ecdsa.util.randrange( pow(2,128) )
335         #self.init_mpk(seed)
336         # encrypt
337         self.seed = self.pw_encode( seed, password )
338
339
340     def init_mpk(self,seed):
341         # public key
342         curve = SECP256k1
343         secexp = self.stretch_key(seed)
344         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
345         self.master_public_key = master_private_key.get_verifying_key().to_string()
346
347     def all_addresses(self):
348         return self.addresses + self.change_addresses + self.imported_keys.keys()
349
350     def is_mine(self, address):
351         return address in self.all_addresses()
352
353     def is_change(self, address):
354         return address in self.change_addresses
355
356     def is_valid(self,addr):
357         ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
358         if not ADDRESS_RE.match(addr): return False
359         try:
360             h = bc_address_to_hash_160(addr)
361         except:
362             return False
363         return addr == hash_160_to_bc_address(h)
364
365     def stretch_key(self,seed):
366         oldseed = seed
367         for i in range(100000):
368             seed = hashlib.sha256(seed + oldseed).digest()
369         return string_to_number( seed )
370
371     def get_sequence(self,n,for_change):
372         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) )
373
374     def get_private_key_base58(self, address, password):
375         pk = self.get_private_key(address, password)
376         if pk is None: return None
377         return SecretToASecret( pk )
378
379     def get_private_key(self, address, password):
380         """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
381         order = generator_secp256k1.order()
382         
383         if address in self.imported_keys.keys():
384             b = self.pw_decode( self.imported_keys[address], password )
385             b = ASecretToSecret( b )
386             secexp = int( b.encode('hex'), 16)
387         else:
388             if address in self.addresses:
389                 n = self.addresses.index(address)
390                 for_change = False
391             elif address in self.change_addresses:
392                 n = self.change_addresses.index(address)
393                 for_change = True
394             else:
395                 raise BaseException("unknown address")
396             if not self.seed: return None
397             try:
398                 seed = self.pw_decode( self.seed, password)
399             except:
400                 raise BaseException("Invalid password")
401             secexp = self.stretch_key(seed)
402             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
403
404         pk = number_to_string(secexp,order)
405         return pk
406
407     def msg_magic(self, message):
408         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
409
410     def sign_message(self, address, message, password):
411         private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
412         public_key = private_key.get_verifying_key()
413         signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
414         assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
415         for i in range(4):
416             sig = base64.b64encode( chr(27+i) + signature )
417             try:
418                 self.verify_message( address, sig, message)
419                 return sig
420             except:
421                 continue
422         else:
423             raise BaseException("error: cannot sign message")
424         
425             
426     def verify_message(self, address, signature, message):
427         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
428         from ecdsa import numbertheory, ellipticcurve, util
429         import msqr
430         curve = curve_secp256k1
431         G = generator_secp256k1
432         order = G.order()
433         # extract r,s from signature
434         sig = base64.b64decode(signature)
435         if len(sig) != 65: raise BaseException("Wrong encoding")
436         r,s = util.sigdecode_string(sig[1:], order)
437         recid = ord(sig[0]) - 27
438         # 1.1
439         x = r + (recid/2) * order
440         # 1.3
441         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
442         beta = msqr.modular_sqrt(alpha, curve.p())
443         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
444         # 1.4 the constructor checks that nR is at infinity
445         R = ellipticcurve.Point(curve, x, y, order)
446         # 1.5 compute e from message:
447         h = Hash( self.msg_magic( message ) )
448         e = string_to_number(h)
449         minus_e = -e % order
450         # 1.6 compute Q = r^-1 (sR - eG)
451         inv_r = numbertheory.inverse_mod(r,order)
452         Q = inv_r * ( s * R + minus_e * G )
453         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
454         # check that Q is the public key
455         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
456         # check that we get the original signing address
457         addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
458         # print addr
459         if address != addr:
460             print "bad signature"
461             raise BaseException("Bad signature")
462     
463
464     def create_new_address(self, for_change):
465         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
466         curve = SECP256k1
467         n = len(self.change_addresses) if for_change else len(self.addresses)
468         z = self.get_sequence(n,for_change)
469         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
470         pubkey_point = master_public_key.pubkey.point + z*curve.generator
471         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
472         address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
473         if for_change:
474             self.change_addresses.append(address)
475         else:
476             self.addresses.append(address)
477
478         self.history[address] = []
479         print address
480         return address
481
482
483
484     def synchronize(self):
485         if not self.master_public_key:
486             return []
487
488         new_addresses = []
489         while True:
490             if self.change_addresses == []:
491                 new_addresses.append( self.create_new_address(True) )
492                 continue
493             a = self.change_addresses[-1]
494             if self.history.get(a):
495                 new_addresses.append( self.create_new_address(True) )
496             else:
497                 break
498
499         n = self.gap_limit
500         while True:
501             if len(self.addresses) < n:
502                 new_addresses.append( self.create_new_address(False) )
503                 continue
504             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
505                 break
506             else:
507                 new_addresses.append( self.create_new_address(False) )
508
509         if self.remote_url:
510             num = self.get_remote_number()
511             while len(self.addresses)<num:
512                 new_addresses.append( self.create_new_address(False) )
513
514         return new_addresses
515
516
517     def get_remote_number(self):
518         import jsonrpclib
519         server = jsonrpclib.Server(self.remote_url)
520         out = server.getnum()
521         return out
522
523     def get_remote_mpk(self):
524         import jsonrpclib
525         server = jsonrpclib.Server(self.remote_url)
526         out = server.getkey()
527         return out
528
529     def is_found(self):
530         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
531
532     def fill_addressbook(self):
533         for tx in self.tx_history.values():
534             if tx['value']<0:
535                 for i in tx['outputs']:
536                     if not self.is_mine(i) and i not in self.addressbook:
537                         self.addressbook.append(i)
538         # redo labels
539         self.update_tx_labels()
540
541
542     def save(self):
543         s = {
544             'seed_version':self.seed_version,
545             'use_encryption':self.use_encryption,
546             'master_public_key': self.master_public_key.encode('hex'),
547             'fee':self.fee,
548             'server':self.server,
549             'seed':self.seed,
550             'addresses':self.addresses,
551             'change_addresses':self.change_addresses,
552             'history':self.history, 
553             'labels':self.labels,
554             'contacts':self.addressbook,
555             'imported_keys':self.imported_keys,
556             'aliases':self.aliases,
557             'authorities':self.authorities,
558             'receipts':self.receipts,
559             'num_zeros':self.num_zeros,
560             'frozen_addresses':self.frozen_addresses,
561             }
562         f = open(self.path,"w")
563         f.write( repr(s) )
564         f.close()
565
566     def read(self):
567         import interface
568
569         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
570         self.file_exists = False
571         try:
572             f = open(self.path,"r")
573             data = f.read()
574             f.close()
575         except:
576             return
577         data = interface.old_to_new(data)
578         try:
579             d = ast.literal_eval( data )
580             self.seed_version = d.get('seed_version')
581             self.master_public_key = d.get('master_public_key').decode('hex')
582             self.use_encryption = d.get('use_encryption')
583             self.fee = int( d.get('fee') )
584             self.seed = d.get('seed')
585             self.server = d.get('server')
586             #blocks = d.get('blocks')
587             self.addresses = d.get('addresses')
588             self.change_addresses = d.get('change_addresses')
589             self.history = d.get('history')
590             self.labels = d.get('labels')
591             self.addressbook = d.get('contacts')
592             self.imported_keys = d.get('imported_keys',{})
593             self.aliases = d.get('aliases',{})
594             self.authorities = d.get('authorities',{})
595             self.receipts = d.get('receipts',{})
596             self.num_zeros = d.get('num_zeros',0)
597             self.frozen_addresses = d.get('frozen_addresses',[])
598         except:
599             raise BaseException("cannot read wallet file")
600
601         self.update_tx_history()
602
603         if self.seed_version != SEED_VERSION:
604             raise BaseException(upgrade_msg)
605
606         if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
607
608         self.file_exists = True
609
610
611         
612
613     def get_addr_balance(self, addr):
614         assert self.is_mine(addr)
615         h = self.history.get(addr,[])
616         c = u = 0
617         for item in h:
618             v = item['value']
619             if item['height']:
620                 c += v
621             else:
622                 u += v
623         return c, u
624
625     def get_balance(self):
626         conf = unconf = 0
627         for addr in self.all_addresses(): 
628             c, u = self.get_addr_balance(addr)
629             conf += c
630             unconf += u
631         return conf, unconf
632
633
634     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
635         """ todo: minimize tx size """
636         total = 0
637         fee = self.fee if fixed_fee is None else fixed_fee
638
639         coins = []
640         domain = [from_addr] if from_addr else self.all_addresses()
641         for i in self.frozen_addresses:
642             if i in domain: domain.remove(i)
643
644         for addr in domain:
645             h = self.history.get(addr)
646             if h is None: continue
647             for item in h:
648                 if item.get('raw_output_script'):
649                     coins.append( (addr,item))
650
651         coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
652         inputs = []
653         for c in coins: 
654             addr, item = c
655             v = item.get('value')
656             total += v
657             inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
658             fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
659             if total >= amount + fee: break
660         else:
661             #print "not enough funds: %d %d"%(total, fee)
662             inputs = []
663         return inputs, total, fee
664
665     def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
666         outputs = [ (to_addr, amount) ]
667         change_amount = total - ( amount + fee )
668         if change_amount != 0:
669             # normally, the update thread should ensure that the last change address is unused
670             if not change_addr:
671                 change_addr = self.change_addresses[-1]
672             outputs.append( ( change_addr,  change_amount) )
673         return outputs
674
675     def sign_inputs( self, inputs, outputs, password ):
676         s_inputs = []
677         for i in range(len(inputs)):
678             addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
679             private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
680             public_key = private_key.get_verifying_key()
681             pubkey = public_key.to_string()
682             tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
683             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
684             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
685             s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
686         return s_inputs
687
688     def pw_encode(self, s, password):
689         if password:
690             secret = Hash(password)
691             return EncodeAES(secret, s)
692         else:
693             return s
694
695     def pw_decode(self, s, password):
696         if password is not None:
697             secret = Hash(password)
698             d = DecodeAES(secret, s)
699             if s == self.seed:
700                 try:
701                     d.decode('hex')
702                 except:
703                     raise BaseException("Invalid password")
704             return d
705         else:
706             return s
707
708     def get_status(self, address):
709         h = self.history.get(address)
710         if not h:
711             status = None
712         else:
713             lastpoint = h[-1]
714             status = lastpoint['block_hash']
715             if status == 'mempool': 
716                 status = status + ':%d'% len(h)
717         return status
718
719     def receive_status_callback(self, addr, status):
720         with self.lock:
721             if self.get_status(addr) != status:
722                 #print "updating status for", addr, status
723                 self.interface.get_history(addr)
724
725     def receive_history_callback(self, addr, data): 
726         #print "updating history for", addr
727         with self.lock:
728             self.history[addr] = data
729             self.update_tx_history()
730             self.save()
731
732     def get_tx_history(self):
733         lines = self.tx_history.values()
734         lines = sorted(lines, key=operator.itemgetter("timestamp"))
735         return lines
736
737     def update_tx_history(self):
738         self.tx_history= {}
739         for addr in self.all_addresses():
740             h = self.history.get(addr)
741             if h is None: continue
742             for tx in h:
743                 tx_hash = tx['tx_hash']
744                 line = self.tx_history.get(tx_hash)
745                 if not line:
746                     self.tx_history[tx_hash] = copy.copy(tx)
747                     line = self.tx_history.get(tx_hash)
748                 else:
749                     line['value'] += tx['value']
750                 if line['height'] == 0:
751                     line['timestamp'] = 1e12
752         self.update_tx_labels()
753
754     def update_tx_labels(self):
755         for tx in self.tx_history.values():
756             default_label = ''
757             if tx['value']<0:
758                 for o_addr in tx['outputs']:
759                     if not self.is_change(o_addr):
760                         dest_label = self.labels.get(o_addr)
761                         if dest_label:
762                             default_label = 'to: ' + dest_label
763                         else:
764                             default_label = 'to: ' + o_addr
765             else:
766                 for o_addr in tx['outputs']:
767                     if self.is_mine(o_addr) and not self.is_change(o_addr):
768                         dest_label = self.labels.get(o_addr)
769                         if dest_label:
770                             default_label = 'at: ' + dest_label
771                         else:
772                             default_label = 'at: ' + o_addr
773             tx['default_label'] = default_label
774
775     def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
776         if not self.is_valid(to_address):
777             raise BaseException("Invalid address")
778         inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
779         if not inputs:
780             raise BaseException("Not enough funds")
781         outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
782         s_inputs = self.sign_inputs( inputs, outputs, password )
783
784         tx = filter( raw_tx( s_inputs, outputs ) )
785         if to_address not in self.addressbook:
786             self.addressbook.append(to_address)
787         if label: 
788             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
789             self.labels[tx_hash] = label
790
791         return tx
792
793     def sendtx(self, tx):
794         tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
795         self.tx_event.clear()
796         self.interface.send([('blockchain.transaction.broadcast', [tx])])
797         self.tx_event.wait()
798         out = self.tx_result 
799         if out != tx_hash:
800             return False, "error: " + out
801         if self.receipt:
802             self.receipts[tx_hash] = self.receipt
803             self.receipt = None
804         return True, out
805
806
807     def read_alias(self, alias):
808         # this might not be the right place for this function.
809         import urllib
810
811         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
812         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
813         if m1:
814             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
815         elif m2:
816             url = 'http://' + alias + '/bitcoin.id'
817         else:
818             return ''
819         try:
820             lines = urllib.urlopen(url).readlines()
821         except:
822             return ''
823
824         # line 0
825         line = lines[0].strip().split(':')
826         if len(line) == 1:
827             auth_name = None
828             target = signing_addr = line[0]
829         else:
830             target, auth_name, signing_addr, signature = line
831             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
832             print msg, signature
833             self.verify_message(signing_addr, signature, msg)
834         
835         # other lines are signed updates
836         for line in lines[1:]:
837             line = line.strip()
838             if not line: continue
839             line = line.split(':')
840             previous = target
841             print repr(line)
842             target, signature = line
843             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
844
845         if not self.is_valid(target):
846             raise BaseException("Invalid bitcoin address")
847
848         return target, signing_addr, auth_name
849
850     def update_password(self, seed, new_password):
851         if new_password == '': new_password = None
852         self.use_encryption = (new_password != None)
853         self.seed = self.pw_encode( seed, new_password)
854         for k in self.imported_keys.keys():
855             a = self.imported_keys[k]
856             b = self.pw_decode(a, password)
857             c = self.pw_encode(b, new_password)
858             self.imported_keys[k] = c
859         self.save()
860
861     def get_alias(self, alias, interactive = False, show_message=None, question = None):
862         try:
863             target, signing_address, auth_name = self.read_alias(alias)
864         except BaseException, e:
865             # raise exception if verify fails (verify the chain)
866             if interactive:
867                 show_message("Alias error: " + str(e))
868             return
869
870         print target, signing_address, auth_name
871
872         if auth_name is None:
873             a = self.aliases.get(alias)
874             if not a:
875                 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)
876                 if interactive and question( msg ):
877                     self.aliases[alias] = (signing_address, target)
878                 else:
879                     target = None
880             else:
881                 if signing_address != a[0]:
882                     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
883                     if interactive and question( msg ):
884                         self.aliases[alias] = (signing_address, target)
885                     else:
886                         target = None
887         else:
888             if signing_address not in self.authorities.keys():
889                 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)
890                 if interactive and question( msg ):
891                     self.authorities[signing_address] = auth_name
892                 else:
893                     target = None
894
895         if target:
896             self.aliases[alias] = (signing_address, target)
897             
898         return target
899
900
901     def parse_url(self, url, show_message, question):
902         o = url[8:].split('?')
903         address = o[0]
904         if len(o)>1:
905             params = o[1].split('&')
906         else:
907             params = []
908
909         amount = label = message = signature = identity = ''
910         for p in params:
911             k,v = p.split('=')
912             uv = urldecode(v)
913             if k == 'amount': amount = uv
914             elif k == 'message': message = uv
915             elif k == 'label': label = uv
916             elif k == 'signature':
917                 identity, signature = uv.split(':')
918                 url = url.replace('&%s=%s'%(k,v),'')
919             else: 
920                 print k,v
921
922         if signature:
923             if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
924                 signing_address = self.get_alias(identity, True, show_message, question)
925             elif self.is_valid(identity):
926                 signing_address = identity
927             else:
928                 signing_address = None
929             if not signing_address:
930                 return
931             try:
932                 self.verify_message(signing_address, signature, url )
933                 self.receipt = (signing_address, signature, url)
934             except:
935                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
936                 address = amount = label = identity = message = ''
937
938         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
939             payto_address = self.get_alias(address, True, show_message, question)
940             if payto_address:
941                 address = address + ' <' + payto_address + '>'
942
943         return address, amount, label, message, signature, identity, url
944
945
946     def update(self):
947         self.interface.poke()
948         self.up_to_date_event.wait()
949
950
951     def start_session(self, interface):
952         self.interface = interface
953         self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
954         self.interface.subscribe(self.all_addresses())
955
956
957
958