enable bip32
[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 Hash(x):
57     if type(x) is unicode: x=x.encode('utf-8')
58     return hashlib.sha256(hashlib.sha256(x).digest()).digest()
59 hash_encode = lambda x: x[::-1].encode('hex')
60 hash_decode = lambda x: x.decode('hex')[::-1]
61
62 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
63 mnemonic_hash = lambda x: hmac_sha_512("Bitcoin mnemonic", x).encode('hex')
64 from version import SEED_PREFIX
65 is_seed = lambda x: hmac_sha_512("Seed version", x).encode('hex')[0:2].startswith(SEED_PREFIX)
66
67 # pywallet openssl private key implementation
68
69 def i2d_ECPrivateKey(pkey, compressed=False):
70     if compressed:
71         key = '3081d30201010420' + \
72               '%064x' % pkey.secret + \
73               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
74               '%064x' % _p + \
75               '3006040100040107042102' + \
76               '%064x' % _Gx + \
77               '022100' + \
78               '%064x' % _r + \
79               '020101a124032200'
80     else:
81         key = '308201130201010420' + \
82               '%064x' % pkey.secret + \
83               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
84               '%064x' % _p + \
85               '3006040100040107044104' + \
86               '%064x' % _Gx + \
87               '%064x' % _Gy + \
88               '022100' + \
89               '%064x' % _r + \
90               '020101a144034200'
91         
92     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
93     
94 def i2o_ECPublicKey(pubkey, compressed=False):
95     # public keys are 65 bytes long (520 bits)
96     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
97     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
98     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
99     if compressed:
100         if pubkey.point.y() & 1:
101             key = '03' + '%064x' % pubkey.point.x()
102         else:
103             key = '02' + '%064x' % pubkey.point.x()
104     else:
105         key = '04' + \
106               '%064x' % pubkey.point.x() + \
107               '%064x' % pubkey.point.y()
108             
109     return key.decode('hex')
110             
111 # end pywallet openssl private key implementation
112
113                                                 
114             
115 ############ functions from pywallet ##################### 
116
117 def hash_160(public_key):
118     try:
119         md = hashlib.new('ripemd160')
120         md.update(hashlib.sha256(public_key).digest())
121         return md.digest()
122     except Exception:
123         import ripemd
124         md = ripemd.new(hashlib.sha256(public_key).digest())
125         return md.digest()
126
127
128 def public_key_to_bc_address(public_key):
129     h160 = hash_160(public_key)
130     return hash_160_to_bc_address(h160)
131
132 def hash_160_to_bc_address(h160, addrtype = 0):
133     vh160 = chr(addrtype) + h160
134     h = Hash(vh160)
135     addr = vh160 + h[0:4]
136     return b58encode(addr)
137
138 def bc_address_to_hash_160(addr):
139     bytes = b58decode(addr, 25)
140     return ord(bytes[0]), bytes[1:21]
141
142 def encode_point(pubkey, compressed=False):
143     order = generator_secp256k1.order()
144     p = pubkey.pubkey.point
145     x_str = ecdsa.util.number_to_string(p.x(), order)
146     y_str = ecdsa.util.number_to_string(p.y(), order)
147     if compressed:
148         return chr(2 + (p.y() & 1)) + x_str
149     else:
150         return chr(4) + pubkey.to_string() #x_str + y_str
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     secret = int('0x' + b.encode('hex'), 16)
239     return EC_KEY(secret)
240
241 def GetPubKey(pubkey, compressed=False):
242     return i2o_ECPublicKey(pubkey, compressed)
243
244 def GetPrivKey(pkey, compressed=False):
245     return i2d_ECPrivateKey(pkey, compressed)
246
247 def GetSecret(pkey):
248     return ('%064x' % pkey.secret).decode('hex')
249
250 def is_compressed(sec):
251     b = ASecretToSecret(sec)
252     return len(b) == 33
253
254
255 def public_key_from_private_key(sec):
256     # rebuild public key from private key, compressed or uncompressed
257     pkey = regenerate_key(sec)
258     assert pkey
259     compressed = is_compressed(sec)
260     public_key = GetPubKey(pkey.pubkey, compressed)
261     return public_key.encode('hex')
262
263
264 def address_from_private_key(sec):
265     public_key = public_key_from_private_key(sec)
266     address = public_key_to_bc_address(public_key.decode('hex'))
267     return address
268
269
270 def is_valid(addr):
271     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
272     if not ADDRESS_RE.match(addr): return False
273     try:
274         addrtype, h = bc_address_to_hash_160(addr)
275     except Exception:
276         return False
277     return addr == hash_160_to_bc_address(h, addrtype)
278
279
280 ########### end pywallet functions #######################
281
282 try:
283     from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
284 except Exception:
285     print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
286     exit()
287 from ecdsa.curves import SECP256k1
288 from ecdsa.util import string_to_number, number_to_string
289
290 def msg_magic(message):
291     varint = var_int(len(message))
292     encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
293
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
307 class EC_KEY(object):
308     def __init__( self, secret ):
309         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
310         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
311         self.secret = secret
312
313     def sign_message(self, message, compressed, address):
314         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
315         public_key = private_key.get_verifying_key()
316         signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
317         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
318         for i in range(4):
319             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
320             try:
321                 self.verify_message( address, sig, message)
322                 return sig
323             except Exception:
324                 continue
325         else:
326             raise Exception("error: cannot sign message")
327
328     @classmethod
329     def verify_message(self, address, signature, message):
330         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
331         from ecdsa import numbertheory, ellipticcurve, util
332         import msqr
333         curve = curve_secp256k1
334         G = generator_secp256k1
335         order = G.order()
336         # extract r,s from signature
337         sig = base64.b64decode(signature)
338         if len(sig) != 65: raise Exception("Wrong encoding")
339         r,s = util.sigdecode_string(sig[1:], order)
340         nV = ord(sig[0])
341         if nV < 27 or nV >= 35:
342             raise Exception("Bad encoding")
343         if nV >= 31:
344             compressed = True
345             nV -= 4
346         else:
347             compressed = False
348
349         recid = nV - 27
350         # 1.1
351         x = r + (recid/2) * order
352         # 1.3
353         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
354         beta = msqr.modular_sqrt(alpha, curve.p())
355         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
356         # 1.4 the constructor checks that nR is at infinity
357         R = ellipticcurve.Point(curve, x, y, order)
358         # 1.5 compute e from message:
359         h = Hash( msg_magic(message) )
360         e = string_to_number(h)
361         minus_e = -e % order
362         # 1.6 compute Q = r^-1 (sR - eG)
363         inv_r = numbertheory.inverse_mod(r,order)
364         Q = inv_r * ( s * R + minus_e * G )
365         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
366         # check that Q is the public key
367         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
368         # check that we get the original signing address
369         addr = public_key_to_bc_address( encode_point(public_key, compressed) )
370         if address != addr:
371             raise Exception("Bad signature")
372
373
374 ###################################### BIP32 ##############################
375
376 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
377 BIP32_PRIME = 0x80000000
378
379 def bip32_init(seed):
380     import hmac
381     seed = seed.decode('hex')        
382     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
383
384     master_secret = I[0:32]
385     master_chain = I[32:]
386
387     K, K_compressed = get_pubkeys_from_secret(master_secret)
388     return master_secret, master_chain, K, K_compressed
389
390
391 def get_pubkeys_from_secret(secret):
392     # public key
393     private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
394     public_key = private_key.get_verifying_key()
395     K = public_key.to_string()
396     K_compressed = GetPubKey(public_key.pubkey,True)
397     return K, K_compressed
398
399
400
401 # Child private key derivation function (from master private key)
402 # k = master private key (32 bytes)
403 # c = master chain code (extra entropy for key derivation) (32 bytes)
404 # n = the index of the key we want to derive. (only 32 bits will be used)
405 # If n is negative (i.e. the 32nd bit is set), the resulting private key's
406 #  corresponding public key can NOT be determined without the master private key.
407 # However, if n is positive, the resulting private key's corresponding
408 #  public key can be determined without the master private key.
409 def CKD(k, c, n):
410     import hmac
411     from ecdsa.util import string_to_number, number_to_string
412     order = generator_secp256k1.order()
413     keypair = EC_KEY(string_to_number(k))
414     K = GetPubKey(keypair.pubkey,True)
415
416     if n & BIP32_PRIME: # We want to make a "secret" address that can't be determined from K
417         data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex')
418         I = hmac.new(c, data, hashlib.sha512).digest()
419     else: # We want a "non-secret" address that can be determined from K
420         I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
421         
422     k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
423     c_n = I[32:]
424     return k_n, c_n
425
426 # Child public key derivation function (from public key only)
427 # K = master public key 
428 # c = master chain code
429 # n = index of key we want to derive
430 # This function allows us to find the nth public key, as long as n is 
431 #  non-negative. If n is negative, we need the master private key to find it.
432 def CKD_prime(K, c, n):
433     import hmac
434     from ecdsa.util import string_to_number, number_to_string
435     order = generator_secp256k1.order()
436
437     if n & BIP32_PRIME: raise
438
439     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
440     K_compressed = GetPubKey(K_public_key.pubkey,True)
441
442     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
443
444     curve = SECP256k1
445     pubkey_point = string_to_number(I[0:32])*curve.generator + K_public_key.pubkey.point
446     public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
447
448     K_n = public_key.to_string()
449     K_n_compressed = GetPubKey(public_key.pubkey,True)
450     c_n = I[32:]
451
452     return K_n, K_n_compressed, c_n
453
454
455
456 def bip32_private_derivation(k, c, branch, sequence):
457     assert sequence.startswith(branch)
458     sequence = sequence[len(branch):]
459     for n in sequence.split('/'):
460         if n == '': continue
461         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
462         k, c = CKD(k, c, n)
463     K, K_compressed = get_pubkeys_from_secret(k)
464     return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex')
465
466
467 def bip32_public_derivation(c, K, branch, sequence):
468     assert sequence.startswith(branch)
469     sequence = sequence[len(branch):]
470     for n in sequence.split('/'):
471         n = int(n)
472         K, cK, c = CKD_prime(K, c, n)
473
474     return c.encode('hex'), K.encode('hex'), cK.encode('hex')
475
476
477 def bip32_private_key(sequence, k, chain):
478     for i in sequence:
479         k, chain = CKD(k, chain, i)
480     return SecretToASecret(k, True)
481
482
483
484
485 ################################## transactions
486
487 MIN_RELAY_TX_FEE = 10000
488
489
490
491 def test_bip32(seed, sequence):
492     """
493     run a test vector,
494     see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
495     """
496
497     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
498         
499     print "secret key", master_secret.encode('hex')
500     print "chain code", master_chain.encode('hex')
501
502     key_id = hash_160(master_public_key_compressed)
503     print "keyid", key_id.encode('hex')
504     print "base58"
505     print "address", hash_160_to_bc_address(key_id)
506     print "secret key", SecretToASecret(master_secret, True)
507
508     k = master_secret
509     c = master_chain
510
511     s = ['m']
512     for n in sequence.split('/'):
513         s.append(n)
514         print "Chain [%s]" % '/'.join(s)
515         
516         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
517         k0, c0 = CKD(k, c, n)
518         K0, K0_compressed = get_pubkeys_from_secret(k0)
519
520         print "* Identifier"
521         print "  * (main addr)", hash_160_to_bc_address(hash_160(K0_compressed))
522
523         print "* Secret Key"
524         print "  * (hex)", k0.encode('hex')
525         print "  * (wif)", SecretToASecret(k0, True)
526
527         print "* Chain Code"
528         print "   * (hex)", c0.encode('hex')
529
530         k = k0
531         c = c0
532     print "----"
533
534         
535
536
537 if __name__ == '__main__':
538     test_bip32("000102030405060708090a0b0c0d0e0f", "0'/1/2'/2/1000000000")
539     test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","0/2147483647'/1/2147483646'/2")
540