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