Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add latest bip32 test vector #16

Merged
merged 2 commits into from
Jun 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ on:

jobs:
build:

runs-on: ubuntu-latest
strategy:
matrix:
Expand All @@ -23,12 +22,23 @@ jobs:
- name: Installation (deps and package)
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
pip install pytest
pip install -r requirements.txt -r tests/requirements.txt
python setup.py install
- name: Linter (flake8)
run: |
flake8 ./bip32/ --count --show-source --statistics --max-line-length=90
- name: Test with pytest
run: |
pytest -vvv

linter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python 3.9
uses: actions/setup-python@v2
with:
python-version: 3.9
- name: Run `black` on the source code
run: |
python -m pip install --upgrade pip
pip install black
python -m black --check bip32 tests
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## Next

- Added test vector #4 for private keys with leading zeros (see https://github.com/bitcoin/bips/pull/1030)

## 0.1

- Started to use a changelog
Expand Down
125 changes: 83 additions & 42 deletions bip32/bip32.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@
import hmac

from .utils import (
HARDENED_INDEX, _derive_hardened_private_child,
_derive_unhardened_private_child, _derive_public_child,
_serialize_extended_key, _unserialize_extended_key,
_hardened_index_in_path, _privkey_to_pubkey, _deriv_path_str_to_list
HARDENED_INDEX,
_derive_hardened_private_child,
_derive_unhardened_private_child,
_derive_public_child,
_serialize_extended_key,
_unserialize_extended_key,
_hardened_index_in_path,
_privkey_to_pubkey,
_deriv_path_str_to_list,
)


class PrivateDerivationError(ValueError):
"""
Tried to use a derivation requiring private keys, without private keys.
"""

pass


Expand All @@ -23,8 +29,16 @@ def __init__(self, message):


class BIP32:
def __init__(self, chaincode, privkey=None, pubkey=None, fingerprint=None,
depth=0, index=0, network="main"):
def __init__(
self,
chaincode,
privkey=None,
pubkey=None,
fingerprint=None,
depth=0,
index=0,
network="main",
):
"""
:param chaincode: The master chaincode, used to derive keys. As bytes.
:param privkey: The master private key for this index (default 0).
Expand Down Expand Up @@ -81,11 +95,13 @@ def get_extended_privkey_from_path(self, path):
chaincode, privkey = self.master_chaincode, self.master_privkey
for index in path:
if index & HARDENED_INDEX:
privkey, chaincode = \
_derive_hardened_private_child(privkey, chaincode, index)
privkey, chaincode = _derive_hardened_private_child(
privkey, chaincode, index
)
else:
privkey, chaincode = \
_derive_unhardened_private_child(privkey, chaincode, index)
privkey, chaincode = _derive_unhardened_private_child(
privkey, chaincode, index
)

return chaincode, privkey

Expand Down Expand Up @@ -121,18 +137,19 @@ def get_extended_pubkey_from_path(self, path):
if _hardened_index_in_path(path):
for index in path:
if index & HARDENED_INDEX:
key, chaincode = \
_derive_hardened_private_child(key, chaincode, index)
key, chaincode = _derive_hardened_private_child(
key, chaincode, index
)
else:
key, chaincode = \
_derive_unhardened_private_child(key, chaincode, index)
key, chaincode = _derive_unhardened_private_child(
key, chaincode, index
)
pubkey = _privkey_to_pubkey(key)
# We won't need private keys for the whole path, so let's only use
# public key derivation.
else:
for index in path:
pubkey, chaincode = \
_derive_public_child(pubkey, chaincode, index)
pubkey, chaincode = _derive_public_child(pubkey, chaincode, index)

return chaincode, pubkey

Expand Down Expand Up @@ -165,10 +182,14 @@ def get_xpriv_from_path(self, path):
else:
parent_pubkey = self.get_pubkey_from_path(path[:-1])
chaincode, privkey = self.get_extended_privkey_from_path(path)
extended_key = _serialize_extended_key(privkey, self.depth + len(path),
parent_pubkey,
path[-1], chaincode,
self.network)
extended_key = _serialize_extended_key(
privkey,
self.depth + len(path),
parent_pubkey,
path[-1],
chaincode,
self.network,
)

return base58.b58encode_check(extended_key).decode()

Expand All @@ -192,31 +213,41 @@ def get_xpub_from_path(self, path):
else:
parent_pubkey = self.get_pubkey_from_path(path[:-1])
chaincode, pubkey = self.get_extended_pubkey_from_path(path)
extended_key = _serialize_extended_key(pubkey, self.depth + len(path),
parent_pubkey,
path[-1], chaincode,
self.network)
extended_key = _serialize_extended_key(
pubkey,
self.depth + len(path),
parent_pubkey,
path[-1],
chaincode,
self.network,
)

return base58.b58encode_check(extended_key).decode()

def get_master_xpriv(self):
"""Get the encoded extended private key of the master private key"""
if self.master_privkey is None:
raise PrivateDerivationError
extended_key = _serialize_extended_key(self.master_privkey, self.depth,
self.parent_fingerprint,
self.index,
self.master_chaincode,
self.network)
extended_key = _serialize_extended_key(
self.master_privkey,
self.depth,
self.parent_fingerprint,
self.index,
self.master_chaincode,
self.network,
)
return base58.b58encode_check(extended_key).decode()

def get_master_xpub(self):
"""Get the encoded extended public key of the master public key"""
extended_key = _serialize_extended_key(self.master_pubkey, self.depth,
self.parent_fingerprint,
self.index,
self.master_chaincode,
self.network)
extended_key = _serialize_extended_key(
self.master_pubkey,
self.depth,
self.parent_fingerprint,
self.index,
self.master_chaincode,
self.network,
)
return base58.b58encode_check(extended_key).decode()

@classmethod
Expand All @@ -229,11 +260,16 @@ def from_xpriv(cls, xpriv):
raise InvalidInputError("'xpriv' must be a string")

extended_key = base58.b58decode_check(xpriv)
(network, depth, fingerprint,
index, chaincode, key) = _unserialize_extended_key(extended_key)
(
network,
depth,
fingerprint,
index,
chaincode,
key,
) = _unserialize_extended_key(extended_key)
# We need to remove the trailing `0` before the actual private key !!
return BIP32(chaincode, key[1:], None, fingerprint, depth, index,
network)
return BIP32(chaincode, key[1:], None, fingerprint, depth, index, network)

@classmethod
def from_xpub(cls, xpub):
Expand All @@ -245,8 +281,14 @@ def from_xpub(cls, xpub):
raise InvalidInputError("'xpub' must be a string")

extended_key = base58.b58decode_check(xpub)
(network, depth, fingerprint,
index, chaincode, key) = _unserialize_extended_key(extended_key)
(
network,
depth,
fingerprint,
index,
chaincode,
key,
) = _unserialize_extended_key(extended_key)
return BIP32(chaincode, None, key, fingerprint, depth, index, network)

@classmethod
Expand All @@ -255,6 +297,5 @@ def from_seed(cls, seed, network="main"):

:param seed: The seed as bytes.
"""
secret = hmac.new("Bitcoin seed".encode(), seed,
hashlib.sha512).digest()
secret = hmac.new("Bitcoin seed".encode(), seed, hashlib.sha512).digest()
return BIP32(secret[32:], secret[:32], network=network)
45 changes: 25 additions & 20 deletions bip32/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@ def _derive_unhardened_private_child(privkey, chaincode, index):
assert not index & HARDENED_INDEX
pubkey = _privkey_to_pubkey(privkey)
# payload is the I from the BIP. Index is 32 bits unsigned int, BE.
payload = hmac.new(chaincode, pubkey + index.to_bytes(4, "big"),
hashlib.sha512).digest()
payload = hmac.new(
chaincode, pubkey + index.to_bytes(4, "big"), hashlib.sha512
).digest()
try:
child_private = coincurve.PrivateKey(payload[:32]).add(privkey)
except ValueError:
raise BIP32DerivationError("Invalid private key at index {}, try the "
"next one!".format(index))
raise BIP32DerivationError(
"Invalid private key at index {}, try the " "next one!".format(index)
)
return child_private.secret, payload[32:]


Expand All @@ -62,13 +64,15 @@ def _derive_hardened_private_child(privkey, chaincode, index):
assert isinstance(privkey, bytes) and isinstance(chaincode, bytes)
assert index & HARDENED_INDEX
# payload is the I from the BIP. Index is 32 bits unsigned int, BE.
payload = hmac.new(chaincode, b'\x00' + privkey + index.to_bytes(4, "big"),
hashlib.sha512).digest()
payload = hmac.new(
chaincode, b"\x00" + privkey + index.to_bytes(4, "big"), hashlib.sha512
).digest()
try:
child_private = coincurve.PrivateKey(payload[:32]).add(privkey)
except ValueError:
raise BIP32DerivationError("Invalid private key at index {}, try the "
"next one!".format(index))
raise BIP32DerivationError(
"Invalid private key at index {}, try the " "next one!".format(index)
)
return child_private.secret, payload[32:]


Expand All @@ -84,19 +88,22 @@ def _derive_public_child(pubkey, chaincode, index):
assert isinstance(pubkey, bytes) and isinstance(chaincode, bytes)
assert not index & HARDENED_INDEX
# payload is the I from the BIP. Index is 32 bits unsigned int, BE.
payload = hmac.new(chaincode, pubkey + index.to_bytes(4, "big"),
hashlib.sha512).digest()
payload = hmac.new(
chaincode, pubkey + index.to_bytes(4, "big"), hashlib.sha512
).digest()
try:
tmp_pub = coincurve.PublicKey.from_secret(payload[:32])
except ValueError:
raise BIP32DerivationError("Invalid private key at index {}, try the "
"next one!".format(index))
raise BIP32DerivationError(
"Invalid private key at index {}, try the " "next one!".format(index)
)
parent_pub = coincurve.PublicKey(pubkey)
try:
child_pub = coincurve.PublicKey.combine_keys([tmp_pub, parent_pub])
except ValueError:
raise BIP32DerivationError("Invalid public key at index {}, try the "
"next one!".format(index))
raise BIP32DerivationError(
"Invalid public key at index {}, try the " "next one!".format(index)
)
return child_pub.format(), payload[32:]


Expand All @@ -106,8 +113,7 @@ def _pubkey_to_fingerprint(pubkey):
return rip.digest()[:4]


def _serialize_extended_key(key, depth, parent, index, chaincode,
network="main"):
def _serialize_extended_key(key, depth, parent, index, chaincode, network="main"):
"""Serialize an extended private *OR* public key, as spec by bip-0032.

:param key: The public or private key to serialize. Note that if this is
Expand All @@ -131,8 +137,7 @@ def _serialize_extended_key(key, depth, parent, index, chaincode,
elif len(parent) == 4:
fingerprint = parent
else:
raise ValueError("Bad parent, a fingerprint or a pubkey is"
" required")
raise ValueError("Bad parent, a fingerprint or a pubkey is" " required")
else:
fingerprint = bytes(4) # master
# A privkey or a compressed pubkey
Expand All @@ -147,7 +152,7 @@ def _serialize_extended_key(key, depth, parent, index, chaincode,
extended += index.to_bytes(4, "big")
extended += chaincode
if is_privkey:
extended += b'\x00'
extended += b"\x00"
extended += key
return extended

Expand Down Expand Up @@ -188,7 +193,7 @@ def _deriv_path_str_to_list(strpath):
"""
if not REGEX_DERIVATION_PATH.match(strpath):
raise ValueError("invalid format")
indexes = strpath.split('/')[1:]
indexes = strpath.split("/")[1:]
list_path = []
for i in indexes:
# if HARDENED
Expand Down
Loading