3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
20 import hashlib, base64, ecdsa, re
21 from util import print_error
24 return s.decode('hex')[::-1].encode('hex')
26 def int_to_hex(i, length=1):
27 s = hex(i)[2:].rstrip('L')
28 s = "0"*(2*length - len(s)) + s
32 # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
36 return "fd"+int_to_hex(i,2)
38 return "fe"+int_to_hex(i,4)
40 return "ff"+int_to_hex(i,8)
46 return '4c' + int_to_hex(i)
48 return '4d' + int_to_hex(i,2)
50 return '4e' + int_to_hex(i,4)
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]
59 # pywallet openssl private key implementation
61 def i2d_ECPrivateKey(pkey, compressed=False):
63 key = '3081d30201010420' + \
64 '%064x' % pkey.secret + \
65 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
67 '3006040100040107042102' + \
73 key = '308201130201010420' + \
74 '%064x' % pkey.secret + \
75 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
77 '3006040100040107044104' + \
84 return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
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
92 if pubkey.point.y() & 1:
93 key = '03' + '%064x' % pubkey.point.x()
95 key = '02' + '%064x' % pubkey.point.x()
98 '%064x' % pubkey.point.x() + \
99 '%064x' % pubkey.point.y()
101 return key.decode('hex')
103 # end pywallet openssl private key implementation
107 ############ functions from pywallet #####################
109 def hash_160(public_key):
111 md = hashlib.new('ripemd160')
112 md.update(hashlib.sha256(public_key).digest())
116 md = ripemd.new(hashlib.sha256(public_key).digest())
120 def public_key_to_bc_address(public_key):
121 h160 = hash_160(public_key)
122 return hash_160_to_bc_address(h160)
124 def hash_160_to_bc_address(h160, addrtype = 0):
125 vh160 = chr(addrtype) + h160
127 addr = vh160 + h[0:4]
128 return b58encode(addr)
130 def bc_address_to_hash_160(addr):
131 bytes = b58decode(addr, 25)
132 return ord(bytes[0]), bytes[1:21]
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)
140 return chr(2 + (p.y() & 1)) + x_str
142 return chr(4) + pubkey.to_string() #x_str + y_str
144 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
145 __b58base = len(__b58chars)
148 """ encode v, which is a string of bytes, to base58."""
151 for (i, c) in enumerate(v[::-1]):
152 long_value += (256**i) * ord(c)
155 while long_value >= __b58base:
156 div, mod = divmod(long_value, __b58base)
157 result = __b58chars[mod] + result
159 result = __b58chars[long_value] + result
161 # Bitcoin does a little leading-zero-compression:
162 # leading 0-bytes in the input become leading-1s
165 if c == '\0': nPad += 1
168 return (__b58chars[0]*nPad) + result
170 def b58decode(v, length):
171 """ decode v into a string of len bytes."""
173 for (i, c) in enumerate(v[::-1]):
174 long_value += __b58chars.find(c) * (__b58base**i)
177 while long_value >= 256:
178 div, mod = divmod(long_value, 256)
179 result = chr(mod) + result
181 result = chr(long_value) + result
185 if c == __b58chars[0]: nPad += 1
188 result = chr(0)*nPad + result
189 if length is not None and len(result) != length:
195 def EncodeBase58Check(vchIn):
197 return b58encode(vchIn + hash[0:4])
199 def DecodeBase58Check(psz):
200 vchRet = b58decode(psz, None)
210 def PrivKeyToSecret(privkey):
211 return privkey[9:9+32]
213 def SecretToASecret(secret, compressed=False, addrtype=0):
214 vchIn = chr((addrtype+128)&255) + secret
215 if compressed: vchIn += '\01'
216 return EncodeBase58Check(vchIn)
218 def ASecretToSecret(key, addrtype=0):
219 vch = DecodeBase58Check(key)
220 if vch and vch[0] == chr((addrtype+128)&255):
225 def regenerate_key(sec):
226 b = ASecretToSecret(sec)
230 secret = int('0x' + b.encode('hex'), 16)
231 return EC_KEY(secret)
233 def GetPubKey(pubkey, compressed=False):
234 return i2o_ECPublicKey(pubkey, compressed)
236 def GetPrivKey(pkey, compressed=False):
237 return i2d_ECPrivateKey(pkey, compressed)
240 return ('%064x' % pkey.secret).decode('hex')
242 def is_compressed(sec):
243 b = ASecretToSecret(sec)
247 def address_from_private_key(sec):
248 # rebuild public key from private key, compressed or uncompressed
249 pkey = regenerate_key(sec)
252 # figure out if private key is compressed
253 compressed = is_compressed(sec)
255 # rebuild private and public key from regenerated secret
256 private_key = GetPrivKey(pkey, compressed)
257 public_key = GetPubKey(pkey.pubkey, compressed)
258 address = public_key_to_bc_address(public_key)
262 ########### end pywallet functions #######################
264 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
265 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
266 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
267 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
268 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
269 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
270 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
271 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
272 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
273 oid_secp256k1 = (1,3,132,0,10)
274 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
276 from ecdsa.util import string_to_number, number_to_string
278 def msg_magic(message):
279 return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message
282 class EC_KEY(object):
283 def __init__( self, secret ):
284 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
285 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
288 def sign_message(self, message, compressed, address):
289 private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
290 public_key = private_key.get_verifying_key()
291 signature = private_key.sign_digest( Hash( msg_magic(message) ), sigencode = ecdsa.util.sigencode_string )
292 assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
294 sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
296 self.verify_message( address, sig, message)
301 raise BaseException("error: cannot sign message")
304 def verify_message(self, address, signature, message):
305 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
306 from ecdsa import numbertheory, ellipticcurve, util
308 curve = curve_secp256k1
309 G = generator_secp256k1
311 # extract r,s from signature
312 sig = base64.b64decode(signature)
313 if len(sig) != 65: raise BaseException("Wrong encoding")
314 r,s = util.sigdecode_string(sig[1:], order)
316 if nV < 27 or nV >= 35:
317 raise BaseException("Bad encoding")
326 x = r + (recid/2) * order
328 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
329 beta = msqr.modular_sqrt(alpha, curve.p())
330 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
331 # 1.4 the constructor checks that nR is at infinity
332 R = ellipticcurve.Point(curve, x, y, order)
333 # 1.5 compute e from message:
334 h = Hash( msg_magic(message) )
335 e = string_to_number(h)
337 # 1.6 compute Q = r^-1 (sR - eG)
338 inv_r = numbertheory.inverse_mod(r,order)
339 Q = inv_r * ( s * R + minus_e * G )
340 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
341 # check that Q is the public key
342 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
343 # check that we get the original signing address
344 addr = public_key_to_bc_address( encode_point(public_key, compressed) )
346 raise BaseException("Bad signature")
349 ###################################### BIP32 ##############################
351 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
355 def bip32_init(seed):
358 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
360 print "seed", seed.encode('hex')
361 master_secret = I[0:32]
362 master_chain = I[32:]
366 master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
367 master_public_key = master_private_key.get_verifying_key()
368 K = master_public_key.to_string()
369 K_compressed = GetPubKey(master_public_key.pubkey,True)
370 return master_secret, master_chain, K, K_compressed
375 from ecdsa.util import string_to_number, number_to_string
376 order = generator_secp256k1.order()
377 keypair = EC_KEY(string_to_number(k))
378 K = GetPubKey(keypair.pubkey,True)
379 I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
380 k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
385 def CKD_prime(K, c, n):
387 from ecdsa.util import string_to_number, number_to_string
388 order = generator_secp256k1.order()
390 K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
391 K_compressed = GetPubKey(K_public_key.pubkey,True)
393 I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
395 #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
396 public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
397 K_n = public_key.to_string()
398 K_n_compressed = GetPubKey(public_key.pubkey,True)
401 return K_n, K_n_compressed, c_n
405 class DeterministicSequence:
406 """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
408 def __init__(self, master_public_key):
409 self.master_public_key = master_public_key
412 def from_seed(klass, seed):
414 secexp = klass.stretch_key(seed)
415 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
416 master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
417 self = klass(master_public_key)
421 def stretch_key(self,seed):
423 for i in range(100000):
424 seed = hashlib.sha256(seed + oldseed).digest()
425 return string_to_number( seed )
427 def get_sequence(self,n,for_change):
428 return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key.decode('hex') ) )
430 def get_pubkey(self, n, for_change):
432 z = self.get_sequence(n, for_change)
433 master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key.decode('hex'), curve = SECP256k1 )
434 pubkey_point = master_public_key.pubkey.point + z*curve.generator
435 public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
436 return '04' + public_key2.to_string().encode('hex')
438 def get_private_key_from_stretched_exponent(self, n, for_change, secexp):
439 order = generator_secp256k1.order()
440 secexp = ( secexp + self.get_sequence(n,for_change) ) % order
441 pk = number_to_string( secexp, generator_secp256k1.order() )
443 return SecretToASecret( pk, compressed )
445 def get_private_key(self, n, for_change, seed):
446 secexp = self.stretch_key(seed)
447 return self.get_private_key_from_stretched_exponent(n, for_change, secexp)
449 def check_seed(self, seed):
451 secexp = self.stretch_key(seed)
452 master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
453 master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
454 if master_public_key != self.master_public_key:
455 print_error('invalid password (mpk)')
456 raise BaseException('Invalid password')
460 ################################## transactions
471 def __init__(self, raw):
474 self.inputs = self.d['inputs']
475 self.outputs = self.d['outputs']
476 self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
477 self.input_info = None
480 def from_io(klass, inputs, outputs):
481 raw = klass.serialize(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
483 self.is_complete = False
485 self.outputs = outputs
487 for i in self.inputs:
488 e = { 'txid':i['tx_hash'], 'vout':i['index'], 'scriptPubKey':i.get('raw_output_script') }
490 self.input_info = extras
497 def multisig_script(klass, public_keys, num=None):
499 if num is None: num = n
500 # supports only "2 of 2", and "2 of 3" transactions
501 assert num <= n and n in [2,3]
510 for k in public_keys:
511 s += var_int(len(k)/2)
521 out = { "address": hash_160_to_bc_address(hash_160(s.decode('hex')), 5), "redeemScript":s }
525 def serialize( klass, inputs, outputs, for_sig = None ):
527 s = int_to_hex(1,4) # version
528 s += var_int( len(inputs) ) # number of inputs
529 for i in range(len(inputs)):
531 s += txin['tx_hash'].decode('hex')[::-1].encode('hex') # prev hash
532 s += int_to_hex(txin['index'],4) # prev index
535 pubkeysig = txin.get('pubkeysig')
537 pubkey, sig = pubkeysig[0]
538 sig = sig + chr(1) # hashtype
539 script = op_push( len(sig))
540 script += sig.encode('hex')
541 script += op_push( len(pubkey))
542 script += pubkey.encode('hex')
544 signatures = txin['signatures']
545 pubkeys = txin['pubkeys']
547 for sig in signatures:
549 script += op_push(len(sig)/2)
552 redeem_script = klass.multisig_script(pubkeys,2).get('redeemScript')
553 script += op_push(len(redeem_script)/2)
554 script += redeem_script
557 if txin.get('redeemScript'):
558 script = txin['redeemScript'] # p2sh uses the inner script
560 script = txin['raw_output_script'] # scriptsig
563 s += var_int( len(script)/2 ) # script length
565 s += "ffffffff" # sequence
567 s += var_int( len(outputs) ) # number of outputs
568 for output in outputs:
569 addr, amount = output
570 s += int_to_hex( amount, 8) # amount
571 addrtype, hash_160 = bc_address_to_hash_160(addr)
573 script = '76a9' # op_dup, op_hash_160
574 script += '14' # push 0x14 bytes
575 script += hash_160.encode('hex')
576 script += '88ac' # op_equalverify, op_checksig
578 script = 'a9' # op_hash_160
579 script += '14' # push 0x14 bytes
580 script += hash_160.encode('hex')
581 script += '87' # op_equal
585 s += var_int( len(script)/2 ) # script length
587 s += int_to_hex(0,4) # lock time
588 if for_sig is not None and for_sig != -1:
589 s += int_to_hex(1, 4) # hash type
594 return self.serialize(self.inputs, self.outputs, for_sig = i)
598 return Hash(self.raw.decode('hex') )[::-1].encode('hex')
600 def sign(self, private_keys):
603 for i in range(len(self.inputs)):
604 txin = self.inputs[i]
605 tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i )
607 if txin.get('redeemScript'):
608 # 1 parse the redeem script
609 num, redeem_pubkeys = deserialize.parse_redeemScript(txin.get('redeemScript'))
610 self.inputs[i]["pubkeys"] = redeem_pubkeys
612 # build list of public/private keys
614 for sec in private_keys.values():
615 compressed = is_compressed(sec)
616 pkey = regenerate_key(sec)
617 pubkey = GetPubKey(pkey.pubkey, compressed)
618 keypairs[ pubkey.encode('hex') ] = sec
620 # list of already existing signatures
621 signatures = txin.get("signatures",[])
622 print_error("signatures",signatures)
624 for pubkey in redeem_pubkeys:
625 public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
628 public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
630 except ecdsa.keys.BadSignatureError:
633 # check if we have a key corresponding to the redeem script
634 if pubkey in keypairs.keys():
636 sec = keypairs[pubkey]
637 compressed = is_compressed(sec)
638 pkey = regenerate_key(sec)
640 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
641 public_key = private_key.get_verifying_key()
642 sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
643 assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
644 signatures.append( sig.encode('hex') )
646 # for p2sh, pubkeysig is a tuple (may be incomplete)
647 self.inputs[i]["signatures"] = signatures
648 print_error("signatures",signatures)
649 self.is_complete = len(signatures) == num
652 sec = private_keys[txin['address']]
653 compressed = is_compressed(sec)
654 pkey = regenerate_key(sec)
657 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
658 public_key = private_key.get_verifying_key()
659 pkey = EC_KEY(secexp)
660 pubkey = GetPubKey(pkey.pubkey, compressed)
661 sig = private_key.sign_digest( Hash( tx_for_sig.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
662 assert public_key.verify_digest( sig, Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
664 self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
665 self.is_complete = True
667 self.raw = self.serialize( self.inputs, self.outputs )
670 def deserialize(self):
672 vds = deserialize.BCDataStream()
673 vds.write(self.raw.decode('hex'))
674 self.d = deserialize.parse_Transaction(vds)
678 def has_address(self, addr):
680 for txin in self.inputs:
681 if addr == txin.get('address'):
684 for txout in self.outputs:
691 def get_value(self, addresses, prevout_values):
692 # return the balance for that tx
695 v_in = v_out = v_out_mine = 0
697 for item in self.inputs:
698 addr = item.get('address')
699 if addr in addresses:
701 key = item['prevout_hash'] + ':%d'%item['prevout_n']
702 value = prevout_values.get( key )
710 for item in self.outputs:
713 if addr in addresses:
717 # all inputs are mine:
719 v = v_out_mine - v_in
721 # some inputs are mine:
724 v = v_out_mine - v_out
729 return is_send, v, fee
735 "complete":self.is_complete
737 if not self.is_complete and self.input_info:
738 out['input_info'] = json.dumps(self.input_info).replace(' ','')
743 seed = "ff000000000000000000000000000000".decode('hex')
744 master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
746 print "secret key", master_secret.encode('hex')
747 print "chain code", master_chain.encode('hex')
749 key_id = hash_160(master_public_key_compressed)
750 print "keyid", key_id.encode('hex')
752 print "address", hash_160_to_bc_address(key_id)
753 print "secret key", SecretToASecret(master_secret, True)
756 k0, c0 = CKD(master_secret, master_chain, 0)
757 print "secret", k0.encode('hex')
758 print "chain", c0.encode('hex')
759 print "secret key", SecretToASecret(k0, True)
761 K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
762 print "address", hash_160_to_bc_address(hash_160(K0_compressed))
765 K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
766 print "address", hash_160_to_bc_address(hash_160(K01_compressed))
768 print "-- m/0/1/3 --"
769 K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
770 print "address", hash_160_to_bc_address(hash_160(K013_compressed))
772 print "-- m/0/1/3/7 --"
773 K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
774 print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
778 if __name__ == '__main__':