move tests to unittest format
[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 import aes
24 from util import print_error
25
26 # AES encryption
27 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
28 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
29
30 def pw_encode(s, password):
31     if password:
32         secret = Hash(password)
33         return EncodeAES(secret, s.encode("utf8"))
34     else:
35         return s
36
37 def pw_decode(s, password):
38     if password is not None:
39         secret = Hash(password)
40         try:
41             d = DecodeAES(secret, s).decode("utf8")
42         except Exception:
43             raise Exception('Invalid password')
44         return d
45     else:
46         return s
47
48
49
50
51
52 def rev_hex(s):
53     return s.decode('hex')[::-1].encode('hex')
54
55 def int_to_hex(i, length=1):
56     s = hex(i)[2:].rstrip('L')
57     s = "0"*(2*length - len(s)) + s
58     return rev_hex(s)
59
60 def var_int(i):
61     # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
62     if i<0xfd:
63         return int_to_hex(i)
64     elif i<=0xffff:
65         return "fd"+int_to_hex(i,2)
66     elif i<=0xffffffff:
67         return "fe"+int_to_hex(i,4)
68     else:
69         return "ff"+int_to_hex(i,8)
70
71 def op_push(i):
72     if i<0x4c:
73         return int_to_hex(i)
74     elif i<0xff:
75         return '4c' + int_to_hex(i)
76     elif i<0xffff:
77         return '4d' + int_to_hex(i,2)
78     else:
79         return '4e' + int_to_hex(i,4)
80     
81
82
83 def sha256(x):
84     return hashlib.sha256(x).digest()
85
86 def Hash(x):
87     if type(x) is unicode: x=x.encode('utf-8')
88     return sha256(sha256(x))
89
90 hash_encode = lambda x: x[::-1].encode('hex')
91 hash_decode = lambda x: x.decode('hex')[::-1]
92 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
93
94 def mnemonic_to_seed(mnemonic, passphrase):
95     from pbkdf2 import PBKDF2
96     import hmac
97     PBKDF2_ROUNDS = 2048
98     return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
99
100 from version import SEED_PREFIX
101 is_new_seed = lambda x: hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')[0:2].startswith(SEED_PREFIX)
102
103 def is_old_seed(seed):
104     import mnemonic
105     words = seed.strip().split()
106     try:
107         mnemonic.mn_decode(words)
108         uses_electrum_words = True
109     except Exception:
110         uses_electrum_words = False
111
112     try:
113         seed.decode('hex')
114         is_hex = (len(seed) == 32)
115     except Exception:
116         is_hex = False
117          
118     return is_hex or (uses_electrum_words and len(words) == 12)
119
120
121 # pywallet openssl private key implementation
122
123 def i2d_ECPrivateKey(pkey, compressed=False):
124     if compressed:
125         key = '3081d30201010420' + \
126               '%064x' % pkey.secret + \
127               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
128               '%064x' % _p + \
129               '3006040100040107042102' + \
130               '%064x' % _Gx + \
131               '022100' + \
132               '%064x' % _r + \
133               '020101a124032200'
134     else:
135         key = '308201130201010420' + \
136               '%064x' % pkey.secret + \
137               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
138               '%064x' % _p + \
139               '3006040100040107044104' + \
140               '%064x' % _Gx + \
141               '%064x' % _Gy + \
142               '022100' + \
143               '%064x' % _r + \
144               '020101a144034200'
145         
146     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
147     
148 def i2o_ECPublicKey(pubkey, compressed=False):
149     # public keys are 65 bytes long (520 bits)
150     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
151     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
152     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
153     if compressed:
154         if pubkey.point.y() & 1:
155             key = '03' + '%064x' % pubkey.point.x()
156         else:
157             key = '02' + '%064x' % pubkey.point.x()
158     else:
159         key = '04' + \
160               '%064x' % pubkey.point.x() + \
161               '%064x' % pubkey.point.y()
162             
163     return key.decode('hex')
164             
165 # end pywallet openssl private key implementation
166
167                                                 
168             
169 ############ functions from pywallet ##################### 
170
171 def hash_160(public_key):
172     try:
173         md = hashlib.new('ripemd160')
174         md.update(sha256(public_key))
175         return md.digest()
176     except Exception:
177         import ripemd
178         md = ripemd.new(sha256(public_key))
179         return md.digest()
180
181
182 def public_key_to_bc_address(public_key):
183     h160 = hash_160(public_key)
184     return hash_160_to_bc_address(h160)
185
186 def hash_160_to_bc_address(h160, addrtype = 0):
187     vh160 = chr(addrtype) + h160
188     h = Hash(vh160)
189     addr = vh160 + h[0:4]
190     return b58encode(addr)
191
192 def bc_address_to_hash_160(addr):
193     bytes = b58decode(addr, 25)
194     return ord(bytes[0]), bytes[1:21]
195
196
197 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
198 __b58base = len(__b58chars)
199
200 def b58encode(v):
201     """ encode v, which is a string of bytes, to base58."""
202
203     long_value = 0L
204     for (i, c) in enumerate(v[::-1]):
205         long_value += (256**i) * ord(c)
206
207     result = ''
208     while long_value >= __b58base:
209         div, mod = divmod(long_value, __b58base)
210         result = __b58chars[mod] + result
211         long_value = div
212     result = __b58chars[long_value] + result
213
214     # Bitcoin does a little leading-zero-compression:
215     # leading 0-bytes in the input become leading-1s
216     nPad = 0
217     for c in v:
218         if c == '\0': nPad += 1
219         else: break
220
221     return (__b58chars[0]*nPad) + result
222
223 def b58decode(v, length):
224     """ decode v into a string of len bytes."""
225     long_value = 0L
226     for (i, c) in enumerate(v[::-1]):
227         long_value += __b58chars.find(c) * (__b58base**i)
228
229     result = ''
230     while long_value >= 256:
231         div, mod = divmod(long_value, 256)
232         result = chr(mod) + result
233         long_value = div
234     result = chr(long_value) + result
235
236     nPad = 0
237     for c in v:
238         if c == __b58chars[0]: nPad += 1
239         else: break
240
241     result = chr(0)*nPad + result
242     if length is not None and len(result) != length:
243         return None
244
245     return result
246
247
248 def EncodeBase58Check(vchIn):
249     hash = Hash(vchIn)
250     return b58encode(vchIn + hash[0:4])
251
252 def DecodeBase58Check(psz):
253     vchRet = b58decode(psz, None)
254     key = vchRet[0:-4]
255     csum = vchRet[-4:]
256     hash = Hash(key)
257     cs32 = hash[0:4]
258     if cs32 != csum:
259         return None
260     else:
261         return key
262
263 def PrivKeyToSecret(privkey):
264     return privkey[9:9+32]
265
266 def SecretToASecret(secret, compressed=False, addrtype=0):
267     vchIn = chr((addrtype+128)&255) + secret
268     if compressed: vchIn += '\01'
269     return EncodeBase58Check(vchIn)
270
271 def ASecretToSecret(key, addrtype=0):
272     vch = DecodeBase58Check(key)
273     if vch and vch[0] == chr((addrtype+128)&255):
274         return vch[1:]
275     else:
276         return False
277
278 def regenerate_key(sec):
279     b = ASecretToSecret(sec)
280     if not b:
281         return False
282     b = b[0:32]
283     return EC_KEY(b)
284
285 def GetPubKey(pubkey, compressed=False):
286     return i2o_ECPublicKey(pubkey, compressed)
287
288 def GetPrivKey(pkey, compressed=False):
289     return i2d_ECPrivateKey(pkey, compressed)
290
291 def GetSecret(pkey):
292     return ('%064x' % pkey.secret).decode('hex')
293
294 def is_compressed(sec):
295     b = ASecretToSecret(sec)
296     return len(b) == 33
297
298
299 def public_key_from_private_key(sec):
300     # rebuild public key from private key, compressed or uncompressed
301     pkey = regenerate_key(sec)
302     assert pkey
303     compressed = is_compressed(sec)
304     public_key = GetPubKey(pkey.pubkey, compressed)
305     return public_key.encode('hex')
306
307
308 def address_from_private_key(sec):
309     public_key = public_key_from_private_key(sec)
310     address = public_key_to_bc_address(public_key.decode('hex'))
311     return address
312
313
314 def is_valid(addr):
315     return is_address(addr)
316
317
318 def is_address(addr):
319     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
320     if not ADDRESS_RE.match(addr): return False
321     try:
322         addrtype, h = bc_address_to_hash_160(addr)
323     except Exception:
324         return False
325     return addr == hash_160_to_bc_address(h, addrtype)
326
327
328 def is_private_key(key):
329     try:
330         k = ASecretToSecret(key) 
331         return k is not False
332     except:
333         return False
334
335
336 ########### end pywallet functions #######################
337
338 try:
339     from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
340 except Exception:
341     print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
342     exit()
343
344 from ecdsa.curves import SECP256k1
345 from ecdsa.ellipticcurve import Point
346 from ecdsa.util import string_to_number, number_to_string
347
348 def msg_magic(message):
349     varint = var_int(len(message))
350     encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
351     return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
352
353
354 def verify_message(address, signature, message):
355     try:
356         EC_KEY.verify_message(address, signature, message)
357         return True
358     except Exception as e:
359         print_error("Verification error: {0}".format(e))
360         return False
361
362
363 def encrypt_message(message, pubkey):
364     return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
365
366
367 def chunks(l, n):
368     return [l[i:i+n] for i in xrange(0, len(l), n)]
369
370
371 def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
372     _p = curved.p()
373     _a = curved.a()
374     _b = curved.b()
375     for offset in range(128):
376         Mx = x + offset
377         My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
378         My = pow(My2, (_p+1)/4, _p )
379
380         if curved.contains_point(Mx,My):
381             if odd == bool(My&1):
382                 return [My,offset]
383             return [_p-My,offset]
384     raise Exception('ECC_YfromX: No Y found')
385
386
387 def negative_point(P):
388     return Point( P.curve(), P.x(), -P.y(), P.order() )
389
390
391 def point_to_ser(P, comp=True ):
392     if comp:
393         return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
394     return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
395
396
397 def ser_to_point(Aser):
398     curve = curve_secp256k1
399     generator = generator_secp256k1
400     _r  = generator.order()
401     assert Aser[0] in ['\x02','\x03','\x04']
402     if Aser[0] == '\x04':
403         return Point( curve, string_to_number(Aser[1:33]), string_to_number(Aser[33:]), _r )
404     Mx = string_to_number(Aser[1:])
405     return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
406
407
408
409 class MyVerifyingKey(ecdsa.VerifyingKey):
410     @classmethod
411     def from_signature(klass, sig, recid, h, curve):
412         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """
413         from ecdsa import util, numbertheory
414         import msqr
415         curveFp = curve.curve
416         G = curve.generator
417         order = G.order()
418         # extract r,s from signature
419         r, s = util.sigdecode_string(sig, order)
420         # 1.1
421         x = r + (recid/2) * order
422         # 1.3
423         alpha = ( x * x * x  + curveFp.a() * x + curveFp.b() ) % curveFp.p()
424         beta = msqr.modular_sqrt(alpha, curveFp.p())
425         y = beta if (beta - recid) % 2 == 0 else curveFp.p() - beta
426         # 1.4 the constructor checks that nR is at infinity
427         R = Point(curveFp, x, y, order)
428         # 1.5 compute e from message:
429         e = string_to_number(h)
430         minus_e = -e % order
431         # 1.6 compute Q = r^-1 (sR - eG)
432         inv_r = numbertheory.inverse_mod(r,order)
433         Q = inv_r * ( s * R + minus_e * G )
434         return klass.from_public_point( Q, curve )
435
436
437 class EC_KEY(object):
438     def __init__( self, k ):
439         secret = string_to_number(k)
440         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
441         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
442         self.secret = secret
443
444     def get_public_key(self, compressed=True):
445         return point_to_ser(self.pubkey.point, compressed).encode('hex')
446
447     def sign_message(self, message, compressed, address):
448         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
449         public_key = private_key.get_verifying_key()
450         signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
451         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
452         for i in range(4):
453             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
454             try:
455                 self.verify_message( address, sig, message)
456                 return sig
457             except Exception:
458                 continue
459         else:
460             raise Exception("error: cannot sign message")
461
462
463     @classmethod
464     def verify_message(self, address, signature, message):
465         sig = base64.b64decode(signature)
466         if len(sig) != 65: raise Exception("Wrong encoding")
467
468         nV = ord(sig[0])
469         if nV < 27 or nV >= 35:
470             raise Exception("Bad encoding")
471         if nV >= 31:
472             compressed = True
473             nV -= 4
474         else:
475             compressed = False
476
477         recid = nV - 27
478         h = Hash( msg_magic(message) )
479         public_key = MyVerifyingKey.from_signature( sig[1:], recid, h, curve = SECP256k1 )
480
481         # check public key
482         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
483
484         # check that we get the original signing address
485         addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
486         if address != addr:
487             raise Exception("Bad signature")
488
489
490     # ecies encryption/decryption methods; aes-256-cbc is used as the cipher; hmac-sha256 is used as the mac
491
492     @classmethod
493     def encrypt_message(self, message, pubkey):
494         
495         pk = ser_to_point(pubkey)
496         if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()):
497             raise Exception('invalid pubkey')
498         
499         ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2,256)), generator_secp256k1.order())
500         ephemeral = EC_KEY(ephemeral_exponent)
501         
502         ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x()
503         ecdh_key = ('%064x' % ecdh_key).decode('hex')
504         key = hashlib.sha512(ecdh_key).digest()
505         key_e, key_m = key[:32], key[32:]
506         
507         iv_ciphertext = aes.encryptData(key_e, message)
508
509         ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex')
510         encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext
511         mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()
512
513         return base64.b64encode(encrypted + mac)
514
515
516     def decrypt_message(self, encrypted):
517         
518         encrypted = base64.b64decode(encrypted)
519         
520         if len(encrypted) < 85:
521             raise Exception('invalid ciphertext: length')
522         
523         magic = encrypted[:4]
524         ephemeral_pubkey = encrypted[4:37]
525         iv_ciphertext = encrypted[37:-32]
526         mac = encrypted[-32:]
527         
528         if magic != 'BIE1':
529             raise Exception('invalid ciphertext: invalid magic bytes')
530         
531         try:
532             ephemeral_pubkey = ser_to_point(ephemeral_pubkey)
533         except AssertionError, e:
534             raise Exception('invalid ciphertext: invalid ephemeral pubkey')
535
536         if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()):
537             raise Exception('invalid ciphertext: invalid ephemeral pubkey')
538
539         ecdh_key = (ephemeral_pubkey * self.privkey.secret_multiplier).x()
540         ecdh_key = ('%064x' % ecdh_key).decode('hex')
541         key = hashlib.sha512(ecdh_key).digest()
542         key_e, key_m = key[:32], key[32:]
543         if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest():
544             raise Exception('invalid ciphertext: invalid mac')
545
546         return aes.decryptData(key_e, iv_ciphertext)
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 import unittest
697 class Test_bitcoin(unittest.TestCase):
698
699     def test_crypto(self):
700         for message in ["Chancellor on brink of second bailout for banks", chr(255)*512]:
701             self.do_test_crypto(message)
702
703     def do_test_crypto(self, message):
704         G = generator_secp256k1
705         _r  = G.order()
706         pvk = ecdsa.util.randrange( pow(2,256) ) %_r
707
708         Pub = pvk*G
709         pubkey_c = point_to_ser(Pub,True)
710         pubkey_u = point_to_ser(Pub,False)
711         addr_c = public_key_to_bc_address(pubkey_c)
712         addr_u = public_key_to_bc_address(pubkey_u)
713
714         print "Private key            ", '%064x'%pvk
715         eck = EC_KEY(number_to_string(pvk,_r))
716
717         print "Compressed public key  ", pubkey_c.encode('hex')
718         enc = EC_KEY.encrypt_message(message, pubkey_c)
719         dec = eck.decrypt_message(enc)
720         assert dec == message
721
722         print "Uncompressed public key", pubkey_u.encode('hex')
723         enc2 = EC_KEY.encrypt_message(message, pubkey_u)
724         dec2 = eck.decrypt_message(enc)
725         assert dec2 == message
726
727         signature = eck.sign_message(message, True, addr_c)
728         print signature
729         EC_KEY.verify_message(addr_c, signature, message)
730
731
732
733     def test_bip32(self):
734         # see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
735         xpub, xprv = self.do_test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
736         assert xpub == "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"
737         assert xprv == "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"
738
739         xpub, xprv = self.do_test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
740         assert xpub == "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"
741         assert xprv == "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"
742
743
744     def do_test_bip32(self, seed, sequence):
745         xprv, xpub = bip32_root(seed)
746         assert sequence[0:2] == "m/"
747         path = 'm'
748         sequence = sequence[2:]
749         for n in sequence.split('/'):
750             child_path = path + '/' + n
751             if n[-1] != "'":
752                 xpub2 = bip32_public_derivation(xpub, path, child_path)
753             xprv, xpub = bip32_private_derivation(xprv, path, child_path)
754             if n[-1] != "'":
755                 assert xpub == xpub2
756             path = child_path
757
758         return xpub, xprv
759
760
761
762
763 if __name__ == "__main__":
764     unittest.main()