don't use bare except
[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 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
57 hash_encode = lambda x: x[::-1].encode('hex')
58 hash_decode = lambda x: x.decode('hex')[::-1]
59
60 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
61 mnemonic_hash = lambda x: hmac_sha_512("Bitcoin mnemonic", x).encode('hex')
62
63 # pywallet openssl private key implementation
64
65 def i2d_ECPrivateKey(pkey, compressed=False):
66     if compressed:
67         key = '3081d30201010420' + \
68               '%064x' % pkey.secret + \
69               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
70               '%064x' % _p + \
71               '3006040100040107042102' + \
72               '%064x' % _Gx + \
73               '022100' + \
74               '%064x' % _r + \
75               '020101a124032200'
76     else:
77         key = '308201130201010420' + \
78               '%064x' % pkey.secret + \
79               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
80               '%064x' % _p + \
81               '3006040100040107044104' + \
82               '%064x' % _Gx + \
83               '%064x' % _Gy + \
84               '022100' + \
85               '%064x' % _r + \
86               '020101a144034200'
87         
88     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
89     
90 def i2o_ECPublicKey(pubkey, compressed=False):
91     # public keys are 65 bytes long (520 bits)
92     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
93     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
94     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
95     if compressed:
96         if pubkey.point.y() & 1:
97             key = '03' + '%064x' % pubkey.point.x()
98         else:
99             key = '02' + '%064x' % pubkey.point.x()
100     else:
101         key = '04' + \
102               '%064x' % pubkey.point.x() + \
103               '%064x' % pubkey.point.y()
104             
105     return key.decode('hex')
106             
107 # end pywallet openssl private key implementation
108
109                                                 
110             
111 ############ functions from pywallet ##################### 
112
113 def hash_160(public_key):
114     try:
115         md = hashlib.new('ripemd160')
116         md.update(hashlib.sha256(public_key).digest())
117         return md.digest()
118     except Exception:
119         import ripemd
120         md = ripemd.new(hashlib.sha256(public_key).digest())
121         return md.digest()
122
123
124 def public_key_to_bc_address(public_key):
125     h160 = hash_160(public_key)
126     return hash_160_to_bc_address(h160)
127
128 def hash_160_to_bc_address(h160, addrtype = 0):
129     vh160 = chr(addrtype) + h160
130     h = Hash(vh160)
131     addr = vh160 + h[0:4]
132     return b58encode(addr)
133
134 def bc_address_to_hash_160(addr):
135     bytes = b58decode(addr, 25)
136     return ord(bytes[0]), bytes[1:21]
137
138 def encode_point(pubkey, compressed=False):
139     order = generator_secp256k1.order()
140     p = pubkey.pubkey.point
141     x_str = ecdsa.util.number_to_string(p.x(), order)
142     y_str = ecdsa.util.number_to_string(p.y(), order)
143     if compressed:
144         return chr(2 + (p.y() & 1)) + x_str
145     else:
146         return chr(4) + pubkey.to_string() #x_str + y_str
147
148 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
149 __b58base = len(__b58chars)
150
151 def b58encode(v):
152     """ encode v, which is a string of bytes, to base58."""
153
154     long_value = 0L
155     for (i, c) in enumerate(v[::-1]):
156         long_value += (256**i) * ord(c)
157
158     result = ''
159     while long_value >= __b58base:
160         div, mod = divmod(long_value, __b58base)
161         result = __b58chars[mod] + result
162         long_value = div
163     result = __b58chars[long_value] + result
164
165     # Bitcoin does a little leading-zero-compression:
166     # leading 0-bytes in the input become leading-1s
167     nPad = 0
168     for c in v:
169         if c == '\0': nPad += 1
170         else: break
171
172     return (__b58chars[0]*nPad) + result
173
174 def b58decode(v, length):
175     """ decode v into a string of len bytes."""
176     long_value = 0L
177     for (i, c) in enumerate(v[::-1]):
178         long_value += __b58chars.find(c) * (__b58base**i)
179
180     result = ''
181     while long_value >= 256:
182         div, mod = divmod(long_value, 256)
183         result = chr(mod) + result
184         long_value = div
185     result = chr(long_value) + result
186
187     nPad = 0
188     for c in v:
189         if c == __b58chars[0]: nPad += 1
190         else: break
191
192     result = chr(0)*nPad + result
193     if length is not None and len(result) != length:
194         return None
195
196     return result
197
198
199 def EncodeBase58Check(vchIn):
200     hash = Hash(vchIn)
201     return b58encode(vchIn + hash[0:4])
202
203 def DecodeBase58Check(psz):
204     vchRet = b58decode(psz, None)
205     key = vchRet[0:-4]
206     csum = vchRet[-4:]
207     hash = Hash(key)
208     cs32 = hash[0:4]
209     if cs32 != csum:
210         return None
211     else:
212         return key
213
214 def PrivKeyToSecret(privkey):
215     return privkey[9:9+32]
216
217 def SecretToASecret(secret, compressed=False, addrtype=0):
218     vchIn = chr((addrtype+128)&255) + secret
219     if compressed: vchIn += '\01'
220     return EncodeBase58Check(vchIn)
221
222 def ASecretToSecret(key, addrtype=0):
223     vch = DecodeBase58Check(key)
224     if vch and vch[0] == chr((addrtype+128)&255):
225         return vch[1:]
226     else:
227         return False
228
229 def regenerate_key(sec):
230     b = ASecretToSecret(sec)
231     if not b:
232         return False
233     b = b[0:32]
234     secret = int('0x' + b.encode('hex'), 16)
235     return EC_KEY(secret)
236
237 def GetPubKey(pubkey, compressed=False):
238     return i2o_ECPublicKey(pubkey, compressed)
239
240 def GetPrivKey(pkey, compressed=False):
241     return i2d_ECPrivateKey(pkey, compressed)
242
243 def GetSecret(pkey):
244     return ('%064x' % pkey.secret).decode('hex')
245
246 def is_compressed(sec):
247     b = ASecretToSecret(sec)
248     return len(b) == 33
249
250
251 def public_key_from_private_key(sec):
252     # rebuild public key from private key, compressed or uncompressed
253     pkey = regenerate_key(sec)
254     assert pkey
255     compressed = is_compressed(sec)
256     public_key = GetPubKey(pkey.pubkey, compressed)
257     return public_key.encode('hex')
258
259
260 def address_from_private_key(sec):
261     public_key = public_key_from_private_key(sec)
262     address = public_key_to_bc_address(public_key.decode('hex'))
263     return address
264
265
266 def is_valid(addr):
267     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
268     if not ADDRESS_RE.match(addr): return False
269     try:
270         addrtype, h = bc_address_to_hash_160(addr)
271     except Exception:
272         return False
273     return addr == hash_160_to_bc_address(h, addrtype)
274
275
276 ########### end pywallet functions #######################
277
278 try:
279     from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
280 except Exception:
281     print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
282     exit()
283 from ecdsa.curves import SECP256k1
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
290     return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
291
292
293 def verify_message(address, signature, message):
294     try:
295         EC_KEY.verify_message(address, signature, message)
296         return True
297     except Exception as e:
298         print_error("Verification error: {0}".format(e))
299         return False
300
301
302
303 class EC_KEY(object):
304     def __init__( self, secret ):
305         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
306         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
307         self.secret = secret
308
309     def sign_message(self, message, compressed, address):
310         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
311         public_key = private_key.get_verifying_key()
312         signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
313         assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
314         for i in range(4):
315             sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
316             try:
317                 self.verify_message( address, sig, message)
318                 return sig
319             except Exception:
320                 continue
321         else:
322             raise Exception("error: cannot sign message")
323
324     @classmethod
325     def verify_message(self, address, signature, message):
326         """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
327         from ecdsa import numbertheory, ellipticcurve, util
328         import msqr
329         curve = curve_secp256k1
330         G = generator_secp256k1
331         order = G.order()
332         # extract r,s from signature
333         sig = base64.b64decode(signature)
334         if len(sig) != 65: raise Exception("Wrong encoding")
335         r,s = util.sigdecode_string(sig[1:], order)
336         nV = ord(sig[0])
337         if nV < 27 or nV >= 35:
338             raise Exception("Bad encoding")
339         if nV >= 31:
340             compressed = True
341             nV -= 4
342         else:
343             compressed = False
344
345         recid = nV - 27
346         # 1.1
347         x = r + (recid/2) * order
348         # 1.3
349         alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
350         beta = msqr.modular_sqrt(alpha, curve.p())
351         y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
352         # 1.4 the constructor checks that nR is at infinity
353         R = ellipticcurve.Point(curve, x, y, order)
354         # 1.5 compute e from message:
355         h = Hash( msg_magic(message) )
356         e = string_to_number(h)
357         minus_e = -e % order
358         # 1.6 compute Q = r^-1 (sR - eG)
359         inv_r = numbertheory.inverse_mod(r,order)
360         Q = inv_r * ( s * R + minus_e * G )
361         public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
362         # check that Q is the public key
363         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
364         # check that we get the original signing address
365         addr = public_key_to_bc_address( encode_point(public_key, compressed) )
366         if address != addr:
367             raise Exception("Bad signature")
368
369
370 ###################################### BIP32 ##############################
371
372 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
373 BIP32_PRIME = 0x80000000
374
375 def bip32_init(seed):
376     import hmac
377     seed = seed.decode('hex')        
378     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
379
380     master_secret = I[0:32]
381     master_chain = I[32:]
382
383     K, K_compressed = get_pubkeys_from_secret(master_secret)
384     return master_secret, master_chain, K, K_compressed
385
386
387 def get_pubkeys_from_secret(secret):
388     # public key
389     curve = SECP256k1
390     private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
391     public_key = private_key.get_verifying_key()
392     K = public_key.to_string()
393     K_compressed = GetPubKey(public_key.pubkey,True)
394     return K, K_compressed
395
396
397
398     
399 def CKD(k, c, n):
400     import hmac
401     from ecdsa.util import string_to_number, number_to_string
402     order = generator_secp256k1.order()
403     keypair = EC_KEY(string_to_number(k))
404     K = GetPubKey(keypair.pubkey,True)
405
406     if n & BIP32_PRIME:
407         data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex')
408         I = hmac.new(c, data, hashlib.sha512).digest()
409     else:
410         I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
411         
412     k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
413     c_n = I[32:]
414     return k_n, c_n
415
416
417 def CKD_prime(K, c, n):
418     import hmac
419     from ecdsa.util import string_to_number, number_to_string
420     order = generator_secp256k1.order()
421
422     if n & BIP32_PRIME: raise
423
424     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
425     K_compressed = GetPubKey(K_public_key.pubkey,True)
426
427     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
428
429     curve = SECP256k1
430     pubkey_point = string_to_number(I[0:32])*curve.generator + K_public_key.pubkey.point
431     public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
432
433     K_n = public_key.to_string()
434     K_n_compressed = GetPubKey(public_key.pubkey,True)
435     c_n = I[32:]
436
437     return K_n, K_n_compressed, c_n
438
439
440
441 def bip32_private_derivation(k, c, branch, sequence):
442     assert sequence.startswith(branch)
443     sequence = sequence[len(branch):]
444     for n in sequence.split('/'):
445         if n == '': continue
446         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
447         k, c = CKD(k, c, n)
448     K, K_compressed = get_pubkeys_from_secret(k)
449     return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex')
450
451
452 def bip32_public_derivation(c, K, branch, sequence):
453     assert sequence.startswith(branch)
454     sequence = sequence[len(branch):]
455     for n in sequence.split('/'):
456         n = int(n)
457         K, cK, c = CKD_prime(K, c, n)
458
459     return c.encode('hex'), K.encode('hex'), cK.encode('hex')
460
461
462 def bip32_private_key(sequence, k, chain):
463     for i in sequence:
464         k, chain = CKD(k, chain, i)
465     return SecretToASecret(k, True)
466
467
468
469
470 ################################## transactions
471
472 MIN_RELAY_TX_FEE = 10000
473
474
475
476 def test_bip32(seed, sequence):
477     """
478     run a test vector,
479     see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
480     """
481
482     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
483         
484     print "secret key", master_secret.encode('hex')
485     print "chain code", master_chain.encode('hex')
486
487     key_id = hash_160(master_public_key_compressed)
488     print "keyid", key_id.encode('hex')
489     print "base58"
490     print "address", hash_160_to_bc_address(key_id)
491     print "secret key", SecretToASecret(master_secret, True)
492
493     k = master_secret
494     c = master_chain
495
496     s = ['m']
497     for n in sequence.split('/'):
498         s.append(n)
499         print "Chain [%s]" % '/'.join(s)
500         
501         n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
502         k0, c0 = CKD(k, c, n)
503         K0, K0_compressed = get_pubkeys_from_secret(k0)
504
505         print "* Identifier"
506         print "  * (main addr)", hash_160_to_bc_address(hash_160(K0_compressed))
507
508         print "* Secret Key"
509         print "  * (hex)", k0.encode('hex')
510         print "  * (wif)", SecretToASecret(k0, True)
511
512         print "* Chain Code"
513         print "   * (hex)", c0.encode('hex')
514
515         k = k0
516         c = c0
517     print "----"
518
519         
520
521
522 if __name__ == '__main__':
523     test_bip32("000102030405060708090a0b0c0d0e0f", "0'/1/2'/2/1000000000")
524     test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","0/2147483647'/1/2147483646'/2")
525