1 # -*- coding: utf-8 -*-
4 # Electrum - lightweight Bitcoin client
5 # Copyright (C) 2011 thomasv@gitorious
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.
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.
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/>.
21 import hashlib, base64, ecdsa, re
24 from util import print_error
27 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
28 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
30 def pw_encode(s, password):
32 secret = Hash(password)
33 return EncodeAES(secret, s.encode("utf8"))
37 def pw_decode(s, password):
38 if password is not None:
39 secret = Hash(password)
41 d = DecodeAES(secret, s).decode("utf8")
43 raise Exception('Invalid password')
53 return s.decode('hex')[::-1].encode('hex')
55 def int_to_hex(i, length=1):
56 s = hex(i)[2:].rstrip('L')
57 s = "0"*(2*length - len(s)) + s
61 # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
65 return "fd"+int_to_hex(i,2)
67 return "fe"+int_to_hex(i,4)
69 return "ff"+int_to_hex(i,8)
75 return '4c' + int_to_hex(i)
77 return '4d' + int_to_hex(i,2)
79 return '4e' + int_to_hex(i,4)
84 return hashlib.sha256(x).digest()
87 if type(x) is unicode: x=x.encode('utf-8')
88 return sha256(sha256(x))
90 hash_encode = lambda x: x[::-1].encode('hex')
91 hash_decode = lambda x: x.decode('hex')[::-1]
92 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
94 def mnemonic_to_seed(mnemonic, passphrase):
95 from pbkdf2 import PBKDF2
98 return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
100 from version import SEED_PREFIX
101 is_new_seed = lambda x: hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')[0:2].startswith(SEED_PREFIX)
103 def is_old_seed(seed):
105 words = seed.strip().split()
107 mnemonic.mn_decode(words)
108 uses_electrum_words = True
110 uses_electrum_words = False
114 is_hex = (len(seed) == 32)
118 return is_hex or (uses_electrum_words and len(words) == 12)
121 # pywallet openssl private key implementation
123 def i2d_ECPrivateKey(pkey, compressed=False):
125 key = '3081d30201010420' + \
126 '%064x' % pkey.secret + \
127 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
129 '3006040100040107042102' + \
135 key = '308201130201010420' + \
136 '%064x' % pkey.secret + \
137 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
139 '3006040100040107044104' + \
146 return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
148 def i2o_ECPublicKey(pubkey, compressed=False):
149 # public keys are 65 bytes long (520 bits)
150 # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
151 # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
152 # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
154 if pubkey.point.y() & 1:
155 key = '03' + '%064x' % pubkey.point.x()
157 key = '02' + '%064x' % pubkey.point.x()
160 '%064x' % pubkey.point.x() + \
161 '%064x' % pubkey.point.y()
163 return key.decode('hex')
165 # end pywallet openssl private key implementation
169 ############ functions from pywallet #####################
171 def hash_160(public_key):
173 md = hashlib.new('ripemd160')
174 md.update(sha256(public_key))
178 md = ripemd.new(sha256(public_key))
182 def public_key_to_bc_address(public_key):
183 h160 = hash_160(public_key)
184 return hash_160_to_bc_address(h160)
186 def hash_160_to_bc_address(h160, addrtype = 0):
187 vh160 = chr(addrtype) + h160
189 addr = vh160 + h[0:4]
190 return b58encode(addr)
192 def bc_address_to_hash_160(addr):
193 bytes = b58decode(addr, 25)
194 return ord(bytes[0]), bytes[1:21]
197 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
198 __b58base = len(__b58chars)
201 """ encode v, which is a string of bytes, to base58."""
204 for (i, c) in enumerate(v[::-1]):
205 long_value += (256**i) * ord(c)
208 while long_value >= __b58base:
209 div, mod = divmod(long_value, __b58base)
210 result = __b58chars[mod] + result
212 result = __b58chars[long_value] + result
214 # Bitcoin does a little leading-zero-compression:
215 # leading 0-bytes in the input become leading-1s
218 if c == '\0': nPad += 1
221 return (__b58chars[0]*nPad) + result
223 def b58decode(v, length):
224 """ decode v into a string of len bytes."""
226 for (i, c) in enumerate(v[::-1]):
227 long_value += __b58chars.find(c) * (__b58base**i)
230 while long_value >= 256:
231 div, mod = divmod(long_value, 256)
232 result = chr(mod) + result
234 result = chr(long_value) + result
238 if c == __b58chars[0]: nPad += 1
241 result = chr(0)*nPad + result
242 if length is not None and len(result) != length:
248 def EncodeBase58Check(vchIn):
250 return b58encode(vchIn + hash[0:4])
252 def DecodeBase58Check(psz):
253 vchRet = b58decode(psz, None)
263 def PrivKeyToSecret(privkey):
264 return privkey[9:9+32]
266 def SecretToASecret(secret, compressed=False, addrtype=0):
267 vchIn = chr((addrtype+128)&255) + secret
268 if compressed: vchIn += '\01'
269 return EncodeBase58Check(vchIn)
271 def ASecretToSecret(key, addrtype=0):
272 vch = DecodeBase58Check(key)
273 if vch and vch[0] == chr((addrtype+128)&255):
278 def regenerate_key(sec):
279 b = ASecretToSecret(sec)
285 def GetPubKey(pubkey, compressed=False):
286 return i2o_ECPublicKey(pubkey, compressed)
288 def GetPrivKey(pkey, compressed=False):
289 return i2d_ECPrivateKey(pkey, compressed)
292 return ('%064x' % pkey.secret).decode('hex')
294 def is_compressed(sec):
295 b = ASecretToSecret(sec)
299 def public_key_from_private_key(sec):
300 # rebuild public key from private key, compressed or uncompressed
301 pkey = regenerate_key(sec)
303 compressed = is_compressed(sec)
304 public_key = GetPubKey(pkey.pubkey, compressed)
305 return public_key.encode('hex')
308 def address_from_private_key(sec):
309 public_key = public_key_from_private_key(sec)
310 address = public_key_to_bc_address(public_key.decode('hex'))
315 return is_address(addr)
318 def is_address(addr):
319 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
320 if not ADDRESS_RE.match(addr): return False
322 addrtype, h = bc_address_to_hash_160(addr)
325 return addr == hash_160_to_bc_address(h, addrtype)
328 def is_private_key(key):
330 k = ASecretToSecret(key)
331 return k is not False
336 ########### end pywallet functions #######################
339 from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
341 print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
344 from ecdsa.curves import SECP256k1
345 from ecdsa.ellipticcurve import Point
346 from ecdsa.util import string_to_number, number_to_string
348 def msg_magic(message):
349 varint = var_int(len(message))
350 encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
351 return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
354 def verify_message(address, signature, message):
356 EC_KEY.verify_message(address, signature, message)
358 except Exception as e:
359 print_error("Verification error: {0}".format(e))
363 def encrypt_message(message, pubkey):
364 return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
368 return [l[i:i+n] for i in xrange(0, len(l), n)]
371 def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
375 for offset in range(128):
377 My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
378 My = pow(My2, (_p+1)/4, _p )
380 if curved.contains_point(Mx,My):
381 if odd == bool(My&1):
383 return [_p-My,offset]
384 raise Exception('ECC_YfromX: No Y found')
386 def private_header(msg,v):
387 assert v<1, "Can't write version %d private header"%v
390 r += ('%08x'%len(msg)).decode('hex')
392 return ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
394 def public_header(pubkey,v):
395 assert v<1, "Can't write version %d public header"%v
398 r = sha256(pubkey)[:2]
399 return '\x6a\x6a' + ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
402 def negative_point(P):
403 return Point( P.curve(), P.x(), -P.y(), P.order() )
406 def point_to_ser(P, comp=True ):
408 return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
409 return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
412 def ser_to_point(Aser):
413 curve = curve_secp256k1
414 generator = generator_secp256k1
415 _r = generator.order()
416 assert Aser[0] in ['\x02','\x03','\x04']
417 if Aser[0] == '\x04':
418 return Point( curve, str_to_long(Aser[1:33]), str_to_long(Aser[33:]), _r )
419 Mx = string_to_number(Aser[1:])
420 return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
424 class EC_KEY(object):
425 def __init__( self, k ):
426 secret = string_to_number(k)
427 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
428 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
431 def get_public_key(self, compressed=True):
432 return point_to_ser(self.pubkey.point, compressed).encode('hex')
434 def sign_message(self, message, compressed, address):
435 private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
436 public_key = private_key.get_verifying_key()
437 signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
438 assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
440 sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
442 self.verify_message( address, sig, message)
447 raise Exception("error: cannot sign message")
451 def verify_message(self, address, signature, message):
452 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
453 from ecdsa import numbertheory, util
455 curve = curve_secp256k1
456 G = generator_secp256k1
458 # extract r,s from signature
459 sig = base64.b64decode(signature)
460 if len(sig) != 65: raise Exception("Wrong encoding")
461 r,s = util.sigdecode_string(sig[1:], order)
463 if nV < 27 or nV >= 35:
464 raise Exception("Bad encoding")
473 x = r + (recid/2) * order
475 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
476 beta = msqr.modular_sqrt(alpha, curve.p())
477 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
478 # 1.4 the constructor checks that nR is at infinity
479 R = Point(curve, x, y, order)
480 # 1.5 compute e from message:
481 h = Hash( msg_magic(message) )
482 e = string_to_number(h)
484 # 1.6 compute Q = r^-1 (sR - eG)
485 inv_r = numbertheory.inverse_mod(r,order)
486 Q = inv_r * ( s * R + minus_e * G )
487 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
488 # check that Q is the public key
489 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
490 # check that we get the original signing address
491 addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
493 raise Exception("Bad signature")
496 # ecdsa encryption/decryption methods
497 # credits: jackjack, https://github.com/jackjack-jj/jeeq
500 def encrypt_message(self, message, pubkey):
501 generator = generator_secp256k1
502 curved = curve_secp256k1
504 msg = private_header(message,0) + message
505 msg = msg + ('\x00'*( 32-(len(msg)%32) ))
506 msgs = chunks(msg,32)
508 _r = generator.order()
509 str_to_long = string_to_number
512 pk = ser_to_point(pubkey)
514 for i in range(len(msgs)):
515 n = ecdsa.util.randrange( pow(2,256) )
516 Mx = str_to_long(msgs[i])
517 My, xoffset = ECC_YfromX(Mx, curved)
518 M = Point( curved, Mx+xoffset, My, _r )
521 toadd = point_to_ser(T) + point_to_ser(U)
522 toadd = chr(ord(toadd[0])-2 + 2*xoffset) + toadd[1:]
525 return base64.b64encode(public_header(pubkey,0) + r)
528 def decrypt_message(self, enc):
529 G = generator_secp256k1
530 curved = curve_secp256k1
532 pubkeys = [point_to_ser(G*pvk,True), point_to_ser(G*pvk,False)]
533 enc = base64.b64decode(enc)
534 str_to_long = string_to_number
536 assert enc[:2]=='\x6a\x6a'
538 phv = str_to_long(enc[2])
539 assert phv==0, "Can't read version %d public header"%phv
540 hs = str_to_long(enc[3:5])
541 public_header=enc[5:5+hs]
542 checksum_pubkey=public_header[:2]
543 address=filter(lambda x:sha256(x)[:2]==checksum_pubkey, pubkeys)
544 assert len(address)>0, 'Bad private key'
548 for Tser,User in map(lambda x:[x[:33],x[33:]], chunks(enc,66)):
551 Tser = chr(2+(ots&1))+Tser[1:]
552 T = ser_to_point(Tser)
553 U = ser_to_point(User)
555 Mcalc = U + negative_point(V)
556 r += ('%064x'%(Mcalc.x()-xoffset)).decode('hex')
558 pvhv = str_to_long(r[0])
559 assert pvhv==0, "Can't read version %d private header"%pvhv
560 phs = str_to_long(r[1:3])
561 private_header = r[3:3+phs]
562 size = str_to_long(private_header[:4])
563 checksum = private_header[4:6]
567 hashmsg = sha256(msg)[:2]
568 checksumok = hashmsg==checksum
570 return [msg, checksumok, address]
576 ###################################### BIP32 ##############################
578 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
579 BIP32_PRIME = 0x80000000
582 def get_pubkeys_from_secret(secret):
584 private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
585 public_key = private_key.get_verifying_key()
586 K = public_key.to_string()
587 K_compressed = GetPubKey(public_key.pubkey,True)
588 return K, K_compressed
591 # Child private key derivation function (from master private key)
592 # k = master private key (32 bytes)
593 # c = master chain code (extra entropy for key derivation) (32 bytes)
594 # n = the index of the key we want to derive. (only 32 bits will be used)
595 # If n is negative (i.e. the 32nd bit is set), the resulting private key's
596 # corresponding public key can NOT be determined without the master private key.
597 # However, if n is positive, the resulting private key's corresponding
598 # public key can be determined without the master private key.
599 def CKD_priv(k, c, n):
600 is_prime = n & BIP32_PRIME
601 return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
603 def _CKD_priv(k, c, s, is_prime):
605 from ecdsa.util import string_to_number, number_to_string
606 order = generator_secp256k1.order()
608 cK = GetPubKey(keypair.pubkey,True)
609 data = chr(0) + k + s if is_prime else cK + s
610 I = hmac.new(c, data, hashlib.sha512).digest()
611 k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
615 # Child public key derivation function (from public key only)
616 # K = master public key
617 # c = master chain code
618 # n = index of key we want to derive
619 # This function allows us to find the nth public key, as long as n is
620 # non-negative. If n is negative, we need the master private key to find it.
621 def CKD_pub(cK, c, n):
622 if n & BIP32_PRIME: raise
623 return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
625 # helper function, callable with arbitrary string
626 def _CKD_pub(cK, c, s):
628 from ecdsa.util import string_to_number, number_to_string
629 order = generator_secp256k1.order()
630 I = hmac.new(c, cK + s, hashlib.sha512).digest()
632 pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
633 public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
635 cK_n = GetPubKey(public_key.pubkey,True)
640 def deserialize_xkey(xkey):
641 xkey = DecodeBase58Check(xkey)
642 assert len(xkey) == 78
643 assert xkey[0:4].encode('hex') in ["0488ade4", "0488b21e"]
645 fingerprint = xkey[5:9]
646 child_number = xkey[9:13]
648 if xkey[0:4].encode('hex') == "0488ade4":
649 K_or_k = xkey[13+33:]
651 K_or_k = xkey[13+32:]
652 return depth, fingerprint, child_number, c, K_or_k
656 def bip32_root(seed):
658 seed = seed.decode('hex')
659 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
662 K, cK = get_pubkeys_from_secret(master_k)
663 xprv = ("0488ADE4" + "00" + "00000000" + "00000000").decode("hex") + master_c + chr(0) + master_k
664 xpub = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + master_c + cK
665 return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
669 def bip32_private_derivation(xprv, branch, sequence):
670 depth, fingerprint, child_number, c, k = deserialize_xkey(xprv)
671 assert sequence.startswith(branch)
672 sequence = sequence[len(branch):]
673 for n in sequence.split('/'):
675 i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
677 k, c = CKD_priv(k, c, i)
680 _, parent_cK = get_pubkeys_from_secret(parent_k)
681 fingerprint = hash_160(parent_cK)[0:4]
682 child_number = ("%08X"%i).decode('hex')
683 K, cK = get_pubkeys_from_secret(k)
684 xprv = "0488ADE4".decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k
685 xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
686 return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
690 def bip32_public_derivation(xpub, branch, sequence):
691 depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub)
692 assert sequence.startswith(branch)
693 sequence = sequence[len(branch):]
694 for n in sequence.split('/'):
698 cK, c = CKD_pub(cK, c, i)
701 fingerprint = hash_160(parent_cK)[0:4]
702 child_number = ("%08X"%i).decode('hex')
703 xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
704 return EncodeBase58Check(xpub)
709 def bip32_private_key(sequence, k, chain):
711 k, chain = CKD_priv(k, chain, i)
712 return SecretToASecret(k, True)
717 ################################## transactions
719 MIN_RELAY_TX_FEE = 1000
723 def test_bip32(seed, sequence):
726 see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
729 xprv, xpub = bip32_root(seed)
733 assert sequence[0:2] == "m/"
735 sequence = sequence[2:]
736 for n in sequence.split('/'):
737 child_path = path + '/' + n
739 xpub2 = bip32_public_derivation(xpub, path, child_path)
740 xprv, xpub = bip32_private_derivation(xprv, path, child_path)
756 G = generator_secp256k1
758 pvk = ecdsa.util.randrange( pow(2,256) ) %_r
761 pubkey_c = point_to_ser(Pub,True)
762 pubkey_u = point_to_ser(Pub,False)
763 addr_c = public_key_to_bc_address(pubkey_c)
764 addr_u = public_key_to_bc_address(pubkey_u)
766 print "Private key ", '%064x'%pvk
767 print "Compressed public key ", pubkey_c.encode('hex')
768 print "Uncompressed public key", pubkey_u.encode('hex')
770 message = "Chancellor on brink of second bailout for banks"
771 enc = EC_KEY.encrypt_message(message,pubkey_c)
772 eck = EC_KEY(number_to_string(pvk,_r))
773 dec = eck.decrypt_message(enc)
774 print "decrypted", dec
776 signature = eck.sign_message(message, True, addr_c)
778 EC_KEY.verify_message(addr_c, signature, message)
781 if __name__ == '__main__':
783 test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
784 test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")