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