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