fix #676
[electrum-nvc.git] / lib / bitcoin.py
1 # -*- coding: utf-8 -*-
2 #!/usr/bin/env python
3 #
4 # Electrum - lightweight Bitcoin client
5 # Copyright (C) 2011 thomasv@gitorious
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 import hashlib, base64, ecdsa, re
22 import hmac
23 from util import print_error
24
25 def rev_hex(s):
26     return s.decode('hex')[::-1].encode('hex')
27
28 def int_to_hex(i, length=1):
29     s = hex(i)[2:].rstrip('L')
30     s = "0"*(2*length - len(s)) + s
31     return rev_hex(s)
32
33 def var_int(i):
34     # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
35     if i<0xfd:
36         return int_to_hex(i)
37     elif i<=0xffff:
38         return "fd"+int_to_hex(i,2)
39     elif i<=0xffffffff:
40         return "fe"+int_to_hex(i,4)
41     else:
42         return "ff"+int_to_hex(i,8)
43
44 def op_push(i):
45     if i<0x4c:
46         return int_to_hex(i)
47     elif i<0xff:
48         return '4c' + int_to_hex(i)
49     elif i<0xffff:
50         return '4d' + int_to_hex(i,2)
51     else:
52         return '4e' + int_to_hex(i,4)
53     
54
55
56 def sha256(x):
57     return hashlib.sha256(x).digest()
58
59 def Hash(x):
60     if type(x) is unicode: x=x.encode('utf-8')
61     return sha256(sha256(x))
62
63 hash_encode = lambda x: x[::-1].encode('hex')
64 hash_decode = lambda x: x.decode('hex')[::-1]
65 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
66
67 def mnemonic_to_seed(mnemonic, passphrase):
68     from pbkdf2 import PBKDF2
69     import hmac
70     PBKDF2_ROUNDS = 2048
71     return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
72
73 from version import SEED_PREFIX
74 is_new_seed = lambda x: hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')[0:2].startswith(SEED_PREFIX)
75
76 def is_old_seed(seed):
77     import mnemonic
78     words = seed.strip().split()
79     try:
80         mnemonic.mn_decode(words)
81         uses_electrum_words = True
82     except Exception:
83         uses_electrum_words = False
84
85     try:
86         seed.decode('hex')
87         is_hex = (len(seed) == 32)
88     except Exception:
89         is_hex = False
90          
91     return is_hex or (uses_electrum_words and len(words) == 12)
92
93
94 # pywallet openssl private key implementation
95
96 def i2d_ECPrivateKey(pkey, compressed=False):
97     if compressed:
98         key = '3081d30201010420' + \
99               '%064x' % pkey.secret + \
100               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
101               '%064x' % _p + \
102               '3006040100040107042102' + \
103               '%064x' % _Gx + \
104               '022100' + \
105               '%064x' % _r + \
106               '020101a124032200'
107     else:
108         key = '308201130201010420' + \
109               '%064x' % pkey.secret + \
110               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
111               '%064x' % _p + \
112               '3006040100040107044104' + \
113               '%064x' % _Gx + \
114               '%064x' % _Gy + \
115               '022100' + \
116               '%064x' % _r + \
117               '020101a144034200'
118         
119     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
120     
121 def i2o_ECPublicKey(pubkey, compressed=False):
122     # public keys are 65 bytes long (520 bits)
123     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
124     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
125     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
126     if compressed:
127         if pubkey.point.y() & 1:
128             key = '03' + '%064x' % pubkey.point.x()
129         else:
130             key = '02' + '%064x' % pubkey.point.x()
131     else:
132         key = '04' + \
133               '%064x' % pubkey.point.x() + \
134               '%064x' % pubkey.point.y()
135             
136     return key.decode('hex')
137             
138 # end pywallet openssl private key implementation
139
140                                                 
141             
142 ############ functions from pywallet ##################### 
143
144 def hash_160(public_key):
145     try:
146         md = hashlib.new('ripemd160')
147         md.update(sha256(public_key))
148         return md.digest()
149     except Exception:
150         import ripemd
151         md = ripemd.new(sha256(public_key))
152         return md.digest()
153
154
155 def public_key_to_bc_address(public_key):
156     h160 = hash_160(public_key)
157     return hash_160_to_bc_address(h160)
158
159 def hash_160_to_bc_address(h160, addrtype = 0):
160     vh160 = chr(addrtype) + h160
161     h = Hash(vh160)
162     addr = vh160 + h[0:4]
163     return b58encode(addr)
164
165 def bc_address_to_hash_160(addr):
166     bytes = b58decode(addr, 25)
167     return ord(bytes[0]), bytes[1:21]
168
169
170 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
171 __b58base = len(__b58chars)
172
173 def b58encode(v):
174     """ encode v, which is a string of bytes, to base58."""
175
176     long_value = 0L
177     for (i, c) in enumerate(v[::-1]):
178         long_value += (256**i) * ord(c)
179
180     result = ''
181     while long_value >= __b58base:
182         div, mod = divmod(long_value, __b58base)
183         result = __b58chars[mod] + result
184         long_value = div
185     result = __b58chars[long_value] + result
186
187     # Bitcoin does a little leading-zero-compression:
188     # leading 0-bytes in the input become leading-1s
189     nPad = 0
190     for c in v:
191         if c == '\0': nPad += 1
192         else: break
193
194     return (__b58chars[0]*nPad) + result
195
196 def b58decode(v, length):
197     """ decode v into a string of len bytes."""
198     long_value = 0L
199     for (i, c) in enumerate(v[::-1]):
200         long_value += __b58chars.find(c) * (__b58base**i)
201
202     result = ''
203     while long_value >= 256:
204         div, mod = divmod(long_value, 256)
205         result = chr(mod) + result
206         long_value = div
207     result = chr(long_value) + result
208
209     nPad = 0
210     for c in v:
211         if c == __b58chars[0]: nPad += 1
212         else: break
213
214     result = chr(0)*nPad + result
215     if length is not None and len(result) != length:
216         return None
217
218     return result
219
220
221 def EncodeBase58Check(vchIn):
222     hash = Hash(vchIn)
223     return b58encode(vchIn + hash[0:4])
224
225 def DecodeBase58Check(psz):
226     vchRet = b58decode(psz, None)
227     key = vchRet[0:-4]
228     csum = vchRet[-4:]
229     hash = Hash(key)
230     cs32 = hash[0:4]
231     if cs32 != csum:
232         return None
233     else:
234         return key
235
236 def PrivKeyToSecret(privkey):
237     return privkey[9:9+32]
238
239 def SecretToASecret(secret, compressed=False, addrtype=0):
240     vchIn = chr((addrtype+128)&255) + secret
241     if compressed: vchIn += '\01'
242     return EncodeBase58Check(vchIn)
243
244 def ASecretToSecret(key, addrtype=0):
245     vch = DecodeBase58Check(key)
246     if vch and vch[0] == chr((addrtype+128)&255):
247         return vch[1:]
248     else:
249         return False
250
251 def regenerate_key(sec):
252     b = ASecretToSecret(sec)
253     if not b:
254         return False
255     b = b[0:32]
256     return EC_KEY(b)
257
258 def GetPubKey(pubkey, compressed=False):
259     return i2o_ECPublicKey(pubkey, compressed)
260
261 def GetPrivKey(pkey, compressed=False):
262     return i2d_ECPrivateKey(pkey, compressed)
263
264 def GetSecret(pkey):
265     return ('%064x' % pkey.secret).decode('hex')
266
267 def is_compressed(sec):
268     b = ASecretToSecret(sec)
269     return len(b) == 33
270
271
272 def public_key_from_private_key(sec):
273     # rebuild public key from private key, compressed or uncompressed
274     pkey = regenerate_key(sec)
275     assert pkey
276     compressed = is_compressed(sec)
277     public_key = GetPubKey(pkey.pubkey, compressed)
278     return public_key.encode('hex')
279
280
281 def address_from_private_key(sec):
282     public_key = public_key_from_private_key(sec)
283     address = public_key_to_bc_address(public_key.decode('hex'))
284     return address
285
286
287 def is_valid(addr):
288     return is_address(addr)
289
290
291 def is_address(addr):
292     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
293     if not ADDRESS_RE.match(addr): return False
294     try:
295         addrtype, h = bc_address_to_hash_160(addr)
296     except Exception:
297         return False
298     return addr == hash_160_to_bc_address(h, addrtype)
299
300
301 def is_private_key(key):
302     try:
303         k = ASecretToSecret(key) 
304         return k is not False
305     except:
306         return False
307
308
309 ########### end pywallet functions #######################
310
311 try:
312     from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
313 except Exception:
314     print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
315     exit()
316
317 from ecdsa.curves import SECP256k1
318 from ecdsa.ellipticcurve import Point
319 from ecdsa.util import string_to_number, number_to_string
320
321 def msg_magic(message):
322     varint = var_int(len(message))
323     encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
324     return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
325
326
327 def verify_message(address, signature, message):
328     try:
329         EC_KEY.verify_message(address, signature, message)
330         return True
331     except Exception as e:
332         print_error("Verification error: {0}".format(e))
333         return False
334
335
336 def encrypt_message(message, pubkey):
337     return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
338
339
340 def chunks(l, n):
341     return [l[i:i+n] for i in xrange(0, len(l), n)]
342
343
344 def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
345     _p = curved.p()
346     _a = curved.a()
347     _b = curved.b()
348     for offset in range(128):
349         Mx = x + offset
350         My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
351         My = pow(My2, (_p+1)/4, _p )
352
353         if curved.contains_point(Mx,My):
354             if odd == bool(My&1):
355                 return [My,offset]
356             return [_p-My,offset]
357     raise Exception('ECC_YfromX: No Y found')
358
359 def private_header(msg,v):
360     assert v<1, "Can't write version %d private header"%v
361     r = ''
362     if v==0:
363         r += ('%08x'%len(msg)).decode('hex')
364         r += sha256(msg)[:2]
365     return ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
366
367 def public_header(pubkey,v):
368     assert v<1, "Can't write version %d public header"%v
369     r = ''
370     if v==0:
371         r = sha256(pubkey)[:2]
372     return '\x6a\x6a' + ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
373
374
375 def negative_point(P):
376     return Point( P.curve(), P.x(), -P.y(), P.order() )
377
378
379 def point_to_ser(P, comp=True ):
380     if comp:
381         return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
382     return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
383
384
385 def ser_to_point(Aser):
386     curve = curve_secp256k1
387     generator = generator_secp256k1
388     _r  = generator.order()
389     assert Aser[0] in ['\x02','\x03','\x04']
390     if Aser[0] == '\x04':
391         return Point( curve, str_to_long(Aser[1:33]), str_to_long(Aser[33:]), _r )
392     Mx = string_to_number(Aser[1:])
393     return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
394
395
396
397 class EC_KEY(object):
398     def __init__( self, k ):
399         secret = string_to_number(k)
400         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
401         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
402         self.secret = secret
403
404     def get_public_key(self, compressed=True):
405         return point_to_ser(self.pubkey.point, compressed).encode('hex')
406
407     def sign_message(self, message, compressed, address):
408         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
409         public_key = private_key.get_verifying_key()
410         signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
411         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
412         for i in range(4):
413             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
414             try:
415                 self.verify_message( address, sig, message)
416                 return sig
417             except Exception:
418                 continue
419         else:
420             raise Exception("error: cannot sign message")
421
422
423     @classmethod
424     def verify_message(self, address, signature, message):
425         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
426         from ecdsa import numbertheory, util
427         import msqr
428         curve = curve_secp256k1
429         G = generator_secp256k1
430         order = G.order()
431         # extract r,s from signature
432         sig = base64.b64decode(signature)
433         if len(sig) != 65: raise Exception("Wrong encoding")
434         r,s = util.sigdecode_string(sig[1:], order)
435         nV = ord(sig[0])
436         if nV < 27 or nV >= 35:
437             raise Exception("Bad encoding")
438         if nV >= 31:
439             compressed = True
440             nV -= 4
441         else:
442             compressed = False
443
444         recid = nV - 27
445         # 1.1
446         x = r + (recid/2) * order
447         # 1.3
448         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
449         beta = msqr.modular_sqrt(alpha, curve.p())
450         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
451         # 1.4 the constructor checks that nR is at infinity
452         R = Point(curve, x, y, order)
453         # 1.5 compute e from message:
454         h = Hash( msg_magic(message) )
455         e = string_to_number(h)
456         minus_e = -e % order
457         # 1.6 compute Q = r^-1 (sR - eG)
458         inv_r = numbertheory.inverse_mod(r,order)
459         Q = inv_r * ( s * R + minus_e * G )
460         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
461         # check that Q is the public key
462         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
463         # check that we get the original signing address
464         addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
465         if address != addr:
466             raise Exception("Bad signature")
467
468
469     # ecdsa encryption/decryption methods
470     # credits: jackjack, https://github.com/jackjack-jj/jeeq
471
472     @classmethod
473     def encrypt_message(self, message, pubkey):
474         generator = generator_secp256k1
475         curved = curve_secp256k1
476         r = ''
477         msg = private_header(message,0) + message
478         msg = msg + ('\x00'*( 32-(len(msg)%32) ))
479         msgs = chunks(msg,32)
480
481         _r  = generator.order()
482         str_to_long = string_to_number
483
484         P = generator
485         pk = ser_to_point(pubkey)
486
487         for i in range(len(msgs)):
488             n = ecdsa.util.randrange( pow(2,256) )
489             Mx = str_to_long(msgs[i])
490             My, xoffset = ECC_YfromX(Mx, curved)
491             M = Point( curved, Mx+xoffset, My, _r )
492             T = P*n
493             U = pk*n + M
494             toadd = point_to_ser(T) + point_to_ser(U)
495             toadd = chr(ord(toadd[0])-2 + 2*xoffset) + toadd[1:]
496             r += toadd
497
498         return base64.b64encode(public_header(pubkey,0) + r)
499
500
501     def decrypt_message(self, enc):
502         G = generator_secp256k1
503         curved = curve_secp256k1
504         pvk = self.secret
505         pubkeys = [point_to_ser(G*pvk,True), point_to_ser(G*pvk,False)]
506         enc = base64.b64decode(enc)
507         str_to_long = string_to_number
508
509         assert enc[:2]=='\x6a\x6a'
510
511         phv = str_to_long(enc[2])
512         assert phv==0, "Can't read version %d public header"%phv
513         hs = str_to_long(enc[3:5])
514         public_header=enc[5:5+hs]
515         checksum_pubkey=public_header[:2]
516         address=filter(lambda x:sha256(x)[:2]==checksum_pubkey, pubkeys)
517         assert len(address)>0, 'Bad private key'
518         address=address[0]
519         enc=enc[5+hs:]
520         r = ''
521         for Tser,User in map(lambda x:[x[:33],x[33:]], chunks(enc,66)):
522             ots = ord(Tser[0])
523             xoffset = ots>>1
524             Tser = chr(2+(ots&1))+Tser[1:]
525             T = ser_to_point(Tser)
526             U = ser_to_point(User)
527             V = T*pvk
528             Mcalc = U + negative_point(V)
529             r += ('%064x'%(Mcalc.x()-xoffset)).decode('hex')
530
531         pvhv = str_to_long(r[0])
532         assert pvhv==0, "Can't read version %d private header"%pvhv
533         phs = str_to_long(r[1:3])
534         private_header = r[3:3+phs]
535         size = str_to_long(private_header[:4])
536         checksum = private_header[4:6]
537         r = r[3+phs:]
538
539         msg = r[:size]
540         hashmsg = sha256(msg)[:2]
541         checksumok = hashmsg==checksum
542
543         return [msg, checksumok, address]
544
545
546
547
548
549 ###################################### BIP32 ##############################
550
551 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
552 BIP32_PRIME = 0x80000000
553
554
555 def get_pubkeys_from_secret(secret):
556     # public key
557     private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
558     public_key = private_key.get_verifying_key()
559     K = public_key.to_string()
560     K_compressed = GetPubKey(public_key.pubkey,True)
561     return K, K_compressed
562
563
564 # Child private key derivation function (from master private key)
565 # k = master private key (32 bytes)
566 # c = master chain code (extra entropy for key derivation) (32 bytes)
567 # n = the index of the key we want to derive. (only 32 bits will be used)
568 # If n is negative (i.e. the 32nd bit is set), the resulting private key's
569 #  corresponding public key can NOT be determined without the master private key.
570 # However, if n is positive, the resulting private key's corresponding
571 #  public key can be determined without the master private key.
572 def CKD_priv(k, c, n):
573     is_prime = n & BIP32_PRIME
574     return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
575
576 def _CKD_priv(k, c, s, is_prime):
577     import hmac
578     from ecdsa.util import string_to_number, number_to_string
579     order = generator_secp256k1.order()
580     keypair = EC_KEY(k)
581     cK = GetPubKey(keypair.pubkey,True)
582     data = chr(0) + k + s if is_prime else cK + s
583     I = hmac.new(c, data, hashlib.sha512).digest()
584     k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
585     c_n = I[32:]
586     return k_n, c_n
587
588 # Child public key derivation function (from public key only)
589 # K = master public key 
590 # c = master chain code
591 # n = index of key we want to derive
592 # This function allows us to find the nth public key, as long as n is 
593 #  non-negative. If n is negative, we need the master private key to find it.
594 def CKD_pub(cK, c, n):
595     if n & BIP32_PRIME: raise
596     return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
597
598 # helper function, callable with arbitrary string
599 def _CKD_pub(cK, c, s):
600     import hmac
601     from ecdsa.util import string_to_number, number_to_string
602     order = generator_secp256k1.order()
603     I = hmac.new(c, cK + s, hashlib.sha512).digest()
604     curve = SECP256k1
605     pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
606     public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
607     c_n = I[32:]
608     cK_n = GetPubKey(public_key.pubkey,True)
609     return cK_n, c_n
610
611
612
613 def deserialize_xkey(xkey):
614     xkey = DecodeBase58Check(xkey) 
615     assert len(xkey) == 78
616     assert xkey[0:4].encode('hex') in ["0488ade4", "0488b21e"]
617     depth = ord(xkey[4])
618     fingerprint = xkey[5:9]
619     child_number = xkey[9:13]
620     c = xkey[13:13+32]
621     if xkey[0:4].encode('hex') == "0488ade4":
622         K_or_k = xkey[13+33:]
623     else:
624         K_or_k = xkey[13+32:]
625     return depth, fingerprint, child_number, c, K_or_k
626
627
628
629 def bip32_root(seed):
630     import hmac
631     seed = seed.decode('hex')        
632     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
633     master_k = I[0:32]
634     master_c = I[32:]
635     K, cK = get_pubkeys_from_secret(master_k)
636     xprv = ("0488ADE4" + "00" + "00000000" + "00000000").decode("hex") + master_c + chr(0) + master_k
637     xpub = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + master_c + cK
638     return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
639
640
641
642 def bip32_private_derivation(xprv, branch, sequence):
643     depth, fingerprint, child_number, c, k = deserialize_xkey(xprv)
644     assert sequence.startswith(branch)
645     sequence = sequence[len(branch):]
646     for n in sequence.split('/'):
647         if n == '': continue
648         i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
649         parent_k = k
650         k, c = CKD_priv(k, c, i)
651         depth += 1
652
653     _, parent_cK = get_pubkeys_from_secret(parent_k)
654     fingerprint = hash_160(parent_cK)[0:4]
655     child_number = ("%08X"%i).decode('hex')
656     K, cK = get_pubkeys_from_secret(k)
657     xprv = "0488ADE4".decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k
658     xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
659     return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
660
661
662
663 def bip32_public_derivation(xpub, branch, sequence):
664     depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub)
665     assert sequence.startswith(branch)
666     sequence = sequence[len(branch):]
667     for n in sequence.split('/'):
668         if n == '': continue
669         i = int(n)
670         parent_cK = cK
671         cK, c = CKD_pub(cK, c, i)
672         depth += 1
673
674     fingerprint = hash_160(parent_cK)[0:4]
675     child_number = ("%08X"%i).decode('hex')
676     xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
677     return EncodeBase58Check(xpub)
678
679
680
681
682 def bip32_private_key(sequence, k, chain):
683     for i in sequence:
684         k, chain = CKD_priv(k, chain, i)
685     return SecretToASecret(k, True)
686
687
688
689
690 ################################## transactions
691
692 MIN_RELAY_TX_FEE = 1000
693
694
695
696 def test_bip32(seed, sequence):
697     """
698     run a test vector,
699     see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
700     """
701
702     xprv, xpub = bip32_root(seed)
703     print xpub
704     print xprv
705
706     assert sequence[0:2] == "m/"
707     path = 'm'
708     sequence = sequence[2:]
709     for n in sequence.split('/'):
710         child_path = path + '/' + n
711         if n[-1] != "'":
712             xpub2 = bip32_public_derivation(xpub, path, child_path)
713         xprv, xpub = bip32_private_derivation(xprv, path, child_path)
714         if n[-1] != "'":
715             assert xpub == xpub2
716         
717
718         path = child_path
719         print path
720         print xpub
721         print xprv
722
723     print "----"
724
725         
726
727 def test_crypto():
728
729     G = generator_secp256k1
730     _r  = G.order()
731     pvk = ecdsa.util.randrange( pow(2,256) ) %_r
732
733     Pub = pvk*G
734     pubkey_c = point_to_ser(Pub,True)
735     pubkey_u = point_to_ser(Pub,False)
736     addr_c = public_key_to_bc_address(pubkey_c)
737     addr_u = public_key_to_bc_address(pubkey_u)
738
739     print "Private key            ", '%064x'%pvk
740     print "Compressed public key  ", pubkey_c.encode('hex')
741     print "Uncompressed public key", pubkey_u.encode('hex')
742
743     message = "Chancellor on brink of second bailout for banks"
744     enc = EC_KEY.encrypt_message(message,pubkey_c)
745     eck = EC_KEY(number_to_string(pvk,_r))
746     dec = eck.decrypt_message(enc)
747     print "decrypted", dec
748
749     signature = eck.sign_message(message, True, addr_c)
750     print signature
751     EC_KEY.verify_message(addr_c, signature, message)
752
753
754 if __name__ == '__main__':
755     #test_crypto()
756     test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
757     test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
758
759