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
23 from util import print_error
26 return s.decode('hex')[::-1].encode('hex')
28 def int_to_hex(i, length=1):
29 s = hex(i)[2:].rstrip('L')
30 s = "0"*(2*length - len(s)) + s
34 # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
38 return "fd"+int_to_hex(i,2)
40 return "fe"+int_to_hex(i,4)
42 return "ff"+int_to_hex(i,8)
48 return '4c' + int_to_hex(i)
50 return '4d' + int_to_hex(i,2)
52 return '4e' + int_to_hex(i,4)
57 return hashlib.sha256(x).digest()
60 if type(x) is unicode: x=x.encode('utf-8')
61 return sha256(sha256(x))
63 hash_encode = lambda x: x[::-1].encode('hex')
64 hash_decode = lambda x: x.decode('hex')[::-1]
65 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
67 def mnemonic_to_seed(mnemonic, passphrase):
68 from pbkdf2 import PBKDF2
71 return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
73 from version import SEED_PREFIX
74 is_new_seed = lambda x: hmac_sha_512("Seed version", x).encode('hex')[0:2].startswith(SEED_PREFIX)
76 def is_old_seed(seed):
78 words = seed.strip().split()
80 mnemonic.mn_decode(words)
81 uses_electrum_words = True
83 uses_electrum_words = False
91 return is_hex or (uses_electrum_words and len(words) == 12)
94 # pywallet openssl private key implementation
96 def i2d_ECPrivateKey(pkey, compressed=False):
98 key = '3081d30201010420' + \
99 '%064x' % pkey.secret + \
100 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
102 '3006040100040107042102' + \
108 key = '308201130201010420' + \
109 '%064x' % pkey.secret + \
110 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
112 '3006040100040107044104' + \
119 return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
121 def i2o_ECPublicKey(pubkey, compressed=False):
122 # public keys are 65 bytes long (520 bits)
123 # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
124 # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
125 # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
127 if pubkey.point.y() & 1:
128 key = '03' + '%064x' % pubkey.point.x()
130 key = '02' + '%064x' % pubkey.point.x()
133 '%064x' % pubkey.point.x() + \
134 '%064x' % pubkey.point.y()
136 return key.decode('hex')
138 # end pywallet openssl private key implementation
142 ############ functions from pywallet #####################
144 def hash_160(public_key):
146 md = hashlib.new('ripemd160')
147 md.update(sha256(public_key))
151 md = ripemd.new(sha256(public_key))
155 def public_key_to_bc_address(public_key):
156 h160 = hash_160(public_key)
157 return hash_160_to_bc_address(h160)
159 def hash_160_to_bc_address(h160, addrtype = 0):
160 vh160 = chr(addrtype) + h160
162 addr = vh160 + h[0:4]
163 return b58encode(addr)
165 def bc_address_to_hash_160(addr):
166 bytes = b58decode(addr, 25)
167 return ord(bytes[0]), bytes[1:21]
170 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
171 __b58base = len(__b58chars)
174 """ encode v, which is a string of bytes, to base58."""
177 for (i, c) in enumerate(v[::-1]):
178 long_value += (256**i) * ord(c)
181 while long_value >= __b58base:
182 div, mod = divmod(long_value, __b58base)
183 result = __b58chars[mod] + result
185 result = __b58chars[long_value] + result
187 # Bitcoin does a little leading-zero-compression:
188 # leading 0-bytes in the input become leading-1s
191 if c == '\0': nPad += 1
194 return (__b58chars[0]*nPad) + result
196 def b58decode(v, length):
197 """ decode v into a string of len bytes."""
199 for (i, c) in enumerate(v[::-1]):
200 long_value += __b58chars.find(c) * (__b58base**i)
203 while long_value >= 256:
204 div, mod = divmod(long_value, 256)
205 result = chr(mod) + result
207 result = chr(long_value) + result
211 if c == __b58chars[0]: nPad += 1
214 result = chr(0)*nPad + result
215 if length is not None and len(result) != length:
221 def EncodeBase58Check(vchIn):
223 return b58encode(vchIn + hash[0:4])
225 def DecodeBase58Check(psz):
226 vchRet = b58decode(psz, None)
236 def PrivKeyToSecret(privkey):
237 return privkey[9:9+32]
239 def SecretToASecret(secret, compressed=False, addrtype=0):
240 vchIn = chr((addrtype+128)&255) + secret
241 if compressed: vchIn += '\01'
242 return EncodeBase58Check(vchIn)
244 def ASecretToSecret(key, addrtype=0):
245 vch = DecodeBase58Check(key)
246 if vch and vch[0] == chr((addrtype+128)&255):
251 def regenerate_key(sec):
252 b = ASecretToSecret(sec)
258 def GetPubKey(pubkey, compressed=False):
259 return i2o_ECPublicKey(pubkey, compressed)
261 def GetPrivKey(pkey, compressed=False):
262 return i2d_ECPrivateKey(pkey, compressed)
265 return ('%064x' % pkey.secret).decode('hex')
267 def is_compressed(sec):
268 b = ASecretToSecret(sec)
272 def public_key_from_private_key(sec):
273 # rebuild public key from private key, compressed or uncompressed
274 pkey = regenerate_key(sec)
276 compressed = is_compressed(sec)
277 public_key = GetPubKey(pkey.pubkey, compressed)
278 return public_key.encode('hex')
281 def address_from_private_key(sec):
282 public_key = public_key_from_private_key(sec)
283 address = public_key_to_bc_address(public_key.decode('hex'))
288 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
289 if not ADDRESS_RE.match(addr): return False
291 addrtype, h = bc_address_to_hash_160(addr)
294 return addr == hash_160_to_bc_address(h, addrtype)
297 ########### end pywallet functions #######################
300 from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
302 print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
305 from ecdsa.curves import SECP256k1
306 from ecdsa.ellipticcurve import Point
307 from ecdsa.util import string_to_number, number_to_string
309 def msg_magic(message):
310 varint = var_int(len(message))
311 encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
312 return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
315 def verify_message(address, signature, message):
317 EC_KEY.verify_message(address, signature, message)
319 except Exception as e:
320 print_error("Verification error: {0}".format(e))
324 def encrypt_message(message, pubkey):
325 return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
329 return [l[i:i+n] for i in xrange(0, len(l), n)]
332 def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
336 for offset in range(128):
338 My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
339 My = pow(My2, (_p+1)/4, _p )
341 if curved.contains_point(Mx,My):
342 if odd == bool(My&1):
344 return [_p-My,offset]
345 raise Exception('ECC_YfromX: No Y found')
347 def private_header(msg,v):
348 assert v<1, "Can't write version %d private header"%v
351 r += ('%08x'%len(msg)).decode('hex')
353 return ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
355 def public_header(pubkey,v):
356 assert v<1, "Can't write version %d public header"%v
359 r = sha256(pubkey)[:2]
360 return '\x6a\x6a' + ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
363 def negative_point(P):
364 return Point( P.curve(), P.x(), -P.y(), P.order() )
367 def point_to_ser(P, comp=True ):
369 return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
370 return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
373 def ser_to_point(Aser):
374 curve = curve_secp256k1
375 generator = generator_secp256k1
376 _r = generator.order()
377 assert Aser[0] in ['\x02','\x03','\x04']
378 if Aser[0] == '\x04':
379 return Point( curve, str_to_long(Aser[1:33]), str_to_long(Aser[33:]), _r )
380 Mx = string_to_number(Aser[1:])
381 return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
385 class EC_KEY(object):
386 def __init__( self, k ):
387 secret = string_to_number(k)
388 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
389 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
392 def get_public_key(self, compressed=True):
393 return point_to_ser(self.pubkey.point, compressed).encode('hex')
395 def sign_message(self, message, compressed, address):
396 private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
397 public_key = private_key.get_verifying_key()
398 signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
399 assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
401 sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
403 self.verify_message( address, sig, message)
408 raise Exception("error: cannot sign message")
412 def verify_message(self, address, signature, message):
413 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
414 from ecdsa import numbertheory, util
416 curve = curve_secp256k1
417 G = generator_secp256k1
419 # extract r,s from signature
420 sig = base64.b64decode(signature)
421 if len(sig) != 65: raise Exception("Wrong encoding")
422 r,s = util.sigdecode_string(sig[1:], order)
424 if nV < 27 or nV >= 35:
425 raise Exception("Bad encoding")
434 x = r + (recid/2) * order
436 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
437 beta = msqr.modular_sqrt(alpha, curve.p())
438 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
439 # 1.4 the constructor checks that nR is at infinity
440 R = Point(curve, x, y, order)
441 # 1.5 compute e from message:
442 h = Hash( msg_magic(message) )
443 e = string_to_number(h)
445 # 1.6 compute Q = r^-1 (sR - eG)
446 inv_r = numbertheory.inverse_mod(r,order)
447 Q = inv_r * ( s * R + minus_e * G )
448 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
449 # check that Q is the public key
450 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
451 # check that we get the original signing address
452 addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
454 raise Exception("Bad signature")
457 # ecdsa encryption/decryption methods
458 # credits: jackjack, https://github.com/jackjack-jj/jeeq
461 def encrypt_message(self, message, pubkey):
462 generator = generator_secp256k1
463 curved = curve_secp256k1
465 msg = private_header(message,0) + message
466 msg = msg + ('\x00'*( 32-(len(msg)%32) ))
467 msgs = chunks(msg,32)
469 _r = generator.order()
470 str_to_long = string_to_number
473 pk = ser_to_point(pubkey)
475 for i in range(len(msgs)):
476 n = ecdsa.util.randrange( pow(2,256) )
477 Mx = str_to_long(msgs[i])
478 My, xoffset = ECC_YfromX(Mx, curved)
479 M = Point( curved, Mx+xoffset, My, _r )
482 toadd = point_to_ser(T) + point_to_ser(U)
483 toadd = chr(ord(toadd[0])-2 + 2*xoffset) + toadd[1:]
486 return base64.b64encode(public_header(pubkey,0) + r)
489 def decrypt_message(self, enc):
490 G = generator_secp256k1
491 curved = curve_secp256k1
493 pubkeys = [point_to_ser(G*pvk,True), point_to_ser(G*pvk,False)]
494 enc = base64.b64decode(enc)
495 str_to_long = string_to_number
497 assert enc[:2]=='\x6a\x6a'
499 phv = str_to_long(enc[2])
500 assert phv==0, "Can't read version %d public header"%phv
501 hs = str_to_long(enc[3:5])
502 public_header=enc[5:5+hs]
503 checksum_pubkey=public_header[:2]
504 address=filter(lambda x:sha256(x)[:2]==checksum_pubkey, pubkeys)
505 assert len(address)>0, 'Bad private key'
509 for Tser,User in map(lambda x:[x[:33],x[33:]], chunks(enc,66)):
512 Tser = chr(2+(ots&1))+Tser[1:]
513 T = ser_to_point(Tser)
514 U = ser_to_point(User)
516 Mcalc = U + negative_point(V)
517 r += ('%064x'%(Mcalc.x()-xoffset)).decode('hex')
519 pvhv = str_to_long(r[0])
520 assert pvhv==0, "Can't read version %d private header"%pvhv
521 phs = str_to_long(r[1:3])
522 private_header = r[3:3+phs]
523 size = str_to_long(private_header[:4])
524 checksum = private_header[4:6]
528 hashmsg = sha256(msg)[:2]
529 checksumok = hashmsg==checksum
531 return [msg, checksumok, address]
537 ###################################### BIP32 ##############################
539 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
540 BIP32_PRIME = 0x80000000
543 def get_pubkeys_from_secret(secret):
545 private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
546 public_key = private_key.get_verifying_key()
547 K = public_key.to_string()
548 K_compressed = GetPubKey(public_key.pubkey,True)
549 return K, K_compressed
552 # Child private key derivation function (from master private key)
553 # k = master private key (32 bytes)
554 # c = master chain code (extra entropy for key derivation) (32 bytes)
555 # n = the index of the key we want to derive. (only 32 bits will be used)
556 # If n is negative (i.e. the 32nd bit is set), the resulting private key's
557 # corresponding public key can NOT be determined without the master private key.
558 # However, if n is positive, the resulting private key's corresponding
559 # public key can be determined without the master private key.
560 def CKD_priv(k, c, n):
561 is_prime = n & BIP32_PRIME
562 return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
564 def _CKD_priv(k, c, s, is_prime):
566 from ecdsa.util import string_to_number, number_to_string
567 order = generator_secp256k1.order()
569 cK = GetPubKey(keypair.pubkey,True)
570 data = chr(0) + k + s if is_prime else cK + s
571 I = hmac.new(c, data, hashlib.sha512).digest()
572 k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
576 # Child public key derivation function (from public key only)
577 # K = master public key
578 # c = master chain code
579 # n = index of key we want to derive
580 # This function allows us to find the nth public key, as long as n is
581 # non-negative. If n is negative, we need the master private key to find it.
582 def CKD_pub(cK, c, n):
583 if n & BIP32_PRIME: raise
584 return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
586 # helper function, callable with arbitrary string
587 def _CKD_pub(cK, c, s):
589 from ecdsa.util import string_to_number, number_to_string
590 order = generator_secp256k1.order()
591 I = hmac.new(c, cK + s, hashlib.sha512).digest()
593 pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
594 public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
596 cK_n = GetPubKey(public_key.pubkey,True)
601 def deserialize_xkey(xkey):
602 xkey = DecodeBase58Check(xkey)
603 assert len(xkey) == 78
604 assert xkey[0:4].encode('hex') in ["0488ade4", "0488b21e"]
606 fingerprint = xkey[5:9]
607 child_number = xkey[9:13]
609 if xkey[0:4].encode('hex') == "0488ade4":
610 K_or_k = xkey[13+33:]
612 K_or_k = xkey[13+32:]
613 return depth, fingerprint, child_number, c, K_or_k
617 def bip32_root(seed):
619 seed = seed.decode('hex')
620 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
623 K, cK = get_pubkeys_from_secret(master_k)
624 xprv = ("0488ADE4" + "00" + "00000000" + "00000000").decode("hex") + master_c + chr(0) + master_k
625 xpub = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + master_c + cK
626 return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
630 def bip32_private_derivation(xprv, branch, sequence):
631 depth, fingerprint, child_number, c, k = deserialize_xkey(xprv)
632 assert sequence.startswith(branch)
633 sequence = sequence[len(branch):]
634 for n in sequence.split('/'):
636 i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
638 k, c = CKD_priv(k, c, i)
641 _, parent_cK = get_pubkeys_from_secret(parent_k)
642 fingerprint = hash_160(parent_cK)[0:4]
643 child_number = ("%08X"%i).decode('hex')
644 K, cK = get_pubkeys_from_secret(k)
645 xprv = "0488ADE4".decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k
646 xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
647 return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
651 def bip32_public_derivation(xpub, branch, sequence):
652 depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub)
653 assert sequence.startswith(branch)
654 sequence = sequence[len(branch):]
655 for n in sequence.split('/'):
659 cK, c = CKD_pub(cK, c, i)
662 fingerprint = hash_160(parent_cK)[0:4]
663 child_number = ("%08X"%i).decode('hex')
664 xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
665 return EncodeBase58Check(xpub)
670 def bip32_private_key(sequence, k, chain):
672 k, chain = CKD_priv(k, chain, i)
673 return SecretToASecret(k, True)
678 ################################## transactions
680 MIN_RELAY_TX_FEE = 1000
684 def test_bip32(seed, sequence):
687 see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
690 xprv, xpub = bip32_root(seed)
694 assert sequence[0:2] == "m/"
696 sequence = sequence[2:]
697 for n in sequence.split('/'):
698 child_path = path + '/' + n
700 xpub2 = bip32_public_derivation(xpub, path, child_path)
701 xprv, xpub = bip32_private_derivation(xprv, path, child_path)
717 G = generator_secp256k1
719 pvk = ecdsa.util.randrange( pow(2,256) ) %_r
722 pubkey_c = point_to_ser(Pub,True)
723 pubkey_u = point_to_ser(Pub,False)
724 addr_c = public_key_to_bc_address(pubkey_c)
725 addr_u = public_key_to_bc_address(pubkey_u)
727 print "Private key ", '%064x'%pvk
728 print "Compressed public key ", pubkey_c.encode('hex')
729 print "Uncompressed public key", pubkey_u.encode('hex')
731 message = "Chancellor on brink of second bailout for banks"
732 enc = EC_KEY.encrypt_message(message,pubkey_c)
733 eck = EC_KEY(number_to_string(pvk,_r))
734 dec = eck.decrypt_message(enc)
735 print "decrypted", dec
737 signature = eck.sign_message(message, True, addr_c)
739 EC_KEY.verify_message(addr_c, signature, message)
742 if __name__ == '__main__':
744 test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
745 test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")