cleanup (dead code)
[electrum-nvc.git] / lib / bitcoin.py
index c83d5d5..aba02f8 100644 (file)
 # You should have received a copy of the GNU General Public License
 # along with this program. If not, see <http://www.gnu.org/licenses/>.
 
-
-import hashlib, base64, ecdsa, re
+import hashlib
+import base64
+import re
+import sys
 import hmac
-import aes
+
+
+try:
+    import ecdsa
+except ImportError:
+    sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
+
+try:
+    import aes
+except ImportError:
+    sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
+
+try:
+    import pbkdf2
+except ImportError:
+    sys.exit("Error: pbkdf2 does not seem to be installed. Try 'sudo pip install pbkdf2'")
+
+
+
 from util import print_error
 
+
+
 # AES encryption
 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
@@ -400,12 +422,40 @@ def ser_to_point(Aser):
     _r  = generator.order()
     assert Aser[0] in ['\x02','\x03','\x04']
     if Aser[0] == '\x04':
-        return Point( curve, str_to_long(Aser[1:33]), str_to_long(Aser[33:]), _r )
+        return Point( curve, string_to_number(Aser[1:33]), string_to_number(Aser[33:]), _r )
     Mx = string_to_number(Aser[1:])
     return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
 
 
 
+class MyVerifyingKey(ecdsa.VerifyingKey):
+    @classmethod
+    def from_signature(klass, sig, recid, h, curve):
+        """ See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """
+        from ecdsa import util, numbertheory
+        import msqr
+        curveFp = curve.curve
+        G = curve.generator
+        order = G.order()
+        # extract r,s from signature
+        r, s = util.sigdecode_string(sig, order)
+        # 1.1
+        x = r + (recid/2) * order
+        # 1.3
+        alpha = ( x * x * x  + curveFp.a() * x + curveFp.b() ) % curveFp.p()
+        beta = msqr.modular_sqrt(alpha, curveFp.p())
+        y = beta if (beta - recid) % 2 == 0 else curveFp.p() - beta
+        # 1.4 the constructor checks that nR is at infinity
+        R = Point(curveFp, x, y, order)
+        # 1.5 compute e from message:
+        e = string_to_number(h)
+        minus_e = -e % order
+        # 1.6 compute Q = r^-1 (sR - eG)
+        inv_r = numbertheory.inverse_mod(r,order)
+        Q = inv_r * ( s * R + minus_e * G )
+        return klass.from_public_point( Q, curve )
+
+
 class EC_KEY(object):
     def __init__( self, k ):
         secret = string_to_number(k)
@@ -434,16 +484,9 @@ class EC_KEY(object):
 
     @classmethod
     def verify_message(self, address, signature, message):
-        """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """
-        from ecdsa import numbertheory, util
-        import msqr
-        curve = curve_secp256k1
-        G = generator_secp256k1
-        order = G.order()
-        # extract r,s from signature
         sig = base64.b64decode(signature)
         if len(sig) != 65: raise Exception("Wrong encoding")
-        r,s = util.sigdecode_string(sig[1:], order)
+
         nV = ord(sig[0])
         if nV < 27 or nV >= 35:
             raise Exception("Bad encoding")
@@ -454,24 +497,12 @@ class EC_KEY(object):
             compressed = False
 
         recid = nV - 27
-        # 1.1
-        x = r + (recid/2) * order
-        # 1.3
-        alpha = ( x * x * x  + curve.a() * x + curve.b() ) % curve.p()
-        beta = msqr.modular_sqrt(alpha, curve.p())
-        y = beta if (beta - recid) % 2 == 0 else curve.p() - beta
-        # 1.4 the constructor checks that nR is at infinity
-        R = Point(curve, x, y, order)
-        # 1.5 compute e from message:
         h = Hash( msg_magic(message) )
-        e = string_to_number(h)
-        minus_e = -e % order
-        # 1.6 compute Q = r^-1 (sR - eG)
-        inv_r = numbertheory.inverse_mod(r,order)
-        Q = inv_r * ( s * R + minus_e * G )
-        public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 )
-        # check that Q is the public key
+        public_key = MyVerifyingKey.from_signature( sig[1:], recid, h, curve = SECP256k1 )
+
+        # check public key
         public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
+
         # check that we get the original signing address
         addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
         if address != addr:
@@ -496,35 +527,29 @@ class EC_KEY(object):
         key_e, key_m = key[:32], key[32:]
         
         iv_ciphertext = aes.encryptData(key_e, message)
-        iv, ciphertext = iv_ciphertext[:16], iv_ciphertext[16:]
 
-        mac = hmac.new(key_m, ciphertext, hashlib.sha256).digest()
         ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex')
-        
-        encrypted = 'BIE1' + hash_160(pubkey) + ephemeral_pubkey + iv + ciphertext + mac
-        return base64.b64encode(encrypted)
+        encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext
+        mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()
+
+        return base64.b64encode(encrypted + mac)
 
 
     def decrypt_message(self, encrypted):
         
         encrypted = base64.b64decode(encrypted)
         
-        if len(encrypted) < 105:
+        if len(encrypted) < 85:
             raise Exception('invalid ciphertext: length')
         
         magic = encrypted[:4]
-        recipient_pubkeyhash = encrypted[4:24]
-        ephemeral_pubkey = encrypted[24:57]
-        iv = encrypted[57:73]
-        ciphertext = encrypted[73:-32]
+        ephemeral_pubkey = encrypted[4:37]
+        iv_ciphertext = encrypted[37:-32]
         mac = encrypted[-32:]
         
         if magic != 'BIE1':
             raise Exception('invalid ciphertext: invalid magic bytes')
         
-        if hash_160(self.get_public_key().decode('hex')) != recipient_pubkeyhash:
-            raise Exception('invalid ciphertext: invalid key')
-        
         try:
             ephemeral_pubkey = ser_to_point(ephemeral_pubkey)
         except AssertionError, e:
@@ -537,11 +562,10 @@ class EC_KEY(object):
         ecdh_key = ('%064x' % ecdh_key).decode('hex')
         key = hashlib.sha512(ecdh_key).digest()
         key_e, key_m = key[:32], key[32:]
-        if mac != hmac.new(key_m, ciphertext, hashlib.sha256).digest():
+        if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest():
             raise Exception('invalid ciphertext: invalid mac')
 
-        return aes.decryptData(key_e, iv + ciphertext)
-
+        return aes.decryptData(key_e, iv_ciphertext)
 
 
 ###################################### BIP32 ##############################
@@ -691,67 +715,80 @@ MIN_RELAY_TX_FEE = 1000
 
 
 
-def test_bip32(seed, sequence):
-    """
-    run a test vector,
-    see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
-    """
+import unittest
+class Test_bitcoin(unittest.TestCase):
 
-    xprv, xpub = bip32_root(seed)
-    print xpub
-    print xprv
+    def test_crypto(self):
+        for message in ["Chancellor on brink of second bailout for banks", chr(255)*512]:
+            self.do_test_crypto(message)
 
-    assert sequence[0:2] == "m/"
-    path = 'm'
-    sequence = sequence[2:]
-    for n in sequence.split('/'):
-        child_path = path + '/' + n
-        if n[-1] != "'":
-            xpub2 = bip32_public_derivation(xpub, path, child_path)
-        xprv, xpub = bip32_private_derivation(xprv, path, child_path)
-        if n[-1] != "'":
-            assert xpub == xpub2
-        
+    def do_test_crypto(self, message):
+        G = generator_secp256k1
+        _r  = G.order()
+        pvk = ecdsa.util.randrange( pow(2,256) ) %_r
 
-        path = child_path
-        print path
-        print xpub
-        print xprv
+        Pub = pvk*G
+        pubkey_c = point_to_ser(Pub,True)
+        pubkey_u = point_to_ser(Pub,False)
+        addr_c = public_key_to_bc_address(pubkey_c)
+        addr_u = public_key_to_bc_address(pubkey_u)
+
+        #print "Private key            ", '%064x'%pvk
+        eck = EC_KEY(number_to_string(pvk,_r))
+
+        #print "Compressed public key  ", pubkey_c.encode('hex')
+        enc = EC_KEY.encrypt_message(message, pubkey_c)
+        dec = eck.decrypt_message(enc)
+        assert dec == message
+
+        #print "Uncompressed public key", pubkey_u.encode('hex')
+        enc2 = EC_KEY.encrypt_message(message, pubkey_u)
+        dec2 = eck.decrypt_message(enc)
+        assert dec2 == message
+
+        signature = eck.sign_message(message, True, addr_c)
+        #print signature
+        EC_KEY.verify_message(addr_c, signature, message)
 
-    print "----"
 
-        
 
-def test_crypto():
+    def test_bip32(self):
+        # see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
+        xpub, xprv = self.do_test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
+        assert xpub == "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"
+        assert xprv == "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"
 
-    G = generator_secp256k1
-    _r  = G.order()
-    pvk = ecdsa.util.randrange( pow(2,256) ) %_r
+        xpub, xprv = self.do_test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
+        assert xpub == "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"
+        assert xprv == "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"
 
-    Pub = pvk*G
-    pubkey_c = point_to_ser(Pub,True)
-    pubkey_u = point_to_ser(Pub,False)
-    addr_c = public_key_to_bc_address(pubkey_c)
-    addr_u = public_key_to_bc_address(pubkey_u)
 
-    print "Private key            ", '%064x'%pvk
-    print "Compressed public key  ", pubkey_c.encode('hex')
-    print "Uncompressed public key", pubkey_u.encode('hex')
+    def do_test_bip32(self, seed, sequence):
+        xprv, xpub = bip32_root(seed)
+        assert sequence[0:2] == "m/"
+        path = 'm'
+        sequence = sequence[2:]
+        for n in sequence.split('/'):
+            child_path = path + '/' + n
+            if n[-1] != "'":
+                xpub2 = bip32_public_derivation(xpub, path, child_path)
+            xprv, xpub = bip32_private_derivation(xprv, path, child_path)
+            if n[-1] != "'":
+                assert xpub == xpub2
+            path = child_path
 
-    message = "Chancellor on brink of second bailout for banks"
-    enc = EC_KEY.encrypt_message(message,pubkey_c)
-    eck = EC_KEY(number_to_string(pvk,_r))
-    dec = eck.decrypt_message(enc)
-    print "decrypted", dec
+        return xpub, xprv
 
-    signature = eck.sign_message(message, True, addr_c)
-    print signature
-    EC_KEY.verify_message(addr_c, signature, message)
 
+    def test_aes(self):
+        s = u'\u66f4\u7a33\u5b9a\u7684\u4ea4\u6613\u5e73\u53f0'
+        self.do_test_aes(s, s)
 
-if __name__ == '__main__':
-    test_crypto()
-    test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
-    test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
+    def do_test_aes(self, s, p):
+        enc = pw_encode(s, p)
+        dec = pw_decode(enc, p)
+        assert dec == s
 
 
+if __name__ == "__main__":
+    unittest.main()