create separate class for deterministic key generation. add pubkeys to validateaddress
[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
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 ########### end pywallet functions #######################
263
264 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
265 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
266 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
267 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
268 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
269 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
270 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
271 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
272 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
273 oid_secp256k1 = (1,3,132,0,10)
274 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
275
276 from ecdsa.util import string_to_number, number_to_string
277
278 def msg_magic(message):
279     return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
280
281
282 class EC_KEY(object):
283     def __init__( self, secret ):
284         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
285         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
286         self.secret = secret
287
288     def sign_message(self, message, compressed, address):
289         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
290         public_key = private_key.get_verifying_key()
291         signature = private_key.sign_digest( Hash( msg_magic(message) ), sigencode = ecdsa.util.sigencode_string )
292         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
293         for i in range(4):
294             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
295             try:
296                 self.verify_message( address, sig, message)
297                 return sig
298             except:
299                 continue
300         else:
301             raise BaseException("error: cannot sign message")
302
303     @classmethod
304     def verify_message(self, address, signature, message):
305         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
306         from ecdsa import numbertheory, ellipticcurve, util
307         import msqr
308         curve = curve_secp256k1
309         G = generator_secp256k1
310         order = G.order()
311         # extract r,s from signature
312         sig = base64.b64decode(signature)
313         if len(sig) != 65: raise BaseException("Wrong encoding")
314         r,s = util.sigdecode_string(sig[1:], order)
315         nV = ord(sig[0])
316         if nV < 27 or nV >= 35:
317             raise BaseException("Bad encoding")
318         if nV >= 31:
319             compressed = True
320             nV -= 4
321         else:
322             compressed = False
323
324         recid = nV - 27
325         # 1.1
326         x = r + (recid/2) * order
327         # 1.3
328         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
329         beta = msqr.modular_sqrt(alpha, curve.p())
330         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
331         # 1.4 the constructor checks that nR is at infinity
332         R = ellipticcurve.Point(curve, x, y, order)
333         # 1.5 compute e from message:
334         h = Hash( msg_magic(message) )
335         e = string_to_number(h)
336         minus_e = -e % order
337         # 1.6 compute Q = r^-1 (sR - eG)
338         inv_r = numbertheory.inverse_mod(r,order)
339         Q = inv_r * ( s * R + minus_e * G )
340         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
341         # check that Q is the public key
342         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
343         # check that we get the original signing address
344         addr = public_key_to_bc_address( encode_point(public_key, compressed) )
345         if address != addr:
346             raise BaseException("Bad signature")
347
348
349 ###################################### BIP32 ##############################
350
351 def bip32_init(seed):
352     import hmac
353         
354     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
355
356     print "seed", seed.encode('hex')
357     master_secret = I[0:32]
358     master_chain = I[32:]
359
360     # public key
361     curve = SECP256k1
362     master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
363     master_public_key = master_private_key.get_verifying_key()
364     K = master_public_key.to_string()
365     K_compressed = GetPubKey(master_public_key.pubkey,True)
366     return master_secret, master_chain, K, K_compressed
367
368     
369 def CKD(k, c, n):
370     import hmac
371     from ecdsa.util import string_to_number, number_to_string
372     order = generator_secp256k1.order()
373     keypair = EC_KEY(string_to_number(k))
374     K = GetPubKey(keypair.pubkey,True)
375     I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
376     k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
377     c_n = I[32:]
378     return k_n, c_n
379
380
381 def CKD_prime(K, c, n):
382     import hmac
383     from ecdsa.util import string_to_number, number_to_string
384     order = generator_secp256k1.order()
385
386     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
387     K_compressed = GetPubKey(K_public_key.pubkey,True)
388
389     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
390
391     #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
392     public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
393     K_n = public_key.to_string()
394     K_n_compressed = GetPubKey(public_key.pubkey,True)
395     c_n = I[32:]
396
397     return K_n, K_n_compressed, c_n
398
399
400
401 class DeterministicSequence:
402     """  Privatekey(type,n) = Master_private_key + H(n|S|type)  """
403
404     def __init__(self, master_public_key):
405         self.master_public_key = master_public_key
406
407     @classmethod
408     def from_seed(klass, seed):
409         curve = SECP256k1
410         secexp = klass.stretch_key(seed)
411         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
412         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
413         self = klass(master_public_key)
414         return self
415
416     @classmethod
417     def stretch_key(self,seed):
418         oldseed = seed
419         for i in range(100000):
420             seed = hashlib.sha256(seed + oldseed).digest()
421         return string_to_number( seed )
422
423     def get_sequence(self,n,for_change):
424         return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key.decode('hex') ) )
425
426     def get_pubkey(self, n, for_change):
427         curve = SECP256k1
428         z = self.get_sequence(n, for_change)
429         master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key.decode('hex'), curve = SECP256k1 )
430         pubkey_point = master_public_key.pubkey.point + z*curve.generator
431         public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
432         return '04' + public_key2.to_string().encode('hex')
433
434     def get_private_key(self, n, for_change, seed):
435         order = generator_secp256k1.order()
436         secexp = self.stretch_key(seed)
437         secexp = ( secexp + self.get_sequence(n,for_change) ) % order
438         pk = number_to_string( secexp, generator_secp256k1.order() )
439         compressed = False
440         return SecretToASecret( pk, compressed )
441
442     def check_seed(self, seed):
443         curve = SECP256k1
444         secexp = self.stretch_key(seed)
445         master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
446         master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
447         if master_public_key != self.master_public_key:
448             print_error('invalid password (mpk)')
449             raise BaseException('Invalid password')
450
451         return True
452
453 ################################## transactions
454
455
456
457 def raw_tx( inputs, outputs, for_sig = None ):
458
459     s  = int_to_hex(1,4)                                         # version
460     s += var_int( len(inputs) )                                  # number of inputs
461     for i in range(len(inputs)):
462         txin = inputs[i]
463         s += txin['tx_hash'].decode('hex')[::-1].encode('hex')   # prev hash
464         s += int_to_hex(txin['index'],4)                         # prev index
465
466         if for_sig is None:
467             pubkeysig = txin.get('pubkeysig')
468             if pubkeysig:
469                 pubkey, sig = pubkeysig[0]
470                 sig = sig + chr(1)                               # hashtype
471                 script  = op_push( len(sig))
472                 script += sig.encode('hex')
473                 script += op_push( len(pubkey))
474                 script += pubkey.encode('hex')
475             else:
476                 signatures = txin['signatures']
477                 pubkeys = txin['pubkeys']
478                 script = '00'                                    # op_0
479                 for sig in signatures:
480                     sig = sig + '01'
481                     script += op_push(len(sig)/2)
482                     script += sig
483
484                 redeem_script = multisig_script(pubkeys,2)
485                 script += op_push(len(redeem_script)/2)
486                 script += redeem_script
487
488         elif for_sig==i:
489             if txin.get('redeemScript'):
490                 script = txin['redeemScript']                    # p2sh uses the inner script
491             else:
492                 script = txin['raw_output_script']               # scriptsig
493         else:
494             script=''
495         s += var_int( len(script)/2 )                            # script length
496         s += script
497         s += "ffffffff"                                          # sequence
498
499     s += var_int( len(outputs) )                                 # number of outputs
500     for output in outputs:
501         addr, amount = output
502         s += int_to_hex( amount, 8)                              # amount
503         addrtype, hash_160 = bc_address_to_hash_160(addr)
504         if addrtype == 0:
505             script = '76a9'                                      # op_dup, op_hash_160
506             script += '14'                                       # push 0x14 bytes
507             script += hash_160.encode('hex')
508             script += '88ac'                                     # op_equalverify, op_checksig
509         elif addrtype == 5:
510             script = 'a9'                                        # op_hash_160
511             script += '14'                                       # push 0x14 bytes
512             script += hash_160.encode('hex')
513             script += '87'                                       # op_equal
514         else:
515             raise
516             
517         s += var_int( len(script)/2 )                           #  script length
518         s += script                                             #  script
519     s += int_to_hex(0,4)                                        #  lock time
520     if for_sig is not None and for_sig != -1:
521         s += int_to_hex(1, 4)                                   #  hash type
522     return s
523
524
525
526
527 def multisig_script(public_keys, num=None):
528     # supports only "2 of 2", and "2 of 3" transactions
529     n = len(public_keys)
530
531     if num is None:
532         num = n
533
534     assert num <= n and n <= 3 and n >= 2
535     
536     if num==2:
537         s = '52'
538     elif num == 3:
539         s = '53'
540     else:
541         raise
542     
543     for k in public_keys:
544         s += var_int(len(k)/2)
545         s += k
546     if n==2:
547         s += '52'
548     elif n==3:
549         s += '53'
550     else:
551         raise
552     s += 'ae'
553     return s
554
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         
566     @classmethod
567     def from_io(klass, inputs, outputs):
568         raw = raw_tx(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
569         self = klass(raw)
570         self.inputs = inputs
571         self.outputs = outputs
572         return self
573
574     def __str__(self):
575         return self.raw
576
577     def for_sig(self,i):
578         return raw_tx(self.inputs, self.outputs, for_sig = i)
579
580     def hash(self):
581         return Hash(self.raw.decode('hex') )[::-1].encode('hex')
582
583     def sign(self, private_keys):
584         import deserialize
585
586         for i in range(len(self.inputs)):
587             txin = self.inputs[i]
588
589             if txin.get('redeemScript'):
590                 # 1 parse the redeem script
591                 num, redeem_pubkeys = deserialize.parse_redeemScript(txin.get('redeemScript'))
592                 self.inputs[i]["pubkeys"] = redeem_pubkeys
593
594                 # build list of public/private keys
595                 keypairs = {}
596                 for sec in private_keys.values():
597                     compressed = is_compressed(sec)
598                     pkey = regenerate_key(sec)
599                     pubkey = GetPubKey(pkey.pubkey, compressed)
600                     keypairs[ pubkey.encode('hex') ] = sec
601
602                 # list of signatures
603                 signatures = txin.get("signatures",[])
604                 
605                 # check if we have a key corresponding to the redeem script
606                 for pubkey, privkey in keypairs.items():
607                     if pubkey in redeem_pubkeys:
608                         # add signature
609                         compressed = is_compressed(sec)
610                         pkey = regenerate_key(sec)
611                         secexp = pkey.secret
612                         private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
613                         public_key = private_key.get_verifying_key()
614
615                         tx = raw_tx( self.inputs, self.outputs, for_sig = i )
616                         sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
617                         assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
618                         signatures.append( sig.encode('hex') )
619
620                 # for p2sh, pubkeysig is a tuple (may be incomplete)
621                 self.inputs[i]["signatures"] = signatures
622
623             else:
624                 sec = private_keys[txin['address']]
625                 compressed = is_compressed(sec)
626                 pkey = regenerate_key(sec)
627                 secexp = pkey.secret
628
629                 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
630                 public_key = private_key.get_verifying_key()
631                 pkey = EC_KEY(secexp)
632                 pubkey = GetPubKey(pkey.pubkey, compressed)
633                 tx = raw_tx( self.inputs, self.outputs, for_sig = i )
634                 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
635                 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
636
637                 self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
638
639         self.raw = raw_tx( self.inputs, self.outputs )
640
641
642     def deserialize(self):
643         import deserialize
644         vds = deserialize.BCDataStream()
645         vds.write(self.raw.decode('hex'))
646         self.d = deserialize.parse_Transaction(vds)
647         return self.d
648     
649
650     def has_address(self, addr):
651         found = False
652         for txin in self.inputs:
653             if addr == txin.get('address'): 
654                 found = True
655                 break
656         for txout in self.outputs:
657             if addr == txout[0]:
658                 found = True
659                 break
660         return found
661
662
663     def get_value(self, addresses, prevout_values):
664         # return the balance for that tx
665         is_send = False
666         is_pruned = False
667         v_in = v_out = v_out_mine = 0
668
669         for item in self.inputs:
670             addr = item.get('address')
671             if addr in addresses:
672                 is_send = True
673                 key = item['prevout_hash']  + ':%d'%item['prevout_n']
674                 value = prevout_values.get( key )
675                 if value is None:
676                     is_pruned = True
677                 else:
678                     v_in += value
679             else:
680                 is_pruned = True
681                     
682         for item in self.outputs:
683             addr, value = item
684             v_out += value
685             if addr in addresses:
686                 v_out_mine += value
687
688         if not is_pruned:
689             # all inputs are mine:
690             fee = v_out - v_in
691             v = v_out_mine - v_in
692         else:
693             # some inputs are mine:
694             fee = None
695             if is_send:
696                 v = v_out_mine - v_out
697             else:
698                 # no input is mine
699                 v = v_out_mine
700             
701         return is_send, v, fee
702
703
704
705 def test_bip32():
706     seed = "ff000000000000000000000000000000".decode('hex')
707     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
708         
709     print "secret key", master_secret.encode('hex')
710     print "chain code", master_chain.encode('hex')
711
712     key_id = hash_160(master_public_key_compressed)
713     print "keyid", key_id.encode('hex')
714     print "base58"
715     print "address", hash_160_to_bc_address(key_id)
716     print "secret key", SecretToASecret(master_secret, True)
717
718     print "-- m/0 --"
719     k0, c0 = CKD(master_secret, master_chain, 0)
720     print "secret", k0.encode('hex')
721     print "chain", c0.encode('hex')
722     print "secret key", SecretToASecret(k0, True)
723     
724     K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
725     print "address", hash_160_to_bc_address(hash_160(K0_compressed))
726     
727     print "-- m/0/1 --"
728     K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
729     print "address", hash_160_to_bc_address(hash_160(K01_compressed))
730     
731     print "-- m/0/1/3 --"
732     K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
733     print "address", hash_160_to_bc_address(hash_160(K013_compressed))
734     
735     print "-- m/0/1/3/7 --"
736     K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
737     print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
738         
739
740 def test_p2sh():
741
742     print "2 of 2"
743     pubkeys = ["04e89a79651522201d756f14b1874ae49139cc984e5782afeca30ffe84e5e6b2cfadcfe9875c490c8a1a05a4debd715dd57471af8886ab5dfbb3959d97f087f77a",
744                "0455cf4a3ab68a011b18cb0a86aae2b8e9cad6c6355476de05247c57a9632d127084ac7630ad89893b43c486c5a9f7ec6158fb0feb708fa9255d5c4d44bc0858f8"]
745     s = multisig_script(pubkeys)
746     print "address", hash_160_to_bc_address(hash_160(s.decode('hex')), 5)
747
748
749     print "Gavin's tutorial: redeem p2sh:  http://blockchain.info/tx-index/30888901"
750     pubkey1 = "0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"
751     pubkey2 = "04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"
752     pubkey3 = "048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"
753     pubkeys = [pubkey1, pubkey2, pubkey3]
754
755     tx = Transaction.from_io(
756         [{'tx_hash':'3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac', 'index':0,
757           'raw_output_script':'a914f815b036d9bbbce5e9f2a00abd1bf3dc91e9551087', 'redeemScript':multisig_script(pubkeys, 2)}],
758         [('1GtpSrGhRGY5kkrNz4RykoqRQoJuG2L6DS',1000000)])
759
760     tx_for_sig = tx.for_sig(0)
761     print "tx for sig", tx_for_sig
762
763     signature1 = "304502200187af928e9d155c4b1ac9c1c9118153239aba76774f775d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1bbdaaba4e50eb078f39e3d78"
764     signature2 = "30440220795f0f4f5941a77ae032ecb9e33753788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e27038e945bc9db59c732728a383a6f1ed2fb99da7a4"
765
766     for pubkey in pubkeys:
767         import traceback, sys
768
769         public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
770
771         try:
772             public_key.verify_digest( signature1.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
773             print True
774         except ecdsa.keys.BadSignatureError:
775             #traceback.print_exc(file=sys.stdout)
776             print False
777
778         try:
779             public_key.verify_digest( signature2.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
780             print True
781         except ecdsa.keys.BadSignatureError:
782             #traceback.print_exc(file=sys.stdout)
783             print False
784
785 if __name__ == '__main__':
786     #test_bip32()
787     test_p2sh()
788