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