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_seed = lambda x: hmac_sha_512("Seed version", x).encode('hex')[0:2].startswith(SEED_PREFIX)
76 # pywallet openssl private key implementation
78 def i2d_ECPrivateKey(pkey, compressed=False):
80 key = '3081d30201010420' + \
81 '%064x' % pkey.secret + \
82 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
84 '3006040100040107042102' + \
90 key = '308201130201010420' + \
91 '%064x' % pkey.secret + \
92 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
94 '3006040100040107044104' + \
101 return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
103 def i2o_ECPublicKey(pubkey, compressed=False):
104 # public keys are 65 bytes long (520 bits)
105 # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
106 # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
107 # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
109 if pubkey.point.y() & 1:
110 key = '03' + '%064x' % pubkey.point.x()
112 key = '02' + '%064x' % pubkey.point.x()
115 '%064x' % pubkey.point.x() + \
116 '%064x' % pubkey.point.y()
118 return key.decode('hex')
120 # end pywallet openssl private key implementation
124 ############ functions from pywallet #####################
126 def hash_160(public_key):
128 md = hashlib.new('ripemd160')
129 md.update(sha256(public_key))
133 md = ripemd.new(sha256(public_key))
137 def public_key_to_bc_address(public_key):
138 h160 = hash_160(public_key)
139 return hash_160_to_bc_address(h160)
141 def hash_160_to_bc_address(h160, addrtype = 0):
142 vh160 = chr(addrtype) + h160
144 addr = vh160 + h[0:4]
145 return b58encode(addr)
147 def bc_address_to_hash_160(addr):
148 bytes = b58decode(addr, 25)
149 return ord(bytes[0]), bytes[1:21]
152 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
153 __b58base = len(__b58chars)
156 """ encode v, which is a string of bytes, to base58."""
159 for (i, c) in enumerate(v[::-1]):
160 long_value += (256**i) * ord(c)
163 while long_value >= __b58base:
164 div, mod = divmod(long_value, __b58base)
165 result = __b58chars[mod] + result
167 result = __b58chars[long_value] + result
169 # Bitcoin does a little leading-zero-compression:
170 # leading 0-bytes in the input become leading-1s
173 if c == '\0': nPad += 1
176 return (__b58chars[0]*nPad) + result
178 def b58decode(v, length):
179 """ decode v into a string of len bytes."""
181 for (i, c) in enumerate(v[::-1]):
182 long_value += __b58chars.find(c) * (__b58base**i)
185 while long_value >= 256:
186 div, mod = divmod(long_value, 256)
187 result = chr(mod) + result
189 result = chr(long_value) + result
193 if c == __b58chars[0]: nPad += 1
196 result = chr(0)*nPad + result
197 if length is not None and len(result) != length:
203 def EncodeBase58Check(vchIn):
205 return b58encode(vchIn + hash[0:4])
207 def DecodeBase58Check(psz):
208 vchRet = b58decode(psz, None)
218 def PrivKeyToSecret(privkey):
219 return privkey[9:9+32]
221 def SecretToASecret(secret, compressed=False, addrtype=0):
222 vchIn = chr((addrtype+128)&255) + secret
223 if compressed: vchIn += '\01'
224 return EncodeBase58Check(vchIn)
226 def ASecretToSecret(key, addrtype=0):
227 vch = DecodeBase58Check(key)
228 if vch and vch[0] == chr((addrtype+128)&255):
233 def regenerate_key(sec):
234 b = ASecretToSecret(sec)
240 def GetPubKey(pubkey, compressed=False):
241 return i2o_ECPublicKey(pubkey, compressed)
243 def GetPrivKey(pkey, compressed=False):
244 return i2d_ECPrivateKey(pkey, compressed)
247 return ('%064x' % pkey.secret).decode('hex')
249 def is_compressed(sec):
250 b = ASecretToSecret(sec)
254 def public_key_from_private_key(sec):
255 # rebuild public key from private key, compressed or uncompressed
256 pkey = regenerate_key(sec)
258 compressed = is_compressed(sec)
259 public_key = GetPubKey(pkey.pubkey, compressed)
260 return public_key.encode('hex')
263 def address_from_private_key(sec):
264 public_key = public_key_from_private_key(sec)
265 address = public_key_to_bc_address(public_key.decode('hex'))
270 ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
271 if not ADDRESS_RE.match(addr): return False
273 addrtype, h = bc_address_to_hash_160(addr)
276 return addr == hash_160_to_bc_address(h, addrtype)
279 ########### end pywallet functions #######################
282 from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
284 print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
287 from ecdsa.curves import SECP256k1
288 from ecdsa.ellipticcurve import Point
289 from ecdsa.util import string_to_number, number_to_string
291 def msg_magic(message):
292 varint = var_int(len(message))
293 encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
294 return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
297 def verify_message(address, signature, message):
299 EC_KEY.verify_message(address, signature, message)
301 except Exception as e:
302 print_error("Verification error: {0}".format(e))
307 return [l[i:i+n] for i in xrange(0, len(l), n)]
310 def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
314 for offset in range(128):
316 My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
317 My = pow(My2, (_p+1)/4, _p )
319 if curved.contains_point(Mx,My):
320 if odd == bool(My&1):
322 return [_p-My,offset]
323 raise Exception('ECC_YfromX: No Y found')
325 def private_header(msg,v):
326 assert v<1, "Can't write version %d private header"%v
329 r += ('%08x'%len(msg)).decode('hex')
331 return ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
333 def public_header(pubkey,v):
334 assert v<1, "Can't write version %d public header"%v
337 r = sha256(pubkey)[:2]
338 return '\x6a\x6a' + ('%02x'%v).decode('hex') + ('%04x'%len(r)).decode('hex') + r
341 def negative_point(P):
342 return Point( P.curve(), P.x(), -P.y(), P.order() )
345 def point_to_ser(P, comp=True ):
347 return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
348 return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
351 def encode_point(pubkey, compressed=False):
352 order = generator_secp256k1.order()
353 p = pubkey.pubkey.point
354 x_str = ecdsa.util.number_to_string(p.x(), order)
355 y_str = ecdsa.util.number_to_string(p.y(), order)
357 return chr(2 + (p.y() & 1)) + x_str
359 return chr(4) + pubkey.to_string() #x_str + y_str
362 def ser_to_point(Aser):
363 curve = curve_secp256k1
364 generator = generator_secp256k1
365 _r = generator.order()
366 assert Aser[0] in ['\x02','\x03','\x04']
367 if Aser[0] == '\x04':
368 return Point( curve, str_to_long(Aser[1:33]), str_to_long(Aser[33:]), _r )
369 Mx = string_to_number(Aser[1:])
370 return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
374 class EC_KEY(object):
375 def __init__( self, k ):
376 secret = string_to_number(k)
377 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
378 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
381 def sign_message(self, message, compressed, address):
382 private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
383 public_key = private_key.get_verifying_key()
384 signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
385 assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
387 sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
389 self.verify_message( address, sig, message)
394 raise Exception("error: cannot sign message")
398 def verify_message(self, address, signature, message):
399 """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
400 from ecdsa import numbertheory, util
402 curve = curve_secp256k1
403 G = generator_secp256k1
405 # extract r,s from signature
406 sig = base64.b64decode(signature)
407 if len(sig) != 65: raise Exception("Wrong encoding")
408 r,s = util.sigdecode_string(sig[1:], order)
410 if nV < 27 or nV >= 35:
411 raise Exception("Bad encoding")
420 x = r + (recid/2) * order
422 alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p()
423 beta = msqr.modular_sqrt(alpha, curve.p())
424 y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
425 # 1.4 the constructor checks that nR is at infinity
426 R = Point(curve, x, y, order)
427 # 1.5 compute e from message:
428 h = Hash( msg_magic(message) )
429 e = string_to_number(h)
431 # 1.6 compute Q = r^-1 (sR - eG)
432 inv_r = numbertheory.inverse_mod(r,order)
433 Q = inv_r * ( s * R + minus_e * G )
434 public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
435 # check that Q is the public key
436 public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
437 # check that we get the original signing address
438 addr = public_key_to_bc_address( encode_point(public_key, compressed) )
440 raise Exception("Bad signature")
443 # ecdsa encryption/decryption methods
444 # credits: jackjack, https://github.com/jackjack-jj/jeeq
447 def encrypt_message(self, message, pubkey):
448 generator = generator_secp256k1
449 curved = curve_secp256k1
451 msg = private_header(message,0) + message
452 msg = msg + ('\x00'*( 32-(len(msg)%32) ))
453 msgs = chunks(msg,32)
455 _r = generator.order()
456 str_to_long = string_to_number
459 if len(pubkey)==33: #compressed
460 pk = Point( curve_secp256k1, str_to_long(pubkey[1:33]), ECC_YfromX(str_to_long(pubkey[1:33]), curve_secp256k1, pubkey[0]=='\x03')[0], _r )
462 pk = Point( curve_secp256k1, str_to_long(pubkey[1:33]), str_to_long(pubkey[33:65]), _r )
464 for i in range(len(msgs)):
465 n = ecdsa.util.randrange( pow(2,256) )
466 Mx = str_to_long(msgs[i])
467 My, xoffset = ECC_YfromX(Mx, curved)
468 M = Point( curved, Mx+xoffset, My, _r )
471 toadd = point_to_ser(T) + point_to_ser(U)
472 toadd = chr(ord(toadd[0])-2 + 2*xoffset) + toadd[1:]
475 return base64.b64encode(public_header(pubkey,0) + r)
478 def decrypt_message(self, enc):
479 G = generator_secp256k1
480 curved = curve_secp256k1
482 pubkeys = [point_to_ser(G*pvk,True), point_to_ser(G*pvk,False)]
483 enc = base64.b64decode(enc)
484 str_to_long = string_to_number
486 assert enc[:2]=='\x6a\x6a'
488 phv = str_to_long(enc[2])
489 assert phv==0, "Can't read version %d public header"%phv
490 hs = str_to_long(enc[3:5])
491 public_header=enc[5:5+hs]
492 checksum_pubkey=public_header[:2]
493 address=filter(lambda x:sha256(x)[:2]==checksum_pubkey, pubkeys)
494 assert len(address)>0, 'Bad private key'
498 for Tser,User in map(lambda x:[x[:33],x[33:]], chunks(enc,66)):
501 Tser = chr(2+(ots&1))+Tser[1:]
502 T = ser_to_point(Tser)
503 U = ser_to_point(User)
505 Mcalc = U + negative_point(V)
506 r += ('%064x'%(Mcalc.x()-xoffset)).decode('hex')
508 pvhv = str_to_long(r[0])
509 assert pvhv==0, "Can't read version %d private header"%pvhv
510 phs = str_to_long(r[1:3])
511 private_header = r[3:3+phs]
512 size = str_to_long(private_header[:4])
513 checksum = private_header[4:6]
517 hashmsg = sha256(msg)[:2]
518 checksumok = hashmsg==checksum
520 return [msg, checksumok, address]
526 ###################################### BIP32 ##############################
528 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
529 BIP32_PRIME = 0x80000000
531 def bip32_init(seed):
533 seed = seed.decode('hex')
534 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
536 master_secret = I[0:32]
537 master_chain = I[32:]
539 K, K_compressed = get_pubkeys_from_secret(master_secret)
540 return master_secret, master_chain, K, K_compressed
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
553 # Child private key derivation function (from master private key)
554 # k = master private key (32 bytes)
555 # c = master chain code (extra entropy for key derivation) (32 bytes)
556 # n = the index of the key we want to derive. (only 32 bits will be used)
557 # If n is negative (i.e. the 32nd bit is set), the resulting private key's
558 # corresponding public key can NOT be determined without the master private key.
559 # However, if n is positive, the resulting private key's corresponding
560 # public key can be determined without the master private key.
563 from ecdsa.util import string_to_number, number_to_string
564 order = generator_secp256k1.order()
566 K = GetPubKey(keypair.pubkey,True)
568 if n & BIP32_PRIME: # We want to make a "secret" address that can't be determined from K
569 data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex')
570 I = hmac.new(c, data, hashlib.sha512).digest()
571 else: # We want a "non-secret" address that can be determined from K
572 I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
574 k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
578 # Child public key derivation function (from public key only)
579 # K = master public key
580 # c = master chain code
581 # n = index of key we want to derive
582 # This function allows us to find the nth public key, as long as n is
583 # non-negative. If n is negative, we need the master private key to find it.
584 def CKD_prime(K, c, n):
586 from ecdsa.util import string_to_number, number_to_string
587 order = generator_secp256k1.order()
589 if n & BIP32_PRIME: raise
591 K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
592 K_compressed = GetPubKey(K_public_key.pubkey,True)
594 I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
597 pubkey_point = string_to_number(I[0:32])*curve.generator + K_public_key.pubkey.point
598 public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
600 K_n = public_key.to_string()
601 K_n_compressed = GetPubKey(public_key.pubkey,True)
604 return K_n, K_n_compressed, c_n
608 def bip32_private_derivation(k, c, branch, sequence):
609 assert sequence.startswith(branch)
610 sequence = sequence[len(branch):]
611 for n in sequence.split('/'):
613 n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
615 K, K_compressed = get_pubkeys_from_secret(k)
616 return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex')
619 def bip32_public_derivation(c, K, branch, sequence):
620 assert sequence.startswith(branch)
621 sequence = sequence[len(branch):]
622 for n in sequence.split('/'):
624 K, cK, c = CKD_prime(K, c, n)
626 return c.encode('hex'), K.encode('hex'), cK.encode('hex')
629 def bip32_private_key(sequence, k, chain):
631 k, chain = CKD(k, chain, i)
632 return SecretToASecret(k, True)
637 ################################## transactions
639 MIN_RELAY_TX_FEE = 10000
643 def test_bip32(seed, sequence):
646 see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
649 master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
651 print "secret key", master_secret.encode('hex')
652 print "chain code", master_chain.encode('hex')
654 key_id = hash_160(master_public_key_compressed)
655 print "keyid", key_id.encode('hex')
657 print "address", hash_160_to_bc_address(key_id)
658 print "secret key", SecretToASecret(master_secret, True)
664 for n in sequence.split('/'):
666 print "Chain [%s]" % '/'.join(s)
668 n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
669 k0, c0 = CKD(k, c, n)
670 K0, K0_compressed = get_pubkeys_from_secret(k0)
673 print " * (main addr)", hash_160_to_bc_address(hash_160(K0_compressed))
676 print " * (hex)", k0.encode('hex')
677 print " * (wif)", SecretToASecret(k0, True)
680 print " * (hex)", c0.encode('hex')
690 G = generator_secp256k1
692 pvk = ecdsa.util.randrange( pow(2,256) ) %_r
695 pubkey_c = point_to_ser(Pub,True)
696 pubkey_u = point_to_ser(Pub,False)
697 addr_c = public_key_to_bc_address(pubkey_c)
698 addr_u = public_key_to_bc_address(pubkey_u)
700 print "Private key ", '%064x'%pvk
701 print "Compressed public key ", pubkey_c.encode('hex')
702 print "Uncompressed public key", pubkey_u.encode('hex')
704 message = "Chancellor on brink of second bailout for banks"
705 enc = EC_KEY.encrypt_message(message,pubkey_c)
706 eck = EC_KEY(number_to_string(pvk,_r))
707 dec = eck.decrypt_message(enc)
708 print "decrypted", dec
710 signature = eck.sign_message(message, True, addr_c)
712 EC_KEY.verify_message(addr_c, signature, message)
715 if __name__ == '__main__':
717 #test_bip32("000102030405060708090a0b0c0d0e0f", "0'/1/2'/2/1000000000")
718 #test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","0/2147483647'/1/2147483646'/2")