2of3 accounts
[electrum-nvc.git] / lib / bitcoin.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 hashlib, base64, ecdsa, re
21 from util import print_error
22
23 def rev_hex(s):
24     return s.decode('hex')[::-1].encode('hex')
25
26 def int_to_hex(i, length=1):
27     s = hex(i)[2:].rstrip('L')
28     s = "0"*(2*length - len(s)) + s
29     return rev_hex(s)
30
31 def var_int(i):
32     # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
33     if i<0xfd:
34         return int_to_hex(i)
35     elif i<=0xffff:
36         return "fd"+int_to_hex(i,2)
37     elif i<=0xffffffff:
38         return "fe"+int_to_hex(i,4)
39     else:
40         return "ff"+int_to_hex(i,8)
41
42 def op_push(i):
43     if i<0x4c:
44         return int_to_hex(i)
45     elif i<0xff:
46         return '4c' + int_to_hex(i)
47     elif i<0xffff:
48         return '4d' + int_to_hex(i,2)
49     else:
50         return '4e' + int_to_hex(i,4)
51     
52
53
54 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
55 hash_encode = lambda x: x[::-1].encode('hex')
56 hash_decode = lambda x: x.decode('hex')[::-1]
57
58
59 # pywallet openssl private key implementation
60
61 def i2d_ECPrivateKey(pkey, compressed=False):
62     if compressed:
63         key = '3081d30201010420' + \
64               '%064x' % pkey.secret + \
65               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
66               '%064x' % _p + \
67               '3006040100040107042102' + \
68               '%064x' % _Gx + \
69               '022100' + \
70               '%064x' % _r + \
71               '020101a124032200'
72     else:
73         key = '308201130201010420' + \
74               '%064x' % pkey.secret + \
75               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
76               '%064x' % _p + \
77               '3006040100040107044104' + \
78               '%064x' % _Gx + \
79               '%064x' % _Gy + \
80               '022100' + \
81               '%064x' % _r + \
82               '020101a144034200'
83         
84     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
85     
86 def i2o_ECPublicKey(pubkey, compressed=False):
87     # public keys are 65 bytes long (520 bits)
88     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
89     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
90     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
91     if compressed:
92         if pubkey.point.y() & 1:
93             key = '03' + '%064x' % pubkey.point.x()
94         else:
95             key = '02' + '%064x' % pubkey.point.x()
96     else:
97         key = '04' + \
98               '%064x' % pubkey.point.x() + \
99               '%064x' % pubkey.point.y()
100             
101     return key.decode('hex')
102             
103 # end pywallet openssl private key implementation
104
105                                                 
106             
107 ############ functions from pywallet ##################### 
108
109 def hash_160(public_key):
110     try:
111         md = hashlib.new('ripemd160')
112         md.update(hashlib.sha256(public_key).digest())
113         return md.digest()
114     except:
115         import ripemd
116         md = ripemd.new(hashlib.sha256(public_key).digest())
117         return md.digest()
118
119
120 def public_key_to_bc_address(public_key):
121     h160 = hash_160(public_key)
122     return hash_160_to_bc_address(h160)
123
124 def hash_160_to_bc_address(h160, addrtype = 0):
125     vh160 = chr(addrtype) + h160
126     h = Hash(vh160)
127     addr = vh160 + h[0:4]
128     return b58encode(addr)
129
130 def bc_address_to_hash_160(addr):
131     bytes = b58decode(addr, 25)
132     return ord(bytes[0]), bytes[1:21]
133
134 def encode_point(pubkey, compressed=False):
135     order = generator_secp256k1.order()
136     p = pubkey.pubkey.point
137     x_str = ecdsa.util.number_to_string(p.x(), order)
138     y_str = ecdsa.util.number_to_string(p.y(), order)
139     if compressed:
140         return chr(2 + (p.y() & 1)) + x_str
141     else:
142         return chr(4) + pubkey.to_string() #x_str + y_str
143
144 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
145 __b58base = len(__b58chars)
146
147 def b58encode(v):
148     """ encode v, which is a string of bytes, to base58."""
149
150     long_value = 0L
151     for (i, c) in enumerate(v[::-1]):
152         long_value += (256**i) * ord(c)
153
154     result = ''
155     while long_value >= __b58base:
156         div, mod = divmod(long_value, __b58base)
157         result = __b58chars[mod] + result
158         long_value = div
159     result = __b58chars[long_value] + result
160
161     # Bitcoin does a little leading-zero-compression:
162     # leading 0-bytes in the input become leading-1s
163     nPad = 0
164     for c in v:
165         if c == '\0': nPad += 1
166         else: break
167
168     return (__b58chars[0]*nPad) + result
169
170 def b58decode(v, length):
171     """ decode v into a string of len bytes."""
172     long_value = 0L
173     for (i, c) in enumerate(v[::-1]):
174         long_value += __b58chars.find(c) * (__b58base**i)
175
176     result = ''
177     while long_value >= 256:
178         div, mod = divmod(long_value, 256)
179         result = chr(mod) + result
180         long_value = div
181     result = chr(long_value) + result
182
183     nPad = 0
184     for c in v:
185         if c == __b58chars[0]: nPad += 1
186         else: break
187
188     result = chr(0)*nPad + result
189     if length is not None and len(result) != length:
190         return None
191
192     return result
193
194
195 def EncodeBase58Check(vchIn):
196     hash = Hash(vchIn)
197     return b58encode(vchIn + hash[0:4])
198
199 def DecodeBase58Check(psz):
200     vchRet = b58decode(psz, None)
201     key = vchRet[0:-4]
202     csum = vchRet[-4:]
203     hash = Hash(key)
204     cs32 = hash[0:4]
205     if cs32 != csum:
206         return None
207     else:
208         return key
209
210 def PrivKeyToSecret(privkey):
211     return privkey[9:9+32]
212
213 def SecretToASecret(secret, compressed=False, addrtype=0):
214     vchIn = chr((addrtype+128)&255) + secret
215     if compressed: vchIn += '\01'
216     return EncodeBase58Check(vchIn)
217
218 def ASecretToSecret(key, addrtype=0):
219     vch = DecodeBase58Check(key)
220     if vch and vch[0] == chr((addrtype+128)&255):
221         return vch[1:]
222     else:
223         return False
224
225 def regenerate_key(sec):
226     b = ASecretToSecret(sec)
227     if not b:
228         return False
229     b = b[0:32]
230     secret = int('0x' + b.encode('hex'), 16)
231     return EC_KEY(secret)
232
233 def GetPubKey(pubkey, compressed=False):
234     return i2o_ECPublicKey(pubkey, compressed)
235
236 def GetPrivKey(pkey, compressed=False):
237     return i2d_ECPrivateKey(pkey, compressed)
238
239 def GetSecret(pkey):
240     return ('%064x' % pkey.secret).decode('hex')
241
242 def is_compressed(sec):
243     b = ASecretToSecret(sec)
244     return len(b) == 33
245
246
247 def address_from_private_key(sec):
248     # rebuild public key from private key, compressed or uncompressed
249     pkey = regenerate_key(sec)
250     assert pkey
251
252     # figure out if private key is compressed
253     compressed = is_compressed(sec)
254         
255     # rebuild private and public key from regenerated secret
256     private_key = GetPrivKey(pkey, compressed)
257     public_key = GetPubKey(pkey.pubkey, compressed)
258     address = public_key_to_bc_address(public_key)
259     return address
260
261
262 def is_valid(addr):
263     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
264     if not ADDRESS_RE.match(addr): return False
265     try:
266         addrtype, h = bc_address_to_hash_160(addr)
267     except:
268         return False
269     return addr == hash_160_to_bc_address(h, addrtype)
270
271
272 ########### end pywallet functions #######################
273
274 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
275 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
276 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
277 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
278 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
279 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
280 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
281 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
282 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
283 oid_secp256k1 = (1,3,132,0,10)
284 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
285
286 from ecdsa.util import string_to_number, number_to_string
287
288 def msg_magic(message):
289     return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
290
291
292 class EC_KEY(object):
293     def __init__( self, secret ):
294         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
295         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
296         self.secret = secret
297
298     def sign_message(self, message, compressed, address):
299         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
300         public_key = private_key.get_verifying_key()
301         signature = private_key.sign_digest( Hash( msg_magic(message) ), sigencode = ecdsa.util.sigencode_string )
302         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
303         for i in range(4):
304             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
305             try:
306                 self.verify_message( address, sig, message)
307                 return sig
308             except:
309                 continue
310         else:
311             raise BaseException("error: cannot sign message")
312
313     @classmethod
314     def verify_message(self, address, signature, message):
315         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
316         from ecdsa import numbertheory, ellipticcurve, util
317         import msqr
318         curve = curve_secp256k1
319         G = generator_secp256k1
320         order = G.order()
321         # extract r,s from signature
322         sig = base64.b64decode(signature)
323         if len(sig) != 65: raise BaseException("Wrong encoding")
324         r,s = util.sigdecode_string(sig[1:], order)
325         nV = ord(sig[0])
326         if nV < 27 or nV >= 35:
327             raise BaseException("Bad encoding")
328         if nV >= 31:
329             compressed = True
330             nV -= 4
331         else:
332             compressed = False
333
334         recid = nV - 27
335         # 1.1
336         x = r + (recid/2) * order
337         # 1.3
338         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
339         beta = msqr.modular_sqrt(alpha, curve.p())
340         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
341         # 1.4 the constructor checks that nR is at infinity
342         R = ellipticcurve.Point(curve, x, y, order)
343         # 1.5 compute e from message:
344         h = Hash( msg_magic(message) )
345         e = string_to_number(h)
346         minus_e = -e % order
347         # 1.6 compute Q = r^-1 (sR - eG)
348         inv_r = numbertheory.inverse_mod(r,order)
349         Q = inv_r * ( s * R + minus_e * G )
350         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
351         # check that Q is the public key
352         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
353         # check that we get the original signing address
354         addr = public_key_to_bc_address( encode_point(public_key, compressed) )
355         if address != addr:
356             raise BaseException("Bad signature")
357
358
359 ###################################### BIP32 ##############################
360
361 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
362 BIP32_PRIME = 0x80000000
363
364 def bip32_init(seed):
365     import hmac
366     seed = seed.decode('hex')        
367     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
368
369     master_secret = I[0:32]
370     master_chain = I[32:]
371
372     K, K_compressed = get_pubkeys_from_secret(master_secret)
373     return master_secret, master_chain, K, K_compressed
374
375
376 def get_pubkeys_from_secret(secret):
377     # public key
378     curve = SECP256k1
379     private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
380     public_key = private_key.get_verifying_key()
381     K = public_key.to_string()
382     K_compressed = GetPubKey(public_key.pubkey,True)
383     return K, K_compressed
384
385
386
387     
388 def CKD(k, c, n):
389     import hmac
390     from ecdsa.util import string_to_number, number_to_string
391     order = generator_secp256k1.order()
392     keypair = EC_KEY(string_to_number(k))
393     K = GetPubKey(keypair.pubkey,True)
394
395     if n & BIP32_PRIME:
396         data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex')
397         I = hmac.new(c, data, hashlib.sha512).digest()
398     else:
399         I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
400         
401     k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
402     c_n = I[32:]
403     return k_n, c_n
404
405
406 def CKD_prime(K, c, n):
407     import hmac
408     from ecdsa.util import string_to_number, number_to_string
409     order = generator_secp256k1.order()
410
411     if n & BIP32_PRIME: raise
412
413     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
414     K_compressed = GetPubKey(K_public_key.pubkey,True)
415
416     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
417
418     curve = SECP256k1
419     pubkey_point = string_to_number(I[0:32])*curve.generator + K_public_key.pubkey.point
420     public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
421
422     K_n = public_key.to_string()
423     K_n_compressed = GetPubKey(public_key.pubkey,True)
424     c_n = I[32:]
425
426     return K_n, K_n_compressed, c_n
427
428
429
430 def bip32_private_derivation(k, c, branch, sequence):
431     assert sequence.startswith(branch)
432     sequence = sequence[len(branch):]
433     for n in sequence.split('/'):
434         if n == '': continue
435         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
436         k, c = CKD(k, c, n)
437     K, K_compressed = get_pubkeys_from_secret(k)
438     return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex')
439
440
441 def bip32_public_derivation(c, K, branch, sequence):
442     assert sequence.startswith(branch)
443     sequence = sequence[len(branch):]
444     for n in sequence.split('/'):
445         n = int(n)
446         K, cK, c = CKD_prime(K, c, n)
447
448     return c.encode('hex'), K.encode('hex'), cK.encode('hex')
449
450
451
452
453
454 ################################## transactions
455
456 MIN_RELAY_TX_FEE = 10000
457
458 class Transaction:
459     
460     def __init__(self, raw):
461         self.raw = raw
462         self.deserialize()
463         self.inputs = self.d['inputs']
464         self.outputs = self.d['outputs']
465         self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
466         self.input_info = None
467         self.is_complete = True
468         
469     @classmethod
470     def from_io(klass, inputs, outputs):
471         raw = klass.serialize(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
472         self = klass(raw)
473         self.is_complete = False
474         self.inputs = inputs
475         self.outputs = outputs
476         extras = []
477         for i in self.inputs:
478             e = { 'txid':i['tx_hash'], 'vout':i['index'], 'scriptPubKey':i.get('raw_output_script') }
479             extras.append(e)
480         self.input_info = extras
481         return self
482
483     def __str__(self):
484         return self.raw
485
486     @classmethod
487     def multisig_script(klass, public_keys, num=None):
488         n = len(public_keys)
489         if num is None: num = n
490         # supports only "2 of 2", and "2 of 3" transactions
491         assert num <= n and n in [2,3]
492     
493         if num==2:
494             s = '52'
495         elif num == 3:
496             s = '53'
497         else:
498             raise
499     
500         for k in public_keys:
501             s += var_int(len(k)/2)
502             s += k
503         if n==2:
504             s += '52'
505         elif n==3:
506             s += '53'
507         else:
508             raise
509         s += 'ae'
510
511         return s
512
513     @classmethod
514     def serialize( klass, inputs, outputs, for_sig = None ):
515
516         s  = int_to_hex(1,4)                                         # version
517         s += var_int( len(inputs) )                                  # number of inputs
518         for i in range(len(inputs)):
519             txin = inputs[i]
520             s += txin['tx_hash'].decode('hex')[::-1].encode('hex')   # prev hash
521             s += int_to_hex(txin['index'],4)                         # prev index
522
523             if for_sig is None:
524                 pubkeysig = txin.get('pubkeysig')
525                 if pubkeysig:
526                     pubkey, sig = pubkeysig[0]
527                     sig = sig + chr(1)                               # hashtype
528                     script  = op_push( len(sig))
529                     script += sig.encode('hex')
530                     script += op_push( len(pubkey))
531                     script += pubkey.encode('hex')
532                 else:
533                     signatures = txin['signatures']
534                     pubkeys = txin['pubkeys']
535                     script = '00'                                    # op_0
536                     for sig in signatures:
537                         sig = sig + '01'
538                         script += op_push(len(sig)/2)
539                         script += sig
540
541                     redeem_script = klass.multisig_script(pubkeys,2).get('redeemScript')
542                     script += op_push(len(redeem_script)/2)
543                     script += redeem_script
544
545             elif for_sig==i:
546                 if txin.get('redeemScript'):
547                     script = txin['redeemScript']                    # p2sh uses the inner script
548                 else:
549                     script = txin['raw_output_script']               # scriptsig
550             else:
551                 script=''
552             s += var_int( len(script)/2 )                            # script length
553             s += script
554             s += "ffffffff"                                          # sequence
555
556         s += var_int( len(outputs) )                                 # number of outputs
557         for output in outputs:
558             addr, amount = output
559             s += int_to_hex( amount, 8)                              # amount
560             addrtype, hash_160 = bc_address_to_hash_160(addr)
561             if addrtype == 0:
562                 script = '76a9'                                      # op_dup, op_hash_160
563                 script += '14'                                       # push 0x14 bytes
564                 script += hash_160.encode('hex')
565                 script += '88ac'                                     # op_equalverify, op_checksig
566             elif addrtype == 5:
567                 script = 'a9'                                        # op_hash_160
568                 script += '14'                                       # push 0x14 bytes
569                 script += hash_160.encode('hex')
570                 script += '87'                                       # op_equal
571             else:
572                 raise
573             
574             s += var_int( len(script)/2 )                           #  script length
575             s += script                                             #  script
576         s += int_to_hex(0,4)                                        #  lock time
577         if for_sig is not None and for_sig != -1:
578             s += int_to_hex(1, 4)                                   #  hash type
579         return s
580
581
582     def for_sig(self,i):
583         return self.serialize(self.inputs, self.outputs, for_sig = i)
584
585
586     def hash(self):
587         return Hash(self.raw.decode('hex') )[::-1].encode('hex')
588
589     def sign(self, private_keys):
590         import deserialize
591
592         for i in range(len(self.inputs)):
593             txin = self.inputs[i]
594             tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i )
595
596             redeem_script = txin.get('redeemScript')
597             if redeem_script:
598                 # 1 parse the redeem script
599                 num, redeem_pubkeys = deserialize.parse_redeemScript(redeem_script)
600                 self.inputs[i]["pubkeys"] = redeem_pubkeys
601
602                 # build list of public/private keys
603                 keypairs = {}
604                 for sec in private_keys.values():
605                     compressed = is_compressed(sec)
606                     pkey = regenerate_key(sec)
607                     pubkey = GetPubKey(pkey.pubkey, compressed)
608                     keypairs[ pubkey.encode('hex') ] = sec
609
610                 print "keypairs", keypairs
611                 print redeem_script, redeem_pubkeys
612
613                 # list of already existing signatures
614                 signatures = txin.get("signatures",[])
615                 print_error("signatures",signatures)
616
617                 for pubkey in redeem_pubkeys:
618
619                     # here we have compressed key.. it won't work
620                     #public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)  
621                     #for s in signatures:
622                     #    try:
623                     #        public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
624                     #        break
625                     #    except ecdsa.keys.BadSignatureError:
626                     #        continue
627                     #else:
628                     if 1:
629                         # check if we have a key corresponding to the redeem script
630                         if pubkey in keypairs.keys():
631                             # add signature
632                             sec = keypairs[pubkey]
633                             compressed = is_compressed(sec)
634                             pkey = regenerate_key(sec)
635                             secexp = pkey.secret
636                             private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
637                             public_key = private_key.get_verifying_key()
638                             sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
639                             assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
640                             signatures.append( sig.encode('hex') )
641                         
642                 # for p2sh, pubkeysig is a tuple (may be incomplete)
643                 self.inputs[i]["signatures"] = signatures
644                 print_error("signatures",signatures)
645                 self.is_complete = len(signatures) == num
646
647             else:
648                 sec = private_keys[txin['address']]
649                 compressed = is_compressed(sec)
650                 pkey = regenerate_key(sec)
651                 secexp = pkey.secret
652                 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
653                 public_key = private_key.get_verifying_key()
654                 pkey = EC_KEY(secexp)
655                 pubkey = GetPubKey(pkey.pubkey, compressed)
656                 sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
657                 assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
658
659                 self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
660                 self.is_complete = True
661
662         self.raw = self.serialize( self.inputs, self.outputs )
663
664
665     def deserialize(self):
666         import deserialize
667         vds = deserialize.BCDataStream()
668         vds.write(self.raw.decode('hex'))
669         self.d = deserialize.parse_Transaction(vds)
670         return self.d
671     
672
673     def has_address(self, addr):
674         found = False
675         for txin in self.inputs:
676             if addr == txin.get('address'): 
677                 found = True
678                 break
679         for txout in self.outputs:
680             if addr == txout[0]:
681                 found = True
682                 break
683         return found
684
685
686     def get_value(self, addresses, prevout_values):
687         # return the balance for that tx
688         is_relevant = False
689         is_send = False
690         is_pruned = False
691         is_partial = False
692         v_in = v_out = v_out_mine = 0
693
694         for item in self.inputs:
695             addr = item.get('address')
696             if addr in addresses:
697                 is_send = True
698                 is_relevant = True
699                 key = item['prevout_hash']  + ':%d'%item['prevout_n']
700                 value = prevout_values.get( key )
701                 if value is None:
702                     is_pruned = True
703                 else:
704                     v_in += value
705             else:
706                 is_partial = True
707
708         if not is_send: is_partial = False
709                     
710         for item in self.outputs:
711             addr, value = item
712             v_out += value
713             if addr in addresses:
714                 v_out_mine += value
715                 is_relevant = True
716
717         if is_pruned:
718             # some inputs are mine:
719             fee = None
720             if is_send:
721                 v = v_out_mine - v_out
722             else:
723                 # no input is mine
724                 v = v_out_mine
725
726         else:
727             v = v_out_mine - v_in
728
729             if is_partial:
730                 # some inputs are mine, but not all
731                 fee = None
732                 is_send = v < 0
733             else:
734                 # all inputs are mine
735                 fee = v_out - v_in
736
737         return is_relevant, is_send, v, fee
738
739     def as_dict(self):
740         import json
741         out = {
742             "hex":self.raw,
743             "complete":self.is_complete
744             }
745         if not self.is_complete:
746             extras = []
747             for i in self.inputs:
748                 e = { 'txid':i['tx_hash'], 'vout':i['index'],
749                       'scriptPubKey':i.get('raw_output_script'),
750                       'KeyID':i.get('KeyID'),
751                       'redeemScript':i.get('redeemScript'),
752                       'signatures':i.get('signatures'),
753                       'pubkeys':i.get('pubkeys'),
754                       }
755                 extras.append(e)
756             self.input_info = extras
757
758             if self.input_info:
759                 out['input_info'] = json.dumps(self.input_info).replace(' ','')
760
761         return out
762
763
764     def requires_fee(self, verifier):
765         # see https://en.bitcoin.it/wiki/Transaction_fees
766         threshold = 57600000
767         size = len(self.raw)/2
768         if size >= 10000: 
769             return True
770
771         for o in self.outputs:
772             value = o[1]
773             if value < 1000000:
774                 return True
775         sum = 0
776         for i in self.inputs:
777             age = verifier.get_confirmations(i["tx_hash"])[0]
778             sum += i["value"] * age
779         priority = sum / size
780         print_error(priority, threshold)
781         return priority < threshold 
782
783
784
785
786 def test_bip32(seed, sequence):
787     """
788     run a test vector,
789     see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
790     """
791
792     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
793         
794     print "secret key", master_secret.encode('hex')
795     print "chain code", master_chain.encode('hex')
796
797     key_id = hash_160(master_public_key_compressed)
798     print "keyid", key_id.encode('hex')
799     print "base58"
800     print "address", hash_160_to_bc_address(key_id)
801     print "secret key", SecretToASecret(master_secret, True)
802
803     k = master_secret
804     c = master_chain
805
806     s = ['m']
807     for n in sequence.split('/'):
808         s.append(n)
809         print "Chain [%s]" % '/'.join(s)
810         
811         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
812         k0, c0 = CKD(k, c, n)
813         K0, K0_compressed = get_pubkeys_from_secret(k0)
814
815         print "* Identifier"
816         print "  * (main addr)", hash_160_to_bc_address(hash_160(K0_compressed))
817
818         print "* Secret Key"
819         print "  * (hex)", k0.encode('hex')
820         print "  * (wif)", SecretToASecret(k0, True)
821
822         print "* Chain Code"
823         print "   * (hex)", c0.encode('hex')
824
825         k = k0
826         c = c0
827     print "----"
828
829         
830
831
832 if __name__ == '__main__':
833     test_bip32("000102030405060708090a0b0c0d0e0f", "0'/1/2'/2/1000000000")
834     test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","0/2147483647'/1/2147483646'/2")
835