|
|
@ -26,12 +26,12 @@ |
|
|
|
|
|
|
|
import hashlib |
|
|
|
import base64 |
|
|
|
import os |
|
|
|
import re |
|
|
|
import hmac |
|
|
|
|
|
|
|
import version |
|
|
|
from util import print_error, InvalidPassword |
|
|
|
from lib.util import bfh, bh2u |
|
|
|
from . import version |
|
|
|
from .util import print_error, InvalidPassword, assert_bytes, _bytes, to_bytes |
|
|
|
|
|
|
|
import ecdsa |
|
|
|
import pyaes |
|
|
@ -98,6 +98,9 @@ except: |
|
|
|
AES = None |
|
|
|
|
|
|
|
def aes_encrypt_with_iv(key, iv, data): |
|
|
|
assert_bytes(key, iv, data) |
|
|
|
if six.PY2: |
|
|
|
key, iv, data = map(str, (key, iv, data)) |
|
|
|
if AES: |
|
|
|
padlen = 16 - (len(data) % 16) |
|
|
|
if padlen == 0: |
|
|
@ -112,6 +115,9 @@ def aes_encrypt_with_iv(key, iv, data): |
|
|
|
return e |
|
|
|
|
|
|
|
def aes_decrypt_with_iv(key, iv, data): |
|
|
|
assert_bytes(key, iv, data) |
|
|
|
if six.PY2: |
|
|
|
key, iv, data = map(str, (key, iv, data)) |
|
|
|
if AES: |
|
|
|
cipher = AES.new(key, AES.MODE_CBC, iv) |
|
|
|
data = cipher.decrypt(data) |
|
|
@ -127,14 +133,21 @@ def aes_decrypt_with_iv(key, iv, data): |
|
|
|
return s |
|
|
|
|
|
|
|
def EncodeAES(secret, s): |
|
|
|
iv = bytes(os.urandom(16)) |
|
|
|
assert_bytes(s) |
|
|
|
iv = _bytes(os.urandom(16)) |
|
|
|
# aes_cbc = pyaes.AESModeOfOperationCBC(secret, iv=iv) |
|
|
|
# aes = pyaes.Encrypter(aes_cbc) |
|
|
|
# e = iv + aes.feed(s) + aes.feed() |
|
|
|
ct = aes_encrypt_with_iv(secret, iv, s) |
|
|
|
e = iv + ct |
|
|
|
return base64.b64encode(e) |
|
|
|
|
|
|
|
def DecodeAES(secret, e): |
|
|
|
e = bytes(base64.b64decode(e)) |
|
|
|
e = _bytes(base64.b64decode(e)) |
|
|
|
iv, e = e[:16], e[16:] |
|
|
|
# aes_cbc = pyaes.AESModeOfOperationCBC(secret, iv=iv) |
|
|
|
# aes = pyaes.Decrypter(aes_cbc) |
|
|
|
# s = aes.feed(e) + aes.feed() |
|
|
|
s = aes_decrypt_with_iv(secret, iv, e) |
|
|
|
return s |
|
|
|
|
|
|
@ -158,10 +171,11 @@ def pw_decode(s, password): |
|
|
|
|
|
|
|
|
|
|
|
def rev_hex(s): |
|
|
|
return s.decode('hex')[::-1].encode('hex') |
|
|
|
return bh2u(bfh(s)[::-1]) |
|
|
|
|
|
|
|
|
|
|
|
def int_to_hex(i, length=1): |
|
|
|
assert isinstance(i, int) |
|
|
|
s = hex(i)[2:].rstrip('L') |
|
|
|
s = "0"*(2*length - len(s)) + s |
|
|
|
return rev_hex(s) |
|
|
@ -191,26 +205,30 @@ def op_push(i): |
|
|
|
|
|
|
|
|
|
|
|
def sha256(x): |
|
|
|
return hashlib.sha256(x).digest() |
|
|
|
x = to_bytes(x, 'utf8') |
|
|
|
return _bytes(hashlib.sha256(x).digest()) |
|
|
|
|
|
|
|
|
|
|
|
def Hash(x): |
|
|
|
if type(x) is unicode: x=x.encode('utf-8') |
|
|
|
return sha256(sha256(x)) |
|
|
|
x = to_bytes(x, 'utf8') |
|
|
|
out = _bytes(sha256(sha256(x))) |
|
|
|
return out |
|
|
|
|
|
|
|
|
|
|
|
hash_encode = lambda x: bh2u(x[::-1]) |
|
|
|
hash_decode = lambda x: bfh(x)[::-1] |
|
|
|
hmac_sha_512 = lambda x, y: _bytes(hmac.new(x, y, hashlib.sha512).digest()) |
|
|
|
|
|
|
|
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 is_new_seed(x, prefix=version.SEED_PREFIX): |
|
|
|
import mnemonic |
|
|
|
from . import mnemonic |
|
|
|
x = mnemonic.normalize_text(x) |
|
|
|
s = hmac_sha_512("Seed version", x.encode('utf8')).encode('hex') |
|
|
|
s = bh2u(hmac_sha_512(b"Seed version", x.encode('utf8'))) |
|
|
|
return s.startswith(prefix) |
|
|
|
|
|
|
|
|
|
|
|
def is_old_seed(seed): |
|
|
|
import old_mnemonic |
|
|
|
from . import old_mnemonic |
|
|
|
words = seed.strip().split() |
|
|
|
try: |
|
|
|
old_mnemonic.mn_decode(words) |
|
|
@ -218,8 +236,8 @@ def is_old_seed(seed): |
|
|
|
except Exception: |
|
|
|
uses_electrum_words = False |
|
|
|
try: |
|
|
|
seed.decode('hex') |
|
|
|
is_hex = (len(seed) == 32 or len(seed) == 64) |
|
|
|
seed = bfh(seed) |
|
|
|
is_hex = (len(seed) == 16 or len(seed) == 32) |
|
|
|
except Exception: |
|
|
|
is_hex = False |
|
|
|
return is_hex or (uses_electrum_words and (len(words) == 12 or len(words) == 24)) |
|
|
@ -255,37 +273,38 @@ def i2o_ECPublicKey(pubkey, compressed=False): |
|
|
|
'%064x' % pubkey.point.x() + \ |
|
|
|
'%064x' % pubkey.point.y() |
|
|
|
|
|
|
|
return key.decode('hex') |
|
|
|
|
|
|
|
return bfh(key) |
|
|
|
# end pywallet openssl private key implementation |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
############ functions from pywallet ##################### |
|
|
|
|
|
|
|
def hash_160(public_key): |
|
|
|
if 'ANDROID_DATA' in os.environ: |
|
|
|
from Crypto.Hash import RIPEMD |
|
|
|
md = RIPEMD.new() |
|
|
|
else: |
|
|
|
md = hashlib.new('ripemd') |
|
|
|
public_key = to_bytes(public_key, 'ascii') |
|
|
|
md.update(sha256(public_key)) |
|
|
|
return md.digest() |
|
|
|
|
|
|
|
def hash_160_to_bc_address(h160, addrtype, witness_program_version=1): |
|
|
|
s = chr(addrtype) |
|
|
|
s = bytes([addrtype]) |
|
|
|
if addrtype == ADDRTYPE_P2WPKH: |
|
|
|
s += chr(witness_program_version) + chr(0) |
|
|
|
s += bytes([witness_program_version]) + b'\x00' |
|
|
|
s += h160 |
|
|
|
return base_encode(s+Hash(s)[0:4], base=58) |
|
|
|
|
|
|
|
|
|
|
|
def bc_address_to_hash_160(addr): |
|
|
|
bytes = base_decode(addr, 25, base=58) |
|
|
|
return ord(bytes[0]), bytes[1:21] |
|
|
|
addr = to_bytes(addr, 'ascii') |
|
|
|
_bytes = base_decode(addr, 25, base=58) |
|
|
|
return _bytes[0], _bytes[1:21] |
|
|
|
|
|
|
|
def hash160_to_p2pkh(h160): |
|
|
|
return hash_160_to_bc_address(h160, ADDRTYPE_P2PKH) |
|
|
|
|
|
|
|
|
|
|
|
def hash160_to_p2sh(h160): |
|
|
|
return hash_160_to_bc_address(h160, ADDRTYPE_P2SH) |
|
|
|
|
|
|
@ -298,60 +317,70 @@ def public_key_to_p2wpkh(public_key): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
|
|
|
__b58chars = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
|
|
|
assert len(__b58chars) == 58 |
|
|
|
|
|
|
|
__b43chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$*+-./:' |
|
|
|
__b43chars = b'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$*+-./:' |
|
|
|
assert len(__b43chars) == 43 |
|
|
|
|
|
|
|
|
|
|
|
def base_encode(v, base): |
|
|
|
""" encode v, which is a string of bytes, to base58.""" |
|
|
|
if base == 58: |
|
|
|
assert_bytes(v) |
|
|
|
assert base in (58, 43) |
|
|
|
chars = __b58chars |
|
|
|
elif base == 43: |
|
|
|
if base == 43: |
|
|
|
chars = __b43chars |
|
|
|
long_value = 0L |
|
|
|
long_value = 0 |
|
|
|
for (i, c) in enumerate(v[::-1]): |
|
|
|
long_value += (256**i) * ord(c) |
|
|
|
result = '' |
|
|
|
long_value += (256**i) * c |
|
|
|
result = bytearray() |
|
|
|
while long_value >= base: |
|
|
|
div, mod = divmod(long_value, base) |
|
|
|
result = chars[mod] + result |
|
|
|
result.append(chars[mod]) |
|
|
|
long_value = div |
|
|
|
result = chars[long_value] + result |
|
|
|
result.append(chars[long_value]) |
|
|
|
# Bitcoin does a little leading-zero-compression: |
|
|
|
# leading 0-bytes in the input become leading-1s |
|
|
|
nPad = 0 |
|
|
|
for c in v: |
|
|
|
if c == '\0': nPad += 1 |
|
|
|
else: break |
|
|
|
return (chars[0]*nPad) + result |
|
|
|
if c == 0x00: |
|
|
|
nPad += 1 |
|
|
|
else: |
|
|
|
break |
|
|
|
result.extend([chars[0]] * nPad) |
|
|
|
result.reverse() |
|
|
|
return result.decode('ascii') |
|
|
|
|
|
|
|
|
|
|
|
def base_decode(v, length, base): |
|
|
|
""" decode v into a string of len bytes.""" |
|
|
|
if base == 58: |
|
|
|
# assert_bytes(v) |
|
|
|
v = to_bytes(v, 'ascii') |
|
|
|
assert base in (58, 43) |
|
|
|
chars = __b58chars |
|
|
|
elif base == 43: |
|
|
|
if base == 43: |
|
|
|
chars = __b43chars |
|
|
|
long_value = 0L |
|
|
|
long_value = 0 |
|
|
|
for (i, c) in enumerate(v[::-1]): |
|
|
|
long_value += chars.find(c) * (base**i) |
|
|
|
result = '' |
|
|
|
long_value += chars.find(_bytes([c])) * (base**i) |
|
|
|
result = bytearray() |
|
|
|
while long_value >= 256: |
|
|
|
div, mod = divmod(long_value, 256) |
|
|
|
result = chr(mod) + result |
|
|
|
result.append(mod) |
|
|
|
long_value = div |
|
|
|
result = chr(long_value) + result |
|
|
|
result.append(long_value) |
|
|
|
nPad = 0 |
|
|
|
for c in v: |
|
|
|
if c == chars[0]: nPad += 1 |
|
|
|
else: break |
|
|
|
result = chr(0)*nPad + result |
|
|
|
if c == chars[0]: |
|
|
|
nPad += 1 |
|
|
|
else: |
|
|
|
break |
|
|
|
result.extend(b'\x00' * nPad) |
|
|
|
if length is not None and len(result) != length: |
|
|
|
return None |
|
|
|
return result |
|
|
|
result.reverse() |
|
|
|
return bytes(result) |
|
|
|
|
|
|
|
|
|
|
|
def EncodeBase58Check(vchIn): |
|
|
@ -377,14 +406,15 @@ def PrivKeyToSecret(privkey): |
|
|
|
|
|
|
|
def SecretToASecret(secret, compressed=False): |
|
|
|
addrtype = ADDRTYPE_P2PKH |
|
|
|
vchIn = chr((addrtype+128)&255) + secret |
|
|
|
if compressed: vchIn += '\01' |
|
|
|
vchIn = bytes([(addrtype+128)&255]) + secret |
|
|
|
if compressed: vchIn += b'\01' |
|
|
|
return EncodeBase58Check(vchIn) |
|
|
|
|
|
|
|
|
|
|
|
def ASecretToSecret(key): |
|
|
|
addrtype = ADDRTYPE_P2PKH |
|
|
|
vch = DecodeBase58Check(key) |
|
|
|
if vch and vch[0] == chr((addrtype+128)&255): |
|
|
|
if vch and vch[0] == ((addrtype+128)&255): |
|
|
|
return vch[1:] |
|
|
|
elif is_minikey(key): |
|
|
|
return minikey_to_private_key(key) |
|
|
@ -404,7 +434,7 @@ def GetPubKey(pubkey, compressed=False): |
|
|
|
|
|
|
|
|
|
|
|
def GetSecret(pkey): |
|
|
|
return ('%064x' % pkey.secret).decode('hex') |
|
|
|
return bfh('%064x' % pkey.secret) |
|
|
|
|
|
|
|
|
|
|
|
def is_compressed(sec): |
|
|
@ -418,12 +448,12 @@ def public_key_from_private_key(sec): |
|
|
|
assert pkey |
|
|
|
compressed = is_compressed(sec) |
|
|
|
public_key = GetPubKey(pkey.pubkey, compressed) |
|
|
|
return public_key.encode('hex') |
|
|
|
return bh2u(public_key) |
|
|
|
|
|
|
|
|
|
|
|
def address_from_private_key(sec): |
|
|
|
public_key = public_key_from_private_key(sec) |
|
|
|
address = public_key_to_p2pkh(public_key.decode('hex')) |
|
|
|
address = public_key_to_p2pkh(bfh(public_key)) |
|
|
|
return address |
|
|
|
|
|
|
|
|
|
|
@ -434,7 +464,7 @@ def is_valid(addr): |
|
|
|
def is_address(addr): |
|
|
|
try: |
|
|
|
addrtype, h = bc_address_to_hash_160(addr) |
|
|
|
except Exception: |
|
|
|
except Exception as e: |
|
|
|
return False |
|
|
|
if addrtype not in [ADDRTYPE_P2PKH, ADDRTYPE_P2SH]: |
|
|
|
return False |
|
|
@ -478,10 +508,14 @@ from ecdsa.curves import SECP256k1 |
|
|
|
from ecdsa.ellipticcurve import Point |
|
|
|
from ecdsa.util import string_to_number, number_to_string |
|
|
|
|
|
|
|
|
|
|
|
def msg_magic(message): |
|
|
|
varint = var_int(len(message)) |
|
|
|
encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)]) |
|
|
|
return "\x18Bitcoin Signed Message:\n" + encoded_varint + message |
|
|
|
if six.PY3: |
|
|
|
encoded_varint = varint.encode('ascii') |
|
|
|
else: |
|
|
|
encoded_varint = b"".join([chr(int(varint[i:i+2], 16)) for i in range(0, len(varint), 2)]) |
|
|
|
return b"\x18Bitcoin Signed Message:\n" + encoded_varint + message |
|
|
|
|
|
|
|
|
|
|
|
def verify_message(address, sig, message): |
|
|
@ -502,11 +536,11 @@ def verify_message(address, sig, message): |
|
|
|
|
|
|
|
|
|
|
|
def encrypt_message(message, pubkey): |
|
|
|
return EC_KEY.encrypt_message(message, pubkey.decode('hex')) |
|
|
|
return EC_KEY.encrypt_message(message, bfh(pubkey)) |
|
|
|
|
|
|
|
|
|
|
|
def chunks(l, n): |
|
|
|
return [l[i:i+n] for i in xrange(0, len(l), n)] |
|
|
|
return [l[i:i+n] for i in range(0, len(l), n)] |
|
|
|
|
|
|
|
|
|
|
|
def ECC_YfromX(x,curved=curve_secp256k1, odd=True): |
|
|
@ -516,7 +550,7 @@ def ECC_YfromX(x,curved=curve_secp256k1, odd=True): |
|
|
|
for offset in range(128): |
|
|
|
Mx = x + offset |
|
|
|
My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p |
|
|
|
My = pow(My2, (_p+1)/4, _p ) |
|
|
|
My = pow(My2, (_p+1)//4, _p ) |
|
|
|
|
|
|
|
if curved.contains_point(Mx,My): |
|
|
|
if odd == bool(My&1): |
|
|
@ -531,20 +565,19 @@ def negative_point(P): |
|
|
|
|
|
|
|
def point_to_ser(P, comp=True ): |
|
|
|
if comp: |
|
|
|
return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex') |
|
|
|
return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex') |
|
|
|
return bfh( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ) |
|
|
|
return bfh( '04'+('%064x'%P.x())+('%064x'%P.y()) ) |
|
|
|
|
|
|
|
|
|
|
|
def ser_to_point(Aser): |
|
|
|
curve = curve_secp256k1 |
|
|
|
generator = generator_secp256k1 |
|
|
|
_r = generator.order() |
|
|
|
assert Aser[0] in ['\x02','\x03','\x04'] |
|
|
|
if Aser[0] == '\x04': |
|
|
|
assert Aser[0] in [0x02, 0x03, 0x04] |
|
|
|
if Aser[0] == 0x04: |
|
|
|
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 ) |
|
|
|
|
|
|
|
return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0] == 0x03)[0], _r ) |
|
|
|
|
|
|
|
|
|
|
|
class MyVerifyingKey(ecdsa.VerifyingKey): |
|
|
@ -552,14 +585,14 @@ class MyVerifyingKey(ecdsa.VerifyingKey): |
|
|
|
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 |
|
|
|
from . 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 |
|
|
|
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()) |
|
|
@ -578,7 +611,7 @@ class MyVerifyingKey(ecdsa.VerifyingKey): |
|
|
|
def pubkey_from_signature(sig, h): |
|
|
|
if len(sig) != 65: |
|
|
|
raise Exception("Wrong encoding") |
|
|
|
nV = ord(sig[0]) |
|
|
|
nV = sig[0] |
|
|
|
if nV < 27 or nV >= 35: |
|
|
|
raise Exception("Bad encoding") |
|
|
|
if nV >= 31: |
|
|
@ -598,7 +631,7 @@ class MySigningKey(ecdsa.SigningKey): |
|
|
|
G = curve.generator |
|
|
|
order = G.order() |
|
|
|
r, s = ecdsa.SigningKey.sign_number(self, number, entropy, k) |
|
|
|
if s > order/2: |
|
|
|
if s > order//2: |
|
|
|
s = order - s |
|
|
|
return r, s |
|
|
|
|
|
|
@ -612,7 +645,7 @@ class EC_KEY(object): |
|
|
|
self.secret = secret |
|
|
|
|
|
|
|
def get_public_key(self, compressed=True): |
|
|
|
return point_to_ser(self.pubkey.point, compressed).encode('hex') |
|
|
|
return bh2u(point_to_ser(self.pubkey.point, compressed)) |
|
|
|
|
|
|
|
def sign(self, msg_hash): |
|
|
|
private_key = MySigningKey.from_secret_exponent(self.secret, curve = SECP256k1) |
|
|
@ -622,19 +655,20 @@ class EC_KEY(object): |
|
|
|
return signature |
|
|
|
|
|
|
|
def sign_message(self, message, is_compressed): |
|
|
|
message = to_bytes(message, 'utf8') |
|
|
|
signature = self.sign(Hash(msg_magic(message))) |
|
|
|
for i in range(4): |
|
|
|
sig = chr(27 + i + (4 if is_compressed else 0)) + signature |
|
|
|
sig = bytes([27 + i + (4 if is_compressed else 0)]) + signature |
|
|
|
try: |
|
|
|
self.verify_message(sig, message) |
|
|
|
return sig |
|
|
|
except Exception: |
|
|
|
except Exception as e: |
|
|
|
continue |
|
|
|
else: |
|
|
|
raise Exception("error: cannot sign message") |
|
|
|
|
|
|
|
|
|
|
|
def verify_message(self, sig, message): |
|
|
|
assert_bytes(message) |
|
|
|
h = Hash(msg_magic(message)) |
|
|
|
public_key, compressed = pubkey_from_signature(sig, h) |
|
|
|
# check public key |
|
|
@ -648,6 +682,7 @@ class EC_KEY(object): |
|
|
|
|
|
|
|
@classmethod |
|
|
|
def encrypt_message(self, message, pubkey): |
|
|
|
assert_bytes(message) |
|
|
|
|
|
|
|
pk = ser_to_point(pubkey) |
|
|
|
if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()): |
|
|
@ -659,13 +694,12 @@ class EC_KEY(object): |
|
|
|
key = hashlib.sha512(ecdh_key).digest() |
|
|
|
iv, key_e, key_m = key[0:16], key[16:32], key[32:] |
|
|
|
ciphertext = aes_encrypt_with_iv(key_e, iv, message) |
|
|
|
ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex') |
|
|
|
encrypted = 'BIE1' + ephemeral_pubkey + ciphertext |
|
|
|
ephemeral_pubkey = bfh(ephemeral.get_public_key(compressed=True)) |
|
|
|
encrypted = b'BIE1' + ephemeral_pubkey + 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) < 85: |
|
|
@ -674,11 +708,11 @@ class EC_KEY(object): |
|
|
|
ephemeral_pubkey = encrypted[4:37] |
|
|
|
ciphertext = encrypted[37:-32] |
|
|
|
mac = encrypted[-32:] |
|
|
|
if magic != 'BIE1': |
|
|
|
if magic != b'BIE1': |
|
|
|
raise Exception('invalid ciphertext: invalid magic bytes') |
|
|
|
try: |
|
|
|
ephemeral_pubkey = ser_to_point(ephemeral_pubkey) |
|
|
|
except AssertionError, e: |
|
|
|
except AssertionError as e: |
|
|
|
raise Exception('invalid ciphertext: invalid ephemeral pubkey') |
|
|
|
if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()): |
|
|
|
raise Exception('invalid ciphertext: invalid ephemeral pubkey') |
|
|
@ -715,13 +749,14 @@ def get_pubkeys_from_secret(secret): |
|
|
|
# public key can be determined without the master private key. |
|
|
|
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) |
|
|
|
return _CKD_priv(k, c, bfh(rev_hex(int_to_hex(n,4))), is_prime) |
|
|
|
|
|
|
|
|
|
|
|
def _CKD_priv(k, c, s, is_prime): |
|
|
|
order = generator_secp256k1.order() |
|
|
|
keypair = EC_KEY(k) |
|
|
|
cK = GetPubKey(keypair.pubkey,True) |
|
|
|
data = chr(0) + k + s if is_prime else cK + s |
|
|
|
data = bytes([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:] |
|
|
@ -735,7 +770,7 @@ def _CKD_priv(k, c, s, is_prime): |
|
|
|
# non-negative. If n is negative, we need the master private key to find it. |
|
|
|
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')) |
|
|
|
return _CKD_pub(cK, c, bfh(rev_hex(int_to_hex(n,4)))) |
|
|
|
|
|
|
|
# helper function, callable with arbitrary string |
|
|
|
def _CKD_pub(cK, c, s): |
|
|
@ -750,41 +785,48 @@ def _CKD_pub(cK, c, s): |
|
|
|
|
|
|
|
|
|
|
|
def xprv_header(xtype): |
|
|
|
return ("%08x"%(XPRV_HEADER + xtype)).decode('hex') |
|
|
|
return bfh("%08x" % (XPRV_HEADER + xtype)) |
|
|
|
|
|
|
|
|
|
|
|
def xpub_header(xtype): |
|
|
|
return ("%08x"%(XPUB_HEADER + xtype)).decode('hex') |
|
|
|
return bfh("%08x" % (XPUB_HEADER + xtype)) |
|
|
|
|
|
|
|
|
|
|
|
def serialize_xprv(xtype, c, k, depth=0, fingerprint=chr(0)*4, child_number=chr(0)*4): |
|
|
|
xprv = xprv_header(xtype) + chr(depth) + fingerprint + child_number + c + chr(0) + k |
|
|
|
def serialize_xprv(xtype, c, k, depth=0, fingerprint=b'\x00'*4, child_number=b'\x00'*4): |
|
|
|
xprv = xprv_header(xtype) + bytes([depth]) + fingerprint + child_number + c + bytes([0]) + k |
|
|
|
return EncodeBase58Check(xprv) |
|
|
|
|
|
|
|
def serialize_xpub(xtype, c, cK, depth=0, fingerprint=chr(0)*4, child_number=chr(0)*4): |
|
|
|
xpub = xpub_header(xtype) + chr(depth) + fingerprint + child_number + c + cK |
|
|
|
|
|
|
|
def serialize_xpub(xtype, c, cK, depth=0, fingerprint=b'\x00'*4, child_number=b'\x00'*4): |
|
|
|
xpub = xpub_header(xtype) + bytes([depth]) + fingerprint + child_number + c + cK |
|
|
|
return EncodeBase58Check(xpub) |
|
|
|
|
|
|
|
|
|
|
|
def deserialize_xkey(xkey, prv): |
|
|
|
xkey = DecodeBase58Check(xkey) |
|
|
|
if len(xkey) != 78: |
|
|
|
raise BaseException('Invalid length') |
|
|
|
depth = ord(xkey[4]) |
|
|
|
depth = xkey[4] |
|
|
|
fingerprint = xkey[5:9] |
|
|
|
child_number = xkey[9:13] |
|
|
|
c = xkey[13:13+32] |
|
|
|
header = XPRV_HEADER if prv else XPUB_HEADER |
|
|
|
xtype = int('0x' + xkey[0:4].encode('hex'), 16) - header |
|
|
|
xtype = int('0x' + bh2u(xkey[0:4]), 16) - header |
|
|
|
if xtype not in ([0, 1] if TESTNET else [0]): |
|
|
|
raise BaseException('Invalid header') |
|
|
|
n = 33 if prv else 32 |
|
|
|
K_or_k = xkey[13+n:] |
|
|
|
return xtype, depth, fingerprint, child_number, c, K_or_k |
|
|
|
|
|
|
|
|
|
|
|
def deserialize_xpub(xkey): |
|
|
|
return deserialize_xkey(xkey, False) |
|
|
|
|
|
|
|
|
|
|
|
def deserialize_xprv(xkey): |
|
|
|
return deserialize_xkey(xkey, True) |
|
|
|
|
|
|
|
|
|
|
|
def is_xpub(text): |
|
|
|
try: |
|
|
|
deserialize_xpub(text) |
|
|
@ -792,6 +834,7 @@ def is_xpub(text): |
|
|
|
except: |
|
|
|
return False |
|
|
|
|
|
|
|
|
|
|
|
def is_xprv(text): |
|
|
|
try: |
|
|
|
deserialize_xprv(text) |
|
|
@ -807,7 +850,7 @@ def xpub_from_xprv(xprv): |
|
|
|
|
|
|
|
|
|
|
|
def bip32_root(seed, xtype): |
|
|
|
I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest() |
|
|
|
I = hmac.new(b"Bitcoin seed", seed, hashlib.sha512).digest() |
|
|
|
master_k = I[0:32] |
|
|
|
master_c = I[32:] |
|
|
|
K, cK = get_pubkeys_from_secret(master_k) |
|
|
@ -815,9 +858,10 @@ def bip32_root(seed, xtype): |
|
|
|
xpub = serialize_xpub(xtype, master_c, cK) |
|
|
|
return xprv, xpub |
|
|
|
|
|
|
|
|
|
|
|
def xpub_from_pubkey(xtype, cK): |
|
|
|
assert cK[0] in ['\x02','\x03'] |
|
|
|
return serialize_xpub(xtype, chr(0)*32, cK) |
|
|
|
assert cK[0] in [0x02, 0x03] |
|
|
|
return serialize_xpub(xtype, b'\x00'*32, cK) |
|
|
|
|
|
|
|
|
|
|
|
def bip32_derivation(s): |
|
|
@ -849,7 +893,7 @@ def bip32_private_derivation(xprv, branch, sequence): |
|
|
|
depth += 1 |
|
|
|
_, parent_cK = get_pubkeys_from_secret(parent_k) |
|
|
|
fingerprint = hash_160(parent_cK)[0:4] |
|
|
|
child_number = ("%08X"%i).decode('hex') |
|
|
|
child_number = bfh("%08X"%i) |
|
|
|
K, cK = get_pubkeys_from_secret(k) |
|
|
|
xpub = serialize_xpub(xtype, c, cK, depth, fingerprint, child_number) |
|
|
|
xprv = serialize_xprv(xtype, c, k, depth, fingerprint, child_number) |
|
|
@ -867,7 +911,7 @@ def bip32_public_derivation(xpub, branch, sequence): |
|
|
|
cK, c = CKD_pub(cK, c, i) |
|
|
|
depth += 1 |
|
|
|
fingerprint = hash_160(parent_cK)[0:4] |
|
|
|
child_number = ("%08X"%i).decode('hex') |
|
|
|
child_number = bfh("%08X"%i) |
|
|
|
return serialize_xpub(xtype, c, cK, depth, fingerprint, child_number) |
|
|
|
|
|
|
|
|
|
|
@ -878,7 +922,7 @@ def bip32_private_key(sequence, k, chain): |
|
|
|
|
|
|
|
|
|
|
|
def xkeys_from_seed(seed, passphrase, derivation): |
|
|
|
from mnemonic import Mnemonic |
|
|
|
from .mnemonic import Mnemonic |
|
|
|
xprv, xpub = bip32_root(Mnemonic.mnemonic_to_seed(seed, passphrase), 0) |
|
|
|
xprv, xpub = bip32_private_derivation(xprv, "m/", derivation) |
|
|
|
return xprv, xpub |
|
|
|