method get_private_keys for sequence
[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
363
364
365 def bip32_init(seed):
366     import hmac
367         
368     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
369
370     print "seed", seed.encode('hex')
371     master_secret = I[0:32]
372     master_chain = I[32:]
373
374     # public key
375     curve = SECP256k1
376     master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
377     master_public_key = master_private_key.get_verifying_key()
378     K = master_public_key.to_string()
379     K_compressed = GetPubKey(master_public_key.pubkey,True)
380     return master_secret, master_chain, K, K_compressed
381
382     
383 def CKD(k, c, n):
384     import hmac
385     from ecdsa.util import string_to_number, number_to_string
386     order = generator_secp256k1.order()
387     keypair = EC_KEY(string_to_number(k))
388     K = GetPubKey(keypair.pubkey,True)
389     I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
390     k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
391     c_n = I[32:]
392     return k_n, c_n
393
394
395 def CKD_prime(K, c, n):
396     import hmac
397     from ecdsa.util import string_to_number, number_to_string
398     order = generator_secp256k1.order()
399
400     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
401     K_compressed = GetPubKey(K_public_key.pubkey,True)
402
403     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
404
405     #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
406     public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
407     K_n = public_key.to_string()
408     K_n_compressed = GetPubKey(public_key.pubkey,True)
409     c_n = I[32:]
410
411     return K_n, K_n_compressed, c_n
412
413
414
415 class DeterministicSequence:
416     """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
417
418     def __init__(self, master_public_key, mpk2 = None):
419         self.master_public_key = master_public_key
420         if mpk2:
421             self.mpk2 = mpk2
422             self.is_p2sh = True
423         else:
424             self.is_p2sh = False
425
426     @classmethod
427     def mpk_from_seed(klass, seed):
428         curve = SECP256k1
429         secexp = klass.stretch_key(seed)
430         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
431         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
432         return master_public_key
433
434     @classmethod
435     def stretch_key(self,seed):
436         oldseed = seed
437         for i in range(100000):
438             seed = hashlib.sha256(seed + oldseed).digest()
439         return string_to_number( seed )
440
441     def get_sequence(self, sequence):
442         for_change, n = sequence
443         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key.decode('hex') ) )
444
445     def get_address(self, sequence):
446         if not self.is_p2sh:
447             pubkey = self.get_pubkey(sequence)
448             address = public_key_to_bc_address( pubkey.decode('hex') )
449         else:
450             pubkey1 = self.get_pubkey(sequence)
451             pubkey2 = self.get_pubkey2(sequence)
452             address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"]
453         return address
454
455     #sec = self.p2sh_sequence.get_private_key(n, for_change, seed)
456     #addr = hash_160_to_bc_address(hash_160(txin["redeemScript"].decode('hex')), 5)
457
458     def get_pubkey2(self, sequence):
459         for_change, n = sequence
460         curve = SECP256k1
461         z = string_to_number( Hash( "%d:%d:"%(n, for_change) + self.mpk2.decode('hex') ) )
462         master_public_key = ecdsa.VerifyingKey.from_string( self.mpk2.decode('hex'), curve = SECP256k1 )
463         pubkey_point = master_public_key.pubkey.point + z*curve.generator
464         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
465         return '04' + public_key2.to_string().encode('hex')
466
467     def get_pubkey(self, sequence):
468         curve = SECP256k1
469         z = self.get_sequence(sequence)
470         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key.decode('hex'), 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         return '04' + public_key2.to_string().encode('hex')
474
475     def get_private_key_from_stretched_exponent(self, sequence, secexp):
476         order = generator_secp256k1.order()
477         secexp = ( secexp + self.get_sequence(sequence) ) % order
478         pk = number_to_string( secexp, generator_secp256k1.order() )
479         compressed = False
480         return SecretToASecret( pk, compressed )
481         
482     def get_private_key(self, sequence, seed):
483         secexp = self.stretch_key(seed)
484         return self.get_private_key_from_stretched_exponent(sequence, secexp)
485
486     def get_private_keys(self, sequence_list, seed):
487         secexp = self.stretch_key(seed)
488         return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list]
489
490     def check_seed(self, seed):
491         curve = SECP256k1
492         secexp = self.stretch_key(seed)
493         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
494         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
495         if master_public_key != self.master_public_key:
496             print_error('invalid password (mpk)')
497             raise BaseException('Invalid password')
498
499         return True
500
501
502     def get_input_info(self, sequence):
503
504         if not self.is_p2sh:
505             pk_addr = self.get_address(sequence)
506             redeemScript = None
507         else:
508             pubkey1 = self.get_pubkey(sequence)
509             pubkey2 = self.get_pubkey2(sequence)
510             pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key
511             redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript']
512
513         return pk_addr, redeemScript
514
515
516
517
518 class BIP32Sequence:
519
520     def __init__(self, mpkc, mpkc2 = None):
521         self.master_public_key, self.master_chain = mpkc
522         if mpkc2:
523             self.master_public_key2, self.master_chain2 = mpkc2
524             self.is_p2sh = True
525         else:
526             self.is_p2sh = False
527     
528     @classmethod
529     def mpk_from_seed(klass, seed):
530         master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
531         return master_public_key, master_chain
532
533     def get_pubkey(self, sequence):
534         K = self.master_public_key
535         chain = self.mchain
536         for i in sequence:
537             K, K_compressed, chain = CKD_prime(K, chain, i)
538         return K_compressed
539
540     def get_address(self, sequence):
541         return hash_160_to_bc_address(hash_160(self.get_pubkey(sequence)))
542
543     def get_private_key(self, seed, sequence):
544         k = self.master_secret
545         chain = self.master_chain
546         for i in sequence:
547             k, k_compressed, chain = CKD(k, chain, i)
548         return SecretToASecret(k0, True)
549
550     def check_seed(self, seed):
551         master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
552         assert self.master_public_key == master_public_key
553
554 ################################## transactions
555
556
557 class Transaction:
558     
559     def __init__(self, raw):
560         self.raw = raw
561         self.deserialize()
562         self.inputs = self.d['inputs']
563         self.outputs = self.d['outputs']
564         self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
565         self.input_info = None
566         self.is_complete = True
567         
568     @classmethod
569     def from_io(klass, inputs, outputs):
570         raw = klass.serialize(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
571         self = klass(raw)
572         self.is_complete = False
573         self.inputs = inputs
574         self.outputs = outputs
575         extras = []
576         for i in self.inputs:
577             e = { 'txid':i['tx_hash'], 'vout':i['index'], 'scriptPubKey':i.get('raw_output_script') }
578             extras.append(e)
579         self.input_info = extras
580         return self
581
582     def __str__(self):
583         return self.raw
584
585     @classmethod
586     def multisig_script(klass, public_keys, num=None):
587         n = len(public_keys)
588         if num is None: num = n
589         # supports only "2 of 2", and "2 of 3" transactions
590         assert num <= n and n in [2,3]
591     
592         if num==2:
593             s = '52'
594         elif num == 3:
595             s = '53'
596         else:
597             raise
598     
599         for k in public_keys:
600             s += var_int(len(k)/2)
601             s += k
602         if n==2:
603             s += '52'
604         elif n==3:
605             s += '53'
606         else:
607             raise
608         s += 'ae'
609
610         out = { "address": hash_160_to_bc_address(hash_160(s.decode('hex')), 5), "redeemScript":s }
611         return out
612
613     @classmethod
614     def serialize( klass, inputs, outputs, for_sig = None ):
615
616         s  = int_to_hex(1,4)                                         # version
617         s += var_int( len(inputs) )                                  # number of inputs
618         for i in range(len(inputs)):
619             txin = inputs[i]
620             s += txin['tx_hash'].decode('hex')[::-1].encode('hex')   # prev hash
621             s += int_to_hex(txin['index'],4)                         # prev index
622
623             if for_sig is None:
624                 pubkeysig = txin.get('pubkeysig')
625                 if pubkeysig:
626                     pubkey, sig = pubkeysig[0]
627                     sig = sig + chr(1)                               # hashtype
628                     script  = op_push( len(sig))
629                     script += sig.encode('hex')
630                     script += op_push( len(pubkey))
631                     script += pubkey.encode('hex')
632                 else:
633                     signatures = txin['signatures']
634                     pubkeys = txin['pubkeys']
635                     script = '00'                                    # op_0
636                     for sig in signatures:
637                         sig = sig + '01'
638                         script += op_push(len(sig)/2)
639                         script += sig
640
641                     redeem_script = klass.multisig_script(pubkeys,2).get('redeemScript')
642                     script += op_push(len(redeem_script)/2)
643                     script += redeem_script
644
645             elif for_sig==i:
646                 if txin.get('redeemScript'):
647                     script = txin['redeemScript']                    # p2sh uses the inner script
648                 else:
649                     script = txin['raw_output_script']               # scriptsig
650             else:
651                 script=''
652             s += var_int( len(script)/2 )                            # script length
653             s += script
654             s += "ffffffff"                                          # sequence
655
656         s += var_int( len(outputs) )                                 # number of outputs
657         for output in outputs:
658             addr, amount = output
659             s += int_to_hex( amount, 8)                              # amount
660             addrtype, hash_160 = bc_address_to_hash_160(addr)
661             if addrtype == 0:
662                 script = '76a9'                                      # op_dup, op_hash_160
663                 script += '14'                                       # push 0x14 bytes
664                 script += hash_160.encode('hex')
665                 script += '88ac'                                     # op_equalverify, op_checksig
666             elif addrtype == 5:
667                 script = 'a9'                                        # op_hash_160
668                 script += '14'                                       # push 0x14 bytes
669                 script += hash_160.encode('hex')
670                 script += '87'                                       # op_equal
671             else:
672                 raise
673             
674             s += var_int( len(script)/2 )                           #  script length
675             s += script                                             #  script
676         s += int_to_hex(0,4)                                        #  lock time
677         if for_sig is not None and for_sig != -1:
678             s += int_to_hex(1, 4)                                   #  hash type
679         return s
680
681
682     def for_sig(self,i):
683         return self.serialize(self.inputs, self.outputs, for_sig = i)
684
685
686     def hash(self):
687         return Hash(self.raw.decode('hex') )[::-1].encode('hex')
688
689     def sign(self, private_keys):
690         import deserialize
691
692         for i in range(len(self.inputs)):
693             txin = self.inputs[i]
694             tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i )
695
696             if txin.get('redeemScript'):
697                 # 1 parse the redeem script
698                 num, redeem_pubkeys = deserialize.parse_redeemScript(txin.get('redeemScript'))
699                 self.inputs[i]["pubkeys"] = redeem_pubkeys
700
701                 # build list of public/private keys
702                 keypairs = {}
703                 for sec in private_keys.values():
704                     compressed = is_compressed(sec)
705                     pkey = regenerate_key(sec)
706                     pubkey = GetPubKey(pkey.pubkey, compressed)
707                     keypairs[ pubkey.encode('hex') ] = sec
708
709                 # list of already existing signatures
710                 signatures = txin.get("signatures",[])
711                 print_error("signatures",signatures)
712
713                 for pubkey in redeem_pubkeys:
714                     public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
715                     for s in signatures:
716                         try:
717                             public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
718                             break
719                         except ecdsa.keys.BadSignatureError:
720                             continue
721                     else:
722                         # check if we have a key corresponding to the redeem script
723                         if pubkey in keypairs.keys():
724                             # add signature
725                             sec = keypairs[pubkey]
726                             compressed = is_compressed(sec)
727                             pkey = regenerate_key(sec)
728                             secexp = pkey.secret
729                             private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
730                             public_key = private_key.get_verifying_key()
731                             sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
732                             assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
733                             signatures.append( sig.encode('hex') )
734                         
735                 # for p2sh, pubkeysig is a tuple (may be incomplete)
736                 self.inputs[i]["signatures"] = signatures
737                 print_error("signatures",signatures)
738                 self.is_complete = len(signatures) == num
739
740             else:
741                 sec = private_keys[txin['address']]
742                 compressed = is_compressed(sec)
743                 pkey = regenerate_key(sec)
744                 secexp = pkey.secret
745
746                 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
747                 public_key = private_key.get_verifying_key()
748                 pkey = EC_KEY(secexp)
749                 pubkey = GetPubKey(pkey.pubkey, compressed)
750                 sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
751                 assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
752
753                 self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
754                 self.is_complete = True
755
756         self.raw = self.serialize( self.inputs, self.outputs )
757
758
759     def deserialize(self):
760         import deserialize
761         vds = deserialize.BCDataStream()
762         vds.write(self.raw.decode('hex'))
763         self.d = deserialize.parse_Transaction(vds)
764         return self.d
765     
766
767     def has_address(self, addr):
768         found = False
769         for txin in self.inputs:
770             if addr == txin.get('address'): 
771                 found = True
772                 break
773         for txout in self.outputs:
774             if addr == txout[0]:
775                 found = True
776                 break
777         return found
778
779
780     def get_value(self, addresses, prevout_values):
781         # return the balance for that tx
782         is_send = False
783         is_pruned = False
784         v_in = v_out = v_out_mine = 0
785
786         for item in self.inputs:
787             addr = item.get('address')
788             if addr in addresses:
789                 is_send = True
790                 key = item['prevout_hash']  + ':%d'%item['prevout_n']
791                 value = prevout_values.get( key )
792                 if value is None:
793                     is_pruned = True
794                 else:
795                     v_in += value
796             else:
797                 is_pruned = True
798                     
799         for item in self.outputs:
800             addr, value = item
801             v_out += value
802             if addr in addresses:
803                 v_out_mine += value
804
805         if not is_pruned:
806             # all inputs are mine:
807             fee = v_out - v_in
808             v = v_out_mine - v_in
809         else:
810             # some inputs are mine:
811             fee = None
812             if is_send:
813                 v = v_out_mine - v_out
814             else:
815                 # no input is mine
816                 v = v_out_mine
817             
818         return is_send, v, fee
819
820     def as_dict(self):
821         import json
822         out = {
823             "hex":self.raw,
824             "complete":self.is_complete
825             }
826         if not self.is_complete:
827             extras = []
828             for i in self.inputs:
829                 e = { 'txid':i['tx_hash'], 'vout':i['index'],
830                       'scriptPubKey':i.get('raw_output_script'),
831                       'electrumKeyID':i.get('electrumKeyID'),
832                       'redeemScript':i.get('redeemScript'),
833                       'signatures':i.get('signatures'),
834                       'pubkeys':i.get('pubkeys'),
835                       }
836                 extras.append(e)
837             self.input_info = extras
838
839             if self.input_info:
840                 out['input_info'] = json.dumps(self.input_info).replace(' ','')
841
842         return out
843
844
845
846
847 def test_bip32():
848     seed = "ff000000000000000000000000000000".decode('hex')
849     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
850         
851     print "secret key", master_secret.encode('hex')
852     print "chain code", master_chain.encode('hex')
853
854     key_id = hash_160(master_public_key_compressed)
855     print "keyid", key_id.encode('hex')
856     print "base58"
857     print "address", hash_160_to_bc_address(key_id)
858     print "secret key", SecretToASecret(master_secret, True)
859
860     print "-- m/0 --"
861     k0, c0 = CKD(master_secret, master_chain, 0)
862     print "secret", k0.encode('hex')
863     print "chain", c0.encode('hex')
864     print "secret key", SecretToASecret(k0, True)
865     
866     K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
867     print "address", hash_160_to_bc_address(hash_160(K0_compressed))
868     
869     print "-- m/0/1 --"
870     K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
871     print "address", hash_160_to_bc_address(hash_160(K01_compressed))
872     
873     print "-- m/0/1/3 --"
874     K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
875     print "address", hash_160_to_bc_address(hash_160(K013_compressed))
876     
877     print "-- m/0/1/3/7 --"
878     K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
879     print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
880         
881
882
883 if __name__ == '__main__':
884     test_bip32()
885
886