bugfix: for_sig != -1
[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
236 def address_from_private_key(sec):
237     # rebuild public key from private key, compressed or uncompressed
238     pkey = regenerate_key(sec)
239     assert pkey
240
241     # figure out if private key is compressed
242     compressed = is_compressed(sec)
243         
244     # rebuild private and public key from regenerated secret
245     private_key = GetPrivKey(pkey, compressed)
246     public_key = GetPubKey(pkey.pubkey, compressed)
247     address = public_key_to_bc_address(public_key)
248     return address
249
250
251 ########### end pywallet functions #######################
252
253 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
254 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
255 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
256 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
257 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
258 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
259 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
260 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
261 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
262 oid_secp256k1 = (1,3,132,0,10)
263 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) 
264
265 class EC_KEY(object):
266     def __init__( self, secret ):
267         self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
268         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
269         self.secret = secret
270
271
272 ###################################### BIP32 ##############################
273
274 def bip32_init(seed):
275     import hmac
276         
277     I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
278
279     print "seed", seed.encode('hex')
280     master_secret = I[0:32]
281     master_chain = I[32:]
282
283     # public key
284     curve = SECP256k1
285     master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
286     master_public_key = master_private_key.get_verifying_key()
287     K = master_public_key.to_string()
288     K_compressed = GetPubKey(master_public_key.pubkey,True)
289     return master_secret, master_chain, K, K_compressed
290
291     
292 def CKD(k, c, n):
293     import hmac
294     from ecdsa.util import string_to_number, number_to_string
295     order = generator_secp256k1.order()
296     keypair = EC_KEY(string_to_number(k))
297     K = GetPubKey(keypair.pubkey,True)
298     I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
299     k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
300     c_n = I[32:]
301     return k_n, c_n
302
303
304 def CKD_prime(K, c, n):
305     import hmac
306     from ecdsa.util import string_to_number, number_to_string
307     order = generator_secp256k1.order()
308
309     K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
310     K_compressed = GetPubKey(K_public_key.pubkey,True)
311
312     I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
313
314     #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
315     public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
316     K_n = public_key.to_string()
317     K_n_compressed = GetPubKey(public_key.pubkey,True)
318     c_n = I[32:]
319
320     return K_n, K_n_compressed, c_n
321
322
323
324
325
326 ################################## transactions
327
328
329 def tx_filter(s): 
330     out = re.sub('( [^\n]*|)\n','',s)
331     out = out.replace(' ','')
332     out = out.replace('\n','')
333     return out
334
335 def raw_tx( inputs, outputs, for_sig = None ):
336
337     s  = int_to_hex(1,4)                                         # version
338     s += var_int( len(inputs) )                                  # number of inputs
339     for i in range(len(inputs)):
340         txin = inputs[i]
341         s += txin['tx_hash'].decode('hex')[::-1].encode('hex')            # prev hash
342         s += int_to_hex(txin['index'],4)                               # prev index
343
344         if for_sig is None:
345             pubkeysig = txin['pubkeysig']
346             if len(pubkeysig) == 1:
347                 pubkey, sig = pubkeysig[0]
348                 sig = sig + chr(1)                               # hashtype
349                 script  = int_to_hex( len(sig))
350                 script += sig.encode('hex')
351                 script += int_to_hex( len(pubkey))
352                 script += pubkey.encode('hex')
353             else:
354                 n = txin['multisig_num']
355                 pubkeys = map(lambda x:x[0], pubkeysig)
356                 script = '00'                                    # op_0
357                 for item in pubkeysig:
358                     pubkey, sig = item
359                     sig = sig + chr(1)
360                     script += int_to_hex(len(sig))
361                     script += sig.encode('hex')
362                 inner_script = multisig_script(pubkeys)
363                 script += var_int(len(inner_script)/2)
364                 script += inner_script
365
366         elif for_sig==i:
367             pubkeys = txin.get('pubkeys')
368             if pubkeys:
369                 num = txin['p2sh_num']
370                 script = multisig_script(pubkeys, num)           # p2sh uses the inner script
371             else:
372                 script = txin['raw_output_script']               # scriptsig
373         else:
374             script=''
375         s += var_int( len(tx_filter(script))/2 )                 # script length
376         s += script
377         s += "ffffffff"                                          # sequence
378
379     s += var_int( len(outputs) )                                 # number of outputs
380     for output in outputs:
381         addr, amount = output
382         s += int_to_hex( amount, 8)                              # amount
383         addrtype, hash_160 = bc_address_to_hash_160(addr)
384         if addrtype == 0:
385             script = '76a9'                                      # op_dup, op_hash_160
386             script += '14'                                       # push 0x14 bytes
387             script += hash_160.encode('hex')
388             script += '88ac'                                     # op_equalverify, op_checksig
389         elif addrtype == 5:
390             script = 'a9'                                        # op_hash_160
391             script += '14'                                       # push 0x14 bytes
392             script += hash_160.encode('hex')
393             script += '87'                                       # op_equal
394         else:
395             raise
396             
397         s += var_int( len(tx_filter(script))/2 )                #  script length
398         s += script                                             #  script
399     s += int_to_hex(0,4)                                        #  lock time
400     if for_sig is not None and for_sig != -1: s += int_to_hex(1, 4)               #  hash type
401     return tx_filter(s)
402
403
404
405
406 def multisig_script(public_keys, num=None):
407     # supports only "2 of 2", and "2 of 3" transactions
408     n = len(public_keys)
409
410     if num is None:
411         num = n
412
413     assert num <= n and n <= 3 and n >= 2
414     
415     if num==2:
416         s = '52'
417     elif num == 3:
418         s = '53'
419     else:
420         raise
421     
422     for k in public_keys:
423         s += var_int(len(k)/2)
424         s += k
425     if n==2:
426         s += '52'
427     elif n==3:
428         s += '53'
429     else:
430         raise
431     s += 'ae'
432     return s
433
434
435
436 class Transaction:
437     
438     def __init__(self, raw):
439         self.raw = raw
440         self.deserialize()
441         self.inputs = self.d['inputs']
442         self.outputs = self.d['outputs']
443         self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
444         
445     @classmethod
446     def from_io(klass, inputs, outputs):
447         raw = raw_tx(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
448         self = klass(raw)
449         self.inputs = inputs
450         self.outputs = outputs
451         return self
452
453     def __str__(self):
454         return self.raw
455
456     def for_sig(self,i):
457         return raw_tx(self.inputs, self.outputs, for_sig = i)
458
459     def hash(self):
460         return Hash(self.raw.decode('hex') )[::-1].encode('hex')
461
462     def sign(self, private_keys):
463
464         for i in range(len(self.inputs)):
465             txin = self.inputs[i]
466             sec = private_keys[txin['address']]
467             compressed = is_compressed(sec)
468             pkey = regenerate_key(sec)
469             secexp = pkey.secret
470
471             private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
472             public_key = private_key.get_verifying_key()
473             pkey = EC_KEY(secexp)
474             pubkey = GetPubKey(pkey.pubkey, compressed)
475             tx = raw_tx( self.inputs, self.outputs, for_sig = i )
476             sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
477             assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
478             self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
479
480         self.raw = raw_tx( self.inputs, self.outputs )
481
482
483     def deserialize(self):
484         import deserialize
485         vds = deserialize.BCDataStream()
486         vds.write(self.raw.decode('hex'))
487         self.d = deserialize.parse_Transaction(vds)
488         return self.d
489     
490
491
492
493 def test_bip32():
494     seed = "ff000000000000000000000000000000".decode('hex')
495     master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
496         
497     print "secret key", master_secret.encode('hex')
498     print "chain code", master_chain.encode('hex')
499
500     key_id = hash_160(master_public_key_compressed)
501     print "keyid", key_id.encode('hex')
502     print "base58"
503     print "address", hash_160_to_bc_address(key_id)
504     print "secret key", SecretToASecret(master_secret, True)
505
506     print "-- m/0 --"
507     k0, c0 = CKD(master_secret, master_chain, 0)
508     print "secret", k0.encode('hex')
509     print "chain", c0.encode('hex')
510     print "secret key", SecretToASecret(k0, True)
511     
512     K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
513     print "address", hash_160_to_bc_address(hash_160(K0_compressed))
514     
515     print "-- m/0/1 --"
516     K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
517     print "address", hash_160_to_bc_address(hash_160(K01_compressed))
518     
519     print "-- m/0/1/3 --"
520     K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
521     print "address", hash_160_to_bc_address(hash_160(K013_compressed))
522     
523     print "-- m/0/1/3/7 --"
524     K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
525     print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
526         
527
528 def test_p2sh():
529
530     print "2 of 2"
531     pubkeys = ["04e89a79651522201d756f14b1874ae49139cc984e5782afeca30ffe84e5e6b2cfadcfe9875c490c8a1a05a4debd715dd57471af8886ab5dfbb3959d97f087f77a",
532                "0455cf4a3ab68a011b18cb0a86aae2b8e9cad6c6355476de05247c57a9632d127084ac7630ad89893b43c486c5a9f7ec6158fb0feb708fa9255d5c4d44bc0858f8"]
533     s = multisig_script(pubkeys)
534     print "address", hash_160_to_bc_address(hash_160(s.decode('hex')), 5)
535
536
537     print "Gavin's tutorial: redeem p2sh:  http://blockchain.info/tx-index/30888901"
538     pubkey1 = "0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"
539     pubkey2 = "04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"
540     pubkey3 = "048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"
541     pubkeys = [pubkey1, pubkey2, pubkey3]
542
543     tx = Transaction.from_io(
544         [{'tx_hash':'3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac', 'index':0,
545           'raw_output_script':'a914f815b036d9bbbce5e9f2a00abd1bf3dc91e9551087', 'pubkeys':pubkeys, 'p2sh_num':2}],
546         [('1GtpSrGhRGY5kkrNz4RykoqRQoJuG2L6DS',1000000)])
547
548     tx_for_sig = tx.for_sig(0)
549     print "tx for sig", tx_for_sig
550
551     signature1 = "304502200187af928e9d155c4b1ac9c1c9118153239aba76774f775d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1bbdaaba4e50eb078f39e3d78"
552     signature2 = "30440220795f0f4f5941a77ae032ecb9e33753788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e27038e945bc9db59c732728a383a6f1ed2fb99da7a4"
553
554     for pubkey in pubkeys:
555         import traceback, sys
556
557         public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
558
559         try:
560             public_key.verify_digest( signature1.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
561             print True
562         except ecdsa.keys.BadSignatureError:
563             #traceback.print_exc(file=sys.stdout)
564             print False
565
566         try:
567             public_key.verify_digest( signature2.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
568             print True
569         except ecdsa.keys.BadSignatureError:
570             #traceback.print_exc(file=sys.stdout)
571             print False
572
573 if __name__ == '__main__':
574     #test_bip32()
575     test_p2sh()
576