new class: Imported_Wallet
[electrum-nvc.git] / lib / bitcoin.py
index 37cd60f..44174d2 100644 (file)
@@ -71,7 +71,25 @@ def mnemonic_to_seed(mnemonic, passphrase):
     return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
 
 from version import SEED_PREFIX
-is_seed = lambda x: hmac_sha_512("Seed version", x).encode('hex')[0:2].startswith(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):
+    import mnemonic
+    words = seed.strip().split()
+    try:
+        mnemonic.mn_decode(words)
+        uses_electrum_words = True
+    except Exception:
+        uses_electrum_words = False
+
+    try:
+        seed.decode('hex')
+        is_hex = (len(seed) == 32)
+    except Exception:
+        is_hex = False
+         
+    return is_hex or (uses_electrum_words and len(words) == 12)
+
 
 # pywallet openssl private key implementation
 
@@ -267,6 +285,10 @@ def address_from_private_key(sec):
 
 
 def is_valid(addr):
+    return is_address(addr)
+
+
+def is_address(addr):
     ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
     if not ADDRESS_RE.match(addr): return False
     try:
@@ -276,6 +298,10 @@ def is_valid(addr):
     return addr == hash_160_to_bc_address(h, addrtype)
 
 
+def is_private_key(key):
+    return ASecretToSecret(key) is not False
+
+
 ########### end pywallet functions #######################
 
 try:
@@ -303,6 +329,10 @@ def verify_message(address, signature, message):
         return False
 
 
+def encrypt_message(message, pubkey):
+    return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
+
+
 def chunks(l, n):
     return [l[i:i+n] for i in xrange(0, len(l), n)]
 
@@ -348,17 +378,6 @@ def point_to_ser(P, comp=True ):
     return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
 
 
-def encode_point(pubkey, compressed=False):
-    order = generator_secp256k1.order()
-    p = pubkey.pubkey.point
-    x_str = ecdsa.util.number_to_string(p.x(), order)
-    y_str = ecdsa.util.number_to_string(p.y(), order)
-    if compressed:
-        return chr(2 + (p.y() & 1)) + x_str
-    else:
-        return chr(4) + pubkey.to_string() #x_str + y_str
-
-
 def ser_to_point(Aser):
     curve = curve_secp256k1
     generator = generator_secp256k1
@@ -378,6 +397,9 @@ class EC_KEY(object):
         self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
         self.secret = secret
 
+    def get_public_key(self, compressed=True):
+        return point_to_ser(self.pubkey.point, compressed).encode('hex')
+
     def sign_message(self, message, compressed, address):
         private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
         public_key = private_key.get_verifying_key()
@@ -435,7 +457,7 @@ class EC_KEY(object):
         # check that Q is the 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( encode_point(public_key, compressed) )
+        addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
         if address != addr:
             raise Exception("Bad signature")
 
@@ -456,10 +478,7 @@ class EC_KEY(object):
         str_to_long = string_to_number
 
         P = generator
-        if len(pubkey)==33: #compressed
-            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 )
-        else:
-            pk = Point( curve_secp256k1, str_to_long(pubkey[1:33]), str_to_long(pubkey[33:65]), _r )
+        pk = ser_to_point(pubkey)
 
         for i in range(len(msgs)):
             n = ecdsa.util.randrange( pow(2,256) )
@@ -528,17 +547,6 @@ class EC_KEY(object):
 random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
 BIP32_PRIME = 0x80000000
 
-def bip32_init(seed):
-    import hmac
-    seed = seed.decode('hex')        
-    I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
-
-    master_secret = I[0:32]
-    master_chain = I[32:]
-
-    K, K_compressed = get_pubkeys_from_secret(master_secret)
-    return master_secret, master_chain, K, K_compressed
-
 
 def get_pubkeys_from_secret(secret):
     # public key
@@ -549,7 +557,6 @@ def get_pubkeys_from_secret(secret):
     return K, K_compressed
 
 
-
 # Child private key derivation function (from master private key)
 # k = master private key (32 bytes)
 # c = master chain code (extra entropy for key derivation) (32 bytes)
@@ -558,19 +565,18 @@ def get_pubkeys_from_secret(secret):
 #  corresponding public key can NOT be determined without the master private key.
 # However, if n is positive, the resulting private key's corresponding
 #  public key can be determined without the master private key.
-def CKD(k, c, n):
+def CKD_priv(k, c, n):
+    is_prime = n & BIP32_PRIME
+    return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
+
+def _CKD_priv(k, c, s, is_prime):
     import hmac
     from ecdsa.util import string_to_number, number_to_string
     order = generator_secp256k1.order()
     keypair = EC_KEY(k)
-    K = GetPubKey(keypair.pubkey,True)
-
-    if n & BIP32_PRIME: # We want to make a "secret" address that can't be determined from K
-        data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex')
-        I = hmac.new(c, data, hashlib.sha512).digest()
-    else: # We want a "non-secret" address that can be determined from K
-        I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
-        
+    cK = GetPubKey(keypair.pubkey,True)
+    data = chr(0) + k + s if is_prime else cK + s
+    I = hmac.new(c, data, hashlib.sha512).digest()
     k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
     c_n = I[32:]
     return k_n, c_n
@@ -581,54 +587,97 @@ def CKD(k, c, n):
 # n = index of key we want to derive
 # This function allows us to find the nth public key, as long as n is 
 #  non-negative. If n is negative, we need the master private key to find it.
-def CKD_prime(K, c, n):
+def CKD_pub(cK, c, n):
+    if n & BIP32_PRIME: raise
+    return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
+
+# helper function, callable with arbitrary string
+def _CKD_pub(cK, c, s):
     import hmac
     from ecdsa.util import string_to_number, number_to_string
     order = generator_secp256k1.order()
+    I = hmac.new(c, cK + s, hashlib.sha512).digest()
+    curve = SECP256k1
+    pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
+    public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
+    c_n = I[32:]
+    cK_n = GetPubKey(public_key.pubkey,True)
+    return cK_n, c_n
 
-    if n & BIP32_PRIME: raise
 
-    K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
-    K_compressed = GetPubKey(K_public_key.pubkey,True)
 
-    I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
+def deserialize_xkey(xkey):
+    xkey = DecodeBase58Check(xkey) 
+    assert len(xkey) == 78
+    assert xkey[0:4].encode('hex') in ["0488ade4", "0488b21e"]
+    depth = ord(xkey[4])
+    fingerprint = xkey[5:9]
+    child_number = xkey[9:13]
+    c = xkey[13:13+32]
+    if xkey[0:4].encode('hex') == "0488ade4":
+        K_or_k = xkey[13+33:]
+    else:
+        K_or_k = xkey[13+32:]
+    return depth, fingerprint, child_number, c, K_or_k
 
-    curve = SECP256k1
-    pubkey_point = string_to_number(I[0:32])*curve.generator + K_public_key.pubkey.point
-    public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
 
-    K_n = public_key.to_string()
-    K_n_compressed = GetPubKey(public_key.pubkey,True)
-    c_n = I[32:]
 
-    return K_n, K_n_compressed, c_n
+def bip32_root(seed):
+    import hmac
+    seed = seed.decode('hex')        
+    I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
+    master_k = I[0:32]
+    master_c = I[32:]
+    K, cK = get_pubkeys_from_secret(master_k)
+    xprv = ("0488ADE4" + "00" + "00000000" + "00000000").decode("hex") + master_c + chr(0) + master_k
+    xpub = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + master_c + cK
+    return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
 
 
 
-def bip32_private_derivation(k, c, branch, sequence):
+def bip32_private_derivation(xprv, branch, sequence):
+    depth, fingerprint, child_number, c, k = deserialize_xkey(xprv)
     assert sequence.startswith(branch)
     sequence = sequence[len(branch):]
     for n in sequence.split('/'):
         if n == '': continue
-        n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
-        k, c = CKD(k, c, n)
-    K, K_compressed = get_pubkeys_from_secret(k)
-    return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex')
+        i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
+        parent_k = k
+        k, c = CKD_priv(k, c, i)
+        depth += 1
+
+    _, parent_cK = get_pubkeys_from_secret(parent_k)
+    fingerprint = hash_160(parent_cK)[0:4]
+    child_number = ("%08X"%i).decode('hex')
+    K, cK = get_pubkeys_from_secret(k)
+    xprv = "0488ADE4".decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k
+    xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
+    return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
+
 
 
-def bip32_public_derivation(c, K, branch, sequence):
+def bip32_public_derivation(xpub, branch, sequence):
+    depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub)
     assert sequence.startswith(branch)
     sequence = sequence[len(branch):]
     for n in sequence.split('/'):
-        n = int(n)
-        K, cK, c = CKD_prime(K, c, n)
+        if n == '': continue
+        i = int(n)
+        parent_cK = cK
+        cK, c = CKD_pub(cK, c, i)
+        depth += 1
+
+    fingerprint = hash_160(parent_cK)[0:4]
+    child_number = ("%08X"%i).decode('hex')
+    xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
+    return EncodeBase58Check(xpub)
+
 
-    return c.encode('hex'), K.encode('hex'), cK.encode('hex')
 
 
 def bip32_private_key(sequence, k, chain):
     for i in sequence:
-        k, chain = CKD(k, chain, i)
+        k, chain = CKD_priv(k, chain, i)
     return SecretToASecret(k, True)
 
 
@@ -636,7 +685,7 @@ def bip32_private_key(sequence, k, chain):
 
 ################################## transactions
 
-MIN_RELAY_TX_FEE = 10000
+MIN_RELAY_TX_FEE = 1000
 
 
 
@@ -646,41 +695,27 @@ def test_bip32(seed, sequence):
     see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
     """
 
-    master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
-        
-    print "secret key", master_secret.encode('hex')
-    print "chain code", master_chain.encode('hex')
-
-    key_id = hash_160(master_public_key_compressed)
-    print "keyid", key_id.encode('hex')
-    print "base58"
-    print "address", hash_160_to_bc_address(key_id)
-    print "secret key", SecretToASecret(master_secret, True)
-
-    k = master_secret
-    c = master_chain
+    xprv, xpub = bip32_root(seed)
+    print xpub
+    print xprv
 
-    s = ['m']
+    assert sequence[0:2] == "m/"
+    path = 'm'
+    sequence = sequence[2:]
     for n in sequence.split('/'):
-        s.append(n)
-        print "Chain [%s]" % '/'.join(s)
+        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
         
-        n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
-        k0, c0 = CKD(k, c, n)
-        K0, K0_compressed = get_pubkeys_from_secret(k0)
 
-        print "* Identifier"
-        print "  * (main addr)", hash_160_to_bc_address(hash_160(K0_compressed))
+        path = child_path
+        print path
+        print xpub
+        print xprv
 
-        print "* Secret Key"
-        print "  * (hex)", k0.encode('hex')
-        print "  * (wif)", SecretToASecret(k0, True)
-
-        print "* Chain Code"
-        print "   * (hex)", c0.encode('hex')
-
-        k = k0
-        c = c0
     print "----"
 
         
@@ -713,7 +748,8 @@ def test_crypto():
 
 
 if __name__ == '__main__':
-    test_crypto()
-    #test_bip32("000102030405060708090a0b0c0d0e0f", "0'/1/2'/2/1000000000")
-    #test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","0/2147483647'/1/2147483646'/2")
+    #test_crypto()
+    test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
+    test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
+