handle imported keys as well with deseed and reseed
[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             if not b: return None
386             b = ASecretToSecret( b )
387             secexp = int( b.encode('hex'), 16)
388         else:
389             if address in self.addresses:
390                 n = self.addresses.index(address)
391                 for_change = False
392             elif address in self.change_addresses:
393                 n = self.change_addresses.index(address)
394                 for_change = True
395             else:
396                 raise BaseException("unknown address")
397             try:
398                 seed = self.pw_decode( self.seed, password)
399             except:
400                 raise BaseException("Invalid password")
401             if not seed: return None
402             secexp = self.stretch_key(seed)
403             secexp = ( secexp + self.get_sequence(n,for_change) ) % order
404
405         pk = number_to_string(secexp,order)
406         return pk
407
408     def msg_magic(self, message):
409         return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
410
411     def sign_message(self, address, message, password):
412         private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 )
413         public_key = private_key.get_verifying_key()
414         signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string )
415         assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string)
416         for i in range(4):
417             sig = base64.b64encode( chr(27+i) + signature )
418             try:
419                 self.verify_message( address, sig, message)
420                 return sig
421             except:
422                 continue
423         else:
424             raise BaseException("error: cannot sign message")
425         
426             
427     def verify_message(self, address, signature, message):
428         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
429         from ecdsa import numbertheory, ellipticcurve, util
430         import msqr
431         curve = curve_secp256k1
432         G = generator_secp256k1
433         order = G.order()
434         # extract r,s from signature
435         sig = base64.b64decode(signature)
436         if len(sig) != 65: raise BaseException("Wrong encoding")
437         r,s = util.sigdecode_string(sig[1:], order)
438         recid = ord(sig[0]) - 27
439         # 1.1
440         x = r + (recid/2) * order
441         # 1.3
442         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
443         beta = msqr.modular_sqrt(alpha, curve.p())
444         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
445         # 1.4 the constructor checks that nR is at infinity
446         R = ellipticcurve.Point(curve, x, y, order)
447         # 1.5 compute e from message:
448         h = Hash( self.msg_magic( message ) )
449         e = string_to_number(h)
450         minus_e = -e % order
451         # 1.6 compute Q = r^-1 (sR - eG)
452         inv_r = numbertheory.inverse_mod(r,order)
453         Q = inv_r * ( s * R + minus_e * G )
454         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
455         # check that Q is the public key
456         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
457         # check that we get the original signing address
458         addr = public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() )
459         # print addr
460         if address != addr:
461             print "bad signature"
462             raise BaseException("Bad signature")
463     
464
465     def create_new_address(self, for_change):
466         """   Publickey(type,n) = Master_public_key + H(n|S|type)*point  """
467         curve = SECP256k1
468         n = len(self.change_addresses) if for_change else len(self.addresses)
469         z = self.get_sequence(n,for_change)
470         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 )
471         pubkey_point = master_public_key.pubkey.point + z*curve.generator
472         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
473         address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() )
474         if for_change:
475             self.change_addresses.append(address)
476         else:
477             self.addresses.append(address)
478
479         self.history[address] = []
480         print address
481         return address
482
483
484
485     def synchronize(self):
486         if not self.master_public_key:
487             return []
488
489         new_addresses = []
490         while True:
491             if self.change_addresses == []:
492                 new_addresses.append( self.create_new_address(True) )
493                 continue
494             a = self.change_addresses[-1]
495             if self.history.get(a):
496                 new_addresses.append( self.create_new_address(True) )
497             else:
498                 break
499
500         n = self.gap_limit
501         while True:
502             if len(self.addresses) < n:
503                 new_addresses.append( self.create_new_address(False) )
504                 continue
505             if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]:
506                 break
507             else:
508                 new_addresses.append( self.create_new_address(False) )
509
510         if self.remote_url:
511             num = self.get_remote_number()
512             while len(self.addresses)<num:
513                 new_addresses.append( self.create_new_address(False) )
514
515         return new_addresses
516
517
518     def get_remote_number(self):
519         import jsonrpclib
520         server = jsonrpclib.Server(self.remote_url)
521         out = server.getnum()
522         return out
523
524     def get_remote_mpk(self):
525         import jsonrpclib
526         server = jsonrpclib.Server(self.remote_url)
527         out = server.getkey()
528         return out
529
530     def is_found(self):
531         return (len(self.change_addresses) > 1 ) or ( len(self.addresses) > self.gap_limit )
532
533     def fill_addressbook(self):
534         for tx in self.tx_history.values():
535             if tx['value']<0:
536                 for i in tx['outputs']:
537                     if not self.is_mine(i) and i not in self.addressbook:
538                         self.addressbook.append(i)
539         # redo labels
540         self.update_tx_labels()
541
542
543     def save(self):
544         s = {
545             'seed_version':self.seed_version,
546             'use_encryption':self.use_encryption,
547             'master_public_key': self.master_public_key.encode('hex'),
548             'fee':self.fee,
549             'server':self.server,
550             'seed':self.seed,
551             'addresses':self.addresses,
552             'change_addresses':self.change_addresses,
553             'history':self.history, 
554             'labels':self.labels,
555             'contacts':self.addressbook,
556             'imported_keys':self.imported_keys,
557             'aliases':self.aliases,
558             'authorities':self.authorities,
559             'receipts':self.receipts,
560             'num_zeros':self.num_zeros,
561             'frozen_addresses':self.frozen_addresses,
562             }
563         f = open(self.path,"w")
564         f.write( repr(s) )
565         f.close()
566
567     def read(self):
568         import interface
569
570         upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic."""
571         self.file_exists = False
572         try:
573             f = open(self.path,"r")
574             data = f.read()
575             f.close()
576         except:
577             return
578         data = interface.old_to_new(data)
579         try:
580             d = ast.literal_eval( data )
581             self.seed_version = d.get('seed_version')
582             self.master_public_key = d.get('master_public_key').decode('hex')
583             self.use_encryption = d.get('use_encryption')
584             self.fee = int( d.get('fee') )
585             self.seed = d.get('seed')
586             self.server = d.get('server')
587             #blocks = d.get('blocks')
588             self.addresses = d.get('addresses')
589             self.change_addresses = d.get('change_addresses')
590             self.history = d.get('history')
591             self.labels = d.get('labels')
592             self.addressbook = d.get('contacts')
593             self.imported_keys = d.get('imported_keys',{})
594             self.aliases = d.get('aliases',{})
595             self.authorities = d.get('authorities',{})
596             self.receipts = d.get('receipts',{})
597             self.num_zeros = d.get('num_zeros',0)
598             self.frozen_addresses = d.get('frozen_addresses',[])
599         except:
600             raise BaseException("cannot read wallet file")
601
602         self.update_tx_history()
603
604         if self.seed_version != SEED_VERSION:
605             raise BaseException(upgrade_msg)
606
607         if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk()
608
609         self.file_exists = True
610
611
612         
613
614     def get_addr_balance(self, addr):
615         assert self.is_mine(addr)
616         h = self.history.get(addr,[])
617         c = u = 0
618         for item in h:
619             v = item['value']
620             if item['height']:
621                 c += v
622             else:
623                 u += v
624         return c, u
625
626     def get_balance(self):
627         conf = unconf = 0
628         for addr in self.all_addresses(): 
629             c, u = self.get_addr_balance(addr)
630             conf += c
631             unconf += u
632         return conf, unconf
633
634
635     def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ):
636         """ todo: minimize tx size """
637         total = 0
638         fee = self.fee if fixed_fee is None else fixed_fee
639
640         coins = []
641         domain = [from_addr] if from_addr else self.all_addresses()
642         for i in self.frozen_addresses:
643             if i in domain: domain.remove(i)
644
645         for addr in domain:
646             h = self.history.get(addr)
647             if h is None: continue
648             for item in h:
649                 if item.get('raw_output_script'):
650                     coins.append( (addr,item))
651
652         coins = sorted( coins, key = lambda x: x[1]['timestamp'] )
653         inputs = []
654         for c in coins: 
655             addr, item = c
656             v = item.get('value')
657             total += v
658             inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) )
659             fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee
660             if total >= amount + fee: break
661         else:
662             #print "not enough funds: %d %d"%(total, fee)
663             inputs = []
664         return inputs, total, fee
665
666     def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ):
667         outputs = [ (to_addr, amount) ]
668         change_amount = total - ( amount + fee )
669         if change_amount != 0:
670             # normally, the update thread should ensure that the last change address is unused
671             if not change_addr:
672                 change_addr = self.change_addresses[-1]
673             outputs.append( ( change_addr,  change_amount) )
674         return outputs
675
676     def sign_inputs( self, inputs, outputs, password ):
677         s_inputs = []
678         for i in range(len(inputs)):
679             addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i]
680             private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 )
681             public_key = private_key.get_verifying_key()
682             pubkey = public_key.to_string()
683             tx = filter( raw_tx( inputs, outputs, for_sig = i ) )
684             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
685             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
686             s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) )
687         return s_inputs
688
689     def pw_encode(self, s, password):
690         if password:
691             secret = Hash(password)
692             return EncodeAES(secret, s)
693         else:
694             return s
695
696     def pw_decode(self, s, password):
697         if password is not None:
698             secret = Hash(password)
699             d = DecodeAES(secret, s)
700             if s == self.seed:
701                 try:
702                     d.decode('hex')
703                 except:
704                     raise BaseException("Invalid password")
705             return d
706         else:
707             return s
708
709     def get_status(self, address):
710         h = self.history.get(address)
711         if not h:
712             status = None
713         else:
714             lastpoint = h[-1]
715             status = lastpoint['block_hash']
716             if status == 'mempool': 
717                 status = status + ':%d'% len(h)
718         return status
719
720     def receive_status_callback(self, addr, status):
721         with self.lock:
722             if self.get_status(addr) != status:
723                 #print "updating status for", addr, status
724                 self.interface.get_history(addr)
725
726     def receive_history_callback(self, addr, data): 
727         #print "updating history for", addr
728         with self.lock:
729             self.history[addr] = data
730             self.update_tx_history()
731             self.save()
732
733     def get_tx_history(self):
734         lines = self.tx_history.values()
735         lines = sorted(lines, key=operator.itemgetter("timestamp"))
736         return lines
737
738     def update_tx_history(self):
739         self.tx_history= {}
740         for addr in self.all_addresses():
741             h = self.history.get(addr)
742             if h is None: continue
743             for tx in h:
744                 tx_hash = tx['tx_hash']
745                 line = self.tx_history.get(tx_hash)
746                 if not line:
747                     self.tx_history[tx_hash] = copy.copy(tx)
748                     line = self.tx_history.get(tx_hash)
749                 else:
750                     line['value'] += tx['value']
751                 if line['height'] == 0:
752                     line['timestamp'] = 1e12
753         self.update_tx_labels()
754
755     def update_tx_labels(self):
756         for tx in self.tx_history.values():
757             default_label = ''
758             if tx['value']<0:
759                 for o_addr in tx['outputs']:
760                     if not self.is_change(o_addr):
761                         dest_label = self.labels.get(o_addr)
762                         if dest_label:
763                             default_label = 'to: ' + dest_label
764                         else:
765                             default_label = 'to: ' + o_addr
766             else:
767                 for o_addr in tx['outputs']:
768                     if self.is_mine(o_addr) and not self.is_change(o_addr):
769                         dest_label = self.labels.get(o_addr)
770                         if dest_label:
771                             default_label = 'at: ' + dest_label
772                         else:
773                             default_label = 'at: ' + o_addr
774             tx['default_label'] = default_label
775
776     def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None):
777         if not self.is_valid(to_address):
778             raise BaseException("Invalid address")
779         inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr )
780         if not inputs:
781             raise BaseException("Not enough funds")
782         outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr )
783         s_inputs = self.sign_inputs( inputs, outputs, password )
784
785         tx = filter( raw_tx( s_inputs, outputs ) )
786         if to_address not in self.addressbook:
787             self.addressbook.append(to_address)
788         if label: 
789             tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
790             self.labels[tx_hash] = label
791
792         return tx
793
794     def sendtx(self, tx):
795         tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex')
796         self.tx_event.clear()
797         self.interface.send([('blockchain.transaction.broadcast', [tx])])
798         self.tx_event.wait()
799         out = self.tx_result 
800         if out != tx_hash:
801             return False, "error: " + out
802         if self.receipt:
803             self.receipts[tx_hash] = self.receipt
804             self.receipt = None
805         return True, out
806
807
808     def read_alias(self, alias):
809         # this might not be the right place for this function.
810         import urllib
811
812         m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias)
813         m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias)
814         if m1:
815             url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) 
816         elif m2:
817             url = 'http://' + alias + '/bitcoin.id'
818         else:
819             return ''
820         try:
821             lines = urllib.urlopen(url).readlines()
822         except:
823             return ''
824
825         # line 0
826         line = lines[0].strip().split(':')
827         if len(line) == 1:
828             auth_name = None
829             target = signing_addr = line[0]
830         else:
831             target, auth_name, signing_addr, signature = line
832             msg = "alias:%s:%s:%s"%(alias,target,auth_name)
833             print msg, signature
834             self.verify_message(signing_addr, signature, msg)
835         
836         # other lines are signed updates
837         for line in lines[1:]:
838             line = line.strip()
839             if not line: continue
840             line = line.split(':')
841             previous = target
842             print repr(line)
843             target, signature = line
844             self.verify_message(previous, signature, "alias:%s:%s"%(alias,target))
845
846         if not self.is_valid(target):
847             raise BaseException("Invalid bitcoin address")
848
849         return target, signing_addr, auth_name
850
851     def update_password(self, seed, old_password, new_password):
852         if new_password == '': new_password = None
853         self.use_encryption = (new_password != None)
854         self.seed = self.pw_encode( seed, new_password)
855         for k in self.imported_keys.keys():
856             a = self.imported_keys[k]
857             b = self.pw_decode(a, old_password)
858             c = self.pw_encode(b, new_password)
859             self.imported_keys[k] = c
860         self.save()
861
862     def get_alias(self, alias, interactive = False, show_message=None, question = None):
863         try:
864             target, signing_address, auth_name = self.read_alias(alias)
865         except BaseException, e:
866             # raise exception if verify fails (verify the chain)
867             if interactive:
868                 show_message("Alias error: " + str(e))
869             return
870
871         print target, signing_address, auth_name
872
873         if auth_name is None:
874             a = self.aliases.get(alias)
875             if not a:
876                 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)
877                 if interactive and question( msg ):
878                     self.aliases[alias] = (signing_address, target)
879                 else:
880                     target = None
881             else:
882                 if signing_address != a[0]:
883                     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
884                     if interactive and question( msg ):
885                         self.aliases[alias] = (signing_address, target)
886                     else:
887                         target = None
888         else:
889             if signing_address not in self.authorities.keys():
890                 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)
891                 if interactive and question( msg ):
892                     self.authorities[signing_address] = auth_name
893                 else:
894                     target = None
895
896         if target:
897             self.aliases[alias] = (signing_address, target)
898             
899         return target
900
901
902     def parse_url(self, url, show_message, question):
903         o = url[8:].split('?')
904         address = o[0]
905         if len(o)>1:
906             params = o[1].split('&')
907         else:
908             params = []
909
910         amount = label = message = signature = identity = ''
911         for p in params:
912             k,v = p.split('=')
913             uv = urldecode(v)
914             if k == 'amount': amount = uv
915             elif k == 'message': message = uv
916             elif k == 'label': label = uv
917             elif k == 'signature':
918                 identity, signature = uv.split(':')
919                 url = url.replace('&%s=%s'%(k,v),'')
920             else: 
921                 print k,v
922
923         if signature:
924             if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity):
925                 signing_address = self.get_alias(identity, True, show_message, question)
926             elif self.is_valid(identity):
927                 signing_address = identity
928             else:
929                 signing_address = None
930             if not signing_address:
931                 return
932             try:
933                 self.verify_message(signing_address, signature, url )
934                 self.receipt = (signing_address, signature, url)
935             except:
936                 show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.')
937                 address = amount = label = identity = message = ''
938
939         if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address):
940             payto_address = self.get_alias(address, True, show_message, question)
941             if payto_address:
942                 address = address + ' <' + payto_address + '>'
943
944         return address, amount, label, message, signature, identity, url
945
946
947     def update(self):
948         self.interface.poke()
949         self.up_to_date_event.wait()
950
951
952     def start_session(self, interface):
953         self.interface = interface
954         self.interface.send([('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])])
955         self.interface.subscribe(self.all_addresses())
956
957
958
959