basic functions and tests for multisig transactions and bip 32
[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
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
43 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
44 hash_encode = lambda x: x[::-1].encode('hex')
45 hash_decode = lambda x: x.decode('hex')[::-1]
46
47
48 # pywallet openssl private key implementation
49
50 def i2d_ECPrivateKey(pkey, compressed=False):
51     if compressed:
52         key = '3081d30201010420' + \
53               '%064x' % pkey.secret + \
54               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
55               '%064x' % _p + \
56               '3006040100040107042102' + \
57               '%064x' % _Gx + \
58               '022100' + \
59               '%064x' % _r + \
60               '020101a124032200'
61     else:
62         key = '308201130201010420' + \
63               '%064x' % pkey.secret + \
64               'a081a53081a2020101302c06072a8648ce3d0101022100' + \
65               '%064x' % _p + \
66               '3006040100040107044104' + \
67               '%064x' % _Gx + \
68               '%064x' % _Gy + \
69               '022100' + \
70               '%064x' % _r + \
71               '020101a144034200'
72         
73     return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
74     
75 def i2o_ECPublicKey(pubkey, compressed=False):
76     # public keys are 65 bytes long (520 bits)
77     # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
78     # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
79     # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
80     if compressed:
81         if pubkey.point.y() & 1:
82             key = '03' + '%064x' % pubkey.point.x()
83         else:
84             key = '02' + '%064x' % pubkey.point.x()
85     else:
86         key = '04' + \
87               '%064x' % pubkey.point.x() + \
88               '%064x' % pubkey.point.y()
89             
90     return key.decode('hex')
91             
92 # end pywallet openssl private key implementation
93
94                                                 
95             
96 ############ functions from pywallet ##################### 
97
98 def hash_160(public_key):
99     try:
100         md = hashlib.new('ripemd160')
101         md.update(hashlib.sha256(public_key).digest())
102         return md.digest()
103     except:
104         import ripemd
105         md = ripemd.new(hashlib.sha256(public_key).digest())
106         return md.digest()
107
108
109 def public_key_to_bc_address(public_key):
110     h160 = hash_160(public_key)
111     return hash_160_to_bc_address(h160)
112
113 def hash_160_to_bc_address(h160, addrtype = 0):
114     vh160 = chr(addrtype) + h160
115     h = Hash(vh160)
116     addr = vh160 + h[0:4]
117     return b58encode(addr)
118
119 def bc_address_to_hash_160(addr):
120     bytes = b58decode(addr, 25)
121     return ord(bytes[0]), bytes[1:21]
122
123 def encode_point(pubkey, compressed=False):
124     order = generator_secp256k1.order()
125     p = pubkey.pubkey.point
126     x_str = ecdsa.util.number_to_string(p.x(), order)
127     y_str = ecdsa.util.number_to_string(p.y(), order)
128     if compressed:
129         return chr(2 + (p.y() & 1)) + x_str
130     else:
131         return chr(4) + pubkey.to_string() #x_str + y_str
132
133 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
134 __b58base = len(__b58chars)
135
136 def b58encode(v):
137     """ encode v, which is a string of bytes, to base58."""
138
139     long_value = 0L
140     for (i, c) in enumerate(v[::-1]):
141         long_value += (256**i) * ord(c)
142
143     result = ''
144     while long_value >= __b58base:
145         div, mod = divmod(long_value, __b58base)
146         result = __b58chars[mod] + result
147         long_value = div
148     result = __b58chars[long_value] + result
149
150     # Bitcoin does a little leading-zero-compression:
151     # leading 0-bytes in the input become leading-1s
152     nPad = 0
153     for c in v:
154         if c == '\0': nPad += 1
155         else: break
156
157     return (__b58chars[0]*nPad) + result
158
159 def b58decode(v, length):
160     """ decode v into a string of len bytes."""
161     long_value = 0L
162     for (i, c) in enumerate(v[::-1]):
163         long_value += __b58chars.find(c) * (__b58base**i)
164
165     result = ''
166     while long_value >= 256:
167         div, mod = divmod(long_value, 256)
168         result = chr(mod) + result
169         long_value = div
170     result = chr(long_value) + result
171
172     nPad = 0
173     for c in v:
174         if c == __b58chars[0]: nPad += 1
175         else: break
176
177     result = chr(0)*nPad + result
178     if length is not None and len(result) != length:
179         return None
180
181     return result
182
183
184 def EncodeBase58Check(vchIn):
185     hash = Hash(vchIn)
186     return b58encode(vchIn + hash[0:4])
187
188 def DecodeBase58Check(psz):
189     vchRet = b58decode(psz, None)
190     key = vchRet[0:-4]
191     csum = vchRet[-4:]
192     hash = Hash(key)
193     cs32 = hash[0:4]
194     if cs32 != csum:
195         return None
196     else:
197         return key
198
199 def PrivKeyToSecret(privkey):
200     return privkey[9:9+32]
201
202 def SecretToASecret(secret, compressed=False, addrtype=0):
203     vchIn = chr((addrtype+128)&255) + secret
204     if compressed: vchIn += '\01'
205     return EncodeBase58Check(vchIn)
206
207 def ASecretToSecret(key, addrtype=0):
208     vch = DecodeBase58Check(key)
209     if vch and vch[0] == chr((addrtype+128)&255):
210         return vch[1:]
211     else:
212         return False
213
214 def regenerate_key(sec):
215     b = ASecretToSecret(sec)
216     if not b:
217         return False
218     b = b[0:32]
219     secret = int('0x' + b.encode('hex'), 16)
220     return EC_KEY(secret)
221
222 def GetPubKey(pubkey, compressed=False):
223     return i2o_ECPublicKey(pubkey, compressed)
224
225 def GetPrivKey(pkey, compressed=False):
226     return i2d_ECPrivateKey(pkey, compressed)
227
228 def GetSecret(pkey):
229     return ('%064x' % pkey.secret).decode('hex')
230
231 def is_compressed(sec):
232     b = ASecretToSecret(sec)
233     return len(b) == 33
234
235 ########### end pywallet functions #######################
236
237 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
238 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
239 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
240 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
241 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
242 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
243 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
244 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
245 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
246 oid_secp256k1 = (1,3,132,0,10)
247 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
248
249 class EC_KEY(object):
250     def __init__( self, secret ):
251         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
252         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
253         self.secret = secret
254
255
256 ###################################### BIP32 ##############################
257
258 def bip32_init(seed):
259     import hmac
260         
261     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
262
263     print "seed", seed.encode('hex')
264     master_secret = I[0:32]
265     master_chain = I[32:]
266
267     # public key
268     curve = SECP256k1
269     master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
270     master_public_key = master_private_key.get_verifying_key()
271     K = master_public_key.to_string()
272     K_compressed = GetPubKey(master_public_key.pubkey,True)
273     return master_secret, master_chain, K, K_compressed
274
275     
276 def CKD(k, c, n):
277     import hmac
278     from ecdsa.util import string_to_number, number_to_string
279     order = generator_secp256k1.order()
280     keypair = EC_KEY(string_to_number(k))
281     K = GetPubKey(keypair.pubkey,True)
282     I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
283     k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
284     c_n = I[32:]
285     return k_n, c_n
286
287
288 def CKD_prime(K, c, n):
289     import hmac
290     from ecdsa.util import string_to_number, number_to_string
291     order = generator_secp256k1.order()
292
293     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
294     K_compressed = GetPubKey(K_public_key.pubkey,True)
295
296     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
297
298     #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
299     public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
300     K_n = public_key.to_string()
301     K_n_compressed = GetPubKey(public_key.pubkey,True)
302     c_n = I[32:]
303
304     return K_n, K_n_compressed, c_n
305
306
307
308
309
310 ################################## transactions
311
312
313 def tx_filter(s): 
314     out = re.sub('( [^\n]*|)\n','',s)
315     out = out.replace(' ','')
316     out = out.replace('\n','')
317     return out
318
319 def raw_tx( inputs, outputs, for_sig = None ):
320     s  = int_to_hex(1,4)                                         # version
321     s += var_int( len(inputs) )                                  # number of inputs
322     for i in range(len(inputs)):
323         _, _, p_hash, p_index, p_script, pubkeysig = inputs[i]
324         s += p_hash.decode('hex')[::-1].encode('hex')            # prev hash
325         s += int_to_hex(p_index,4)                               # prev index
326
327         if for_sig is None:
328             if len(pubkeysig) == 1:
329                 pubkey, sig = pubkeysig[0]
330                 sig = sig + chr(1)                               # hashtype
331                 script  = int_to_hex( len(sig))
332                 script += sig.encode('hex')
333                 script += int_to_hex( len(pubkey))
334                 script += pubkey.encode('hex')
335             else:
336                 pubkey0, sig0 = pubkeysig[0]
337                 pubkey1, sig1 = pubkeysig[1]
338                 sig0 = sig0 + chr(1)
339                 sig1 = sig1 + chr(1)
340                 inner_script = multisig_script([pubkey0, pubkey1])
341                 script = '00'                                    # op_0
342                 script += int_to_hex(len(sig0))
343                 script += sig0.encode('hex')
344                 script += int_to_hex(len(sig1))
345                 script += sig1.encode('hex')
346                 script += var_int(len(inner_script)/2)
347                 script += inner_script
348
349         elif for_sig==i:
350             if len(pubkeysig) > 1:
351                 script = multisig_script(pubkeysig)              # p2sh uses the inner script
352             else:
353                 script = p_script                                # scriptsig
354         else:
355             script=''
356         s += var_int( len(tx_filter(script))/2 )                 # script length
357         s += script
358         s += "ffffffff"                                          # sequence
359
360     s += var_int( len(outputs) )                                 # number of outputs
361     for output in outputs:
362         addr, amount = output
363         s += int_to_hex( amount, 8)                              # amount
364         addrtype, hash_160 = bc_address_to_hash_160(addr)
365         if addrtype == 0:
366             script = '76a9'                                      # op_dup, op_hash_160
367             script += '14'                                       # push 0x14 bytes
368             script += hash_160.encode('hex')
369             script += '88ac'                                     # op_equalverify, op_checksig
370         elif addrtype == 5:
371             script = 'a9'                                        # op_hash_160
372             script += '14'                                       # push 0x14 bytes
373             script += hash_160.encode('hex')
374             script += '87'                                       # op_equal
375         else:
376             raise
377             
378         s += var_int( len(tx_filter(script))/2 )                #  script length
379         s += script                                             #  script
380     s += int_to_hex(0,4)                                        #  lock time
381     if for_sig is not None: s += int_to_hex(1, 4)               #  hash type
382     return tx_filter(s)
383
384
385 def multisig_script(public_keys):
386     # supports only "2 of 2", and "2 of 3" transactions
387     n = len(public_keys)
388     s = '52'
389     for k in public_keys:
390         s += var_int(len(k)/2)
391         s += k
392     if n==2:
393         s += '52'
394     elif n==3:
395         s += '53'
396     else:
397         raise
398     s += 'ae'
399     return s
400
401
402
403 def test_bip32():
404     seed = "ff000000000000000000000000000000".decode('hex')
405     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
406         
407     print "secret key", master_secret.encode('hex')
408     print "chain code", master_chain.encode('hex')
409
410     key_id = hash_160(master_public_key_compressed)
411     print "keyid", key_id.encode('hex')
412     print "base58"
413     print "address", hash_160_to_bc_address(key_id)
414     print "secret key", SecretToASecret(master_secret, True)
415
416     print "-- m/0 --"
417     k0, c0 = CKD(master_secret, master_chain, 0)
418     print "secret", k0.encode('hex')
419     print "chain", c0.encode('hex')
420     print "secret key", SecretToASecret(k0, True)
421     
422     K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
423     print "address", hash_160_to_bc_address(hash_160(K0_compressed))
424     
425     print "-- m/0/1 --"
426     K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
427     print "address", hash_160_to_bc_address(hash_160(K01_compressed))
428     
429     print "-- m/0/1/3 --"
430     K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
431     print "address", hash_160_to_bc_address(hash_160(K013_compressed))
432     
433     print "-- m/0/1/3/7 --"
434     K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
435     print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
436         
437
438 def test_p2sh():
439
440     print "2 of 2"
441     pubkeys = ["04e89a79651522201d756f14b1874ae49139cc984e5782afeca30ffe84e5e6b2cfadcfe9875c490c8a1a05a4debd715dd57471af8886ab5dfbb3959d97f087f77a",
442                "0455cf4a3ab68a011b18cb0a86aae2b8e9cad6c6355476de05247c57a9632d127084ac7630ad89893b43c486c5a9f7ec6158fb0feb708fa9255d5c4d44bc0858f8"]
443     s = multisig_script(pubkeys)
444     print "address", hash_160_to_bc_address(hash_160(s.decode('hex')), 5)
445
446
447     print "Gavin's tutorial: redeem p2sh:  http://blockchain.info/tx-index/30888901"
448     pubkey1 = "0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"
449     pubkey2 = "04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"
450     pubkey3 = "048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"
451     pubkeys = [pubkey1, pubkey2, pubkey3]
452
453     tx_for_sig = raw_tx( [(None, None, '3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac', 0, 'a914f815b036d9bbbce5e9f2a00abd1bf3dc91e9551087', pubkeys)],
454                          [('1GtpSrGhRGY5kkrNz4RykoqRQoJuG2L6DS',1000000)], for_sig = 0)
455
456     print "tx for sig", tx_for_sig
457
458     signature1 = "304502200187af928e9d155c4b1ac9c1c9118153239aba76774f775d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1bbdaaba4e50eb078f39e3d78"
459     signature2 = "30440220795f0f4f5941a77ae032ecb9e33753788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e27038e945bc9db59c732728a383a6f1ed2fb99da7a4"
460
461     for pubkey in pubkeys:
462         import traceback, sys
463
464         public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
465
466         try:
467             public_key.verify_digest( signature1.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
468             print True
469         except ecdsa.keys.BadSignatureError:
470             #traceback.print_exc(file=sys.stdout)
471             print False
472
473         try:
474             public_key.verify_digest( signature2.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
475             print True
476         except ecdsa.keys.BadSignatureError:
477             #traceback.print_exc(file=sys.stdout)
478             print False
479
480 if __name__ == '__main__':
481     #test_bip32()
482     test_p2sh()
483