Skip to content

Commit

Permalink
explicit check for negative bip32 indices (#151)
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerchambers authored Aug 11, 2023
1 parent db434c3 commit 67dc0de
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 6 additions & 3 deletions buidl/hd.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ def child(self, index):
"""Returns the child HDPrivateKey at a particular index.
Hardened children return for indices >= 0x8000000.
"""
# if index >= 0x80000000
if index < 0:
raise ValueError("index should always be positive")
if index >= 0x80000000:
# the message data is the private key secret in 33 bytes in
# big-endian and the index in 4 bytes big-endian.
Expand Down Expand Up @@ -589,11 +590,13 @@ def fingerprint(self):

def child(self, index):
"""Returns the child HDPublicKey at a particular index.
Raises ValueError for indices >= 0x8000000.
Raises ValueError for indices >= 0x8000000 and indices < 0.
"""
# if index >= 0x80000000, raise a ValueError
if index >= 0x80000000:
raise ValueError("child number should always be less than 2^31")
if index < 0:
raise ValueError("child number should always be positive")

# data is the SEC compressed and the index in 4 bytes big-endian
data = self.point.sec() + int_to_big_endian(index, 4)
# get hmac_sha512 with chain code, data
Expand Down
4 changes: 4 additions & 0 deletions buidl/test/test_hd.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,12 @@ def test_child(self):
self.assertEqual(addr, want1)
addr = priv.child(0x80000002).p2wpkh_address()
self.assertEqual(addr, want2)
with self.assertRaises(ValueError):
priv.child(-1)
with self.assertRaises(ValueError):
pub.child(0x80000002)
with self.assertRaises(ValueError):
pub.child(-1)

def test_traverse(self):
seed = b"[email protected] Jimmy Song"
Expand Down

0 comments on commit 67dc0de

Please sign in to comment.