Added private/public key tests
authorChris Glass <tribaal@gmail.com>
Wed, 25 Jun 2014 06:27:45 +0000 (08:27 +0200)
committerChris Glass <tribaal@gmail.com>
Wed, 25 Jun 2014 06:27:45 +0000 (08:27 +0200)
Including converting from a private key to a public key, and
deriving the primary address from a private key.

lib/bitcoin.py
lib/tests/test_bitcoin.py

index 178aea3..7153ccd 100644 (file)
@@ -24,6 +24,7 @@ import sys
 import hmac
 
 from util import print_error
+from version import SEED_PREFIX
 
 try:
     import ecdsa
@@ -44,6 +45,7 @@ MIN_RELAY_TX_FEE = 1000
 EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
 DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
 
+
 def pw_encode(s, password):
     if password:
         secret = Hash(password)
@@ -51,6 +53,7 @@ def pw_encode(s, password):
     else:
         return s
 
+
 def pw_decode(s, password):
     if password is not None:
         secret = Hash(password)
@@ -63,17 +66,16 @@ def pw_decode(s, password):
         return s
 
 
-
-
-
 def rev_hex(s):
     return s.decode('hex')[::-1].encode('hex')
 
+
 def int_to_hex(i, length=1):
     s = hex(i)[2:].rstrip('L')
     s = "0"*(2*length - len(s)) + s
     return rev_hex(s)
 
+
 def var_int(i):
     # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
     if i<0xfd:
@@ -85,6 +87,7 @@ def var_int(i):
     else:
         return "ff"+int_to_hex(i,8)
 
+
 def op_push(i):
     if i<0x4c:
         return int_to_hex(i)
@@ -96,25 +99,27 @@ def op_push(i):
         return '4e' + int_to_hex(i,4)
 
 
-
 def sha256(x):
     return hashlib.sha256(x).digest()
 
+
 def Hash(x):
     if type(x) is unicode: x=x.encode('utf-8')
     return sha256(sha256(x))
 
+
 hash_encode = lambda x: x[::-1].encode('hex')
 hash_decode = lambda x: x.decode('hex')[::-1]
 hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
 
+
 def mnemonic_to_seed(mnemonic, passphrase):
     from pbkdf2 import PBKDF2
     import hmac
     PBKDF2_ROUNDS = 2048
     return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
 
-from version import SEED_PREFIX
+
 is_new_seed = lambda x: hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')[0:2].startswith(SEED_PREFIX)
 
 def is_old_seed(seed):
@@ -214,6 +219,7 @@ def bc_address_to_hash_160(addr):
 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
 __b58base = len(__b58chars)
 
+
 def b58encode(v):
     """ encode v, which is a string of bytes, to base58."""
 
@@ -237,6 +243,7 @@ def b58encode(v):
 
     return (__b58chars[0]*nPad) + result
 
+
 def b58decode(v, length):
     """ decode v into a string of len bytes."""
     long_value = 0L
@@ -266,6 +273,7 @@ def EncodeBase58Check(vchIn):
     hash = Hash(vchIn)
     return b58encode(vchIn + hash[0:4])
 
+
 def DecodeBase58Check(psz):
     vchRet = b58decode(psz, None)
     key = vchRet[0:-4]
@@ -277,9 +285,11 @@ def DecodeBase58Check(psz):
     else:
         return key
 
+
 def PrivKeyToSecret(privkey):
     return privkey[9:9+32]
 
+
 def SecretToASecret(secret, compressed=False, addrtype=0):
     vchIn = chr((addrtype+128)&255) + secret
     if compressed: vchIn += '\01'
@@ -299,15 +309,19 @@ def regenerate_key(sec):
     b = b[0:32]
     return EC_KEY(b)
 
+
 def GetPubKey(pubkey, compressed=False):
     return i2o_ECPublicKey(pubkey, compressed)
 
+
 def GetPrivKey(pkey, compressed=False):
     return i2d_ECPrivateKey(pkey, compressed)
 
+
 def GetSecret(pkey):
     return ('%064x' % pkey.secret).decode('hex')
 
+
 def is_compressed(sec):
     b = ASecretToSecret(sec)
     return len(b) == 33
@@ -694,14 +708,7 @@ def bip32_public_derivation(xpub, branch, sequence):
     return EncodeBase58Check(xpub)
 
 
-
-
 def bip32_private_key(sequence, k, chain):
     for i in sequence:
         k, chain = CKD_priv(k, chain, i)
     return SecretToASecret(k, True)
-
-
-
-
-
index 7b7a966..d4f8261 100644 (file)
@@ -5,7 +5,8 @@ from ecdsa.util import number_to_string
 from lib.bitcoin import (
     generator_secp256k1, point_to_ser, public_key_to_bc_address, EC_KEY,
     bip32_root, bip32_public_derivation, bip32_private_derivation, pw_encode,
-    pw_decode)
+    pw_decode, Hash, public_key_from_private_key, address_from_private_key,
+    is_valid, is_private_key)
 
 try:
     import ecdsa
@@ -46,20 +47,17 @@ class Test_bitcoin(unittest.TestCase):
         #print signature
         EC_KEY.verify_message(addr_c, signature, message)
 
-
-
     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")
+        xpub, xprv = self._do_test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
         assert xpub == "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"
         assert xprv == "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"
 
-        xpub, xprv = self.do_test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
+        xpub, xprv = self._do_test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
         assert xpub == "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"
         assert xprv == "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"
 
-
-    def do_test_bip32(self, seed, sequence):
+    def _do_test_bip32(self, seed, sequence):
         xprv, xpub = bip32_root(seed)
         assert sequence[0:2] == "m/"
         path = 'm'
@@ -75,12 +73,43 @@ class Test_bitcoin(unittest.TestCase):
 
         return xpub, xprv
 
+    def test_aes_homomorphic(self):
+        """Make sure AES is homomorphic."""
+        payload = u'\u66f4\u7a33\u5b9a\u7684\u4ea4\u6613\u5e73\u53f0'
+        password = u'secret'
+        enc = pw_encode(payload, password)
+        dec = pw_decode(enc, password)
+        self.assertEqual(dec, payload)
+
+    def test_hash(self):
+        """Make sure the Hash function does sha256 twice"""
+        payload = u"test"
+        expected = '\x95MZI\xfdp\xd9\xb8\xbc\xdb5\xd2R&x)\x95\x7f~\xf7\xfalt\xf8\x84\x19\xbd\xc5\xe8"\t\xf4'
+
+        result = Hash(payload)
+        self.assertEqual(expected, result)
+
+
+class Test_keyImport(unittest.TestCase):
+    """ The keys used in this class are TEST keys from
+        https://en.bitcoin.it/wiki/BIP_0032_TestVectors"""
+
+    private_key = "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW"
+    public_key_hex = "0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2"
+    main_address = "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma"
+
+    def test_public_key_from_private_key(self):
+        result = public_key_from_private_key(self.private_key)
+        self.assertEqual(self.public_key_hex, result)
+
+    def test_address_from_private_key(self):
+        result = address_from_private_key(self.private_key)
+        self.assertEqual(self.main_address, result)
 
-    def test_aes(self):
-        s = u'\u66f4\u7a33\u5b9a\u7684\u4ea4\u6613\u5e73\u53f0'
-        self.do_test_aes(s, s)
+    def test_is_valid_address(self):
+        self.assertTrue(is_valid(self.main_address))
+        self.assertFalse(is_valid("not an address"))
 
-    def do_test_aes(self, s, p):
-        enc = pw_encode(s, p)
-        dec = pw_decode(enc, p)
-        assert dec == s
+    def test_is_private_key(self):
+        self.assertTrue(is_private_key(self.private_key))
+        self.assertFalse(is_private_key(self.public_key_hex))