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