Skip to content

Commit 67dc0de

Browse files
explicit check for negative bip32 indices (buidl-bitcoin#151)
1 parent db434c3 commit 67dc0de

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

buidl/hd.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ def child(self, index):
158158
"""Returns the child HDPrivateKey at a particular index.
159159
Hardened children return for indices >= 0x8000000.
160160
"""
161-
# if index >= 0x80000000
161+
if index < 0:
162+
raise ValueError("index should always be positive")
162163
if index >= 0x80000000:
163164
# the message data is the private key secret in 33 bytes in
164165
# big-endian and the index in 4 bytes big-endian.
@@ -589,11 +590,13 @@ def fingerprint(self):
589590

590591
def child(self, index):
591592
"""Returns the child HDPublicKey at a particular index.
592-
Raises ValueError for indices >= 0x8000000.
593+
Raises ValueError for indices >= 0x8000000 and indices < 0.
593594
"""
594-
# if index >= 0x80000000, raise a ValueError
595595
if index >= 0x80000000:
596596
raise ValueError("child number should always be less than 2^31")
597+
if index < 0:
598+
raise ValueError("child number should always be positive")
599+
597600
# data is the SEC compressed and the index in 4 bytes big-endian
598601
data = self.point.sec() + int_to_big_endian(index, 4)
599602
# get hmac_sha512 with chain code, data

buidl/test/test_hd.py

+4
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,12 @@ def test_child(self):
5454
self.assertEqual(addr, want1)
5555
addr = priv.child(0x80000002).p2wpkh_address()
5656
self.assertEqual(addr, want2)
57+
with self.assertRaises(ValueError):
58+
priv.child(-1)
5759
with self.assertRaises(ValueError):
5860
pub.child(0x80000002)
61+
with self.assertRaises(ValueError):
62+
pub.child(-1)
5963

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

0 commit comments

Comments
 (0)