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