diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b11788d..bef700a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed + +- Validate the BIP32 seed length in `HDKey.from_seed()`, accepting 16 to 64 bytes + and raising `HDError` for other lengths. + ## [0.8.2] - 2026-08-08 ### Changed diff --git a/docs/api/bip32.md b/docs/api/bip32.md index 8293c016..31ac4dfe 100644 --- a/docs/api/bip32.md +++ b/docs/api/bip32.md @@ -64,7 +64,8 @@ Class method, converts a seed to an instance of `HDKey` (private key). **Arguments** -- `seed` - bytes sequence to use. Normally `32`-byte or `64`-byte seeds are used. +- `seed` - bytes sequence between `16` and `64` bytes (128 to 512 bits), as specified + by BIP32. Normally `32`-byte or `64`-byte seeds are used. Other lengths raise `HDError`. - `version` - version to use, by default it's `NETOWRKS['main']['xprv']` **Returns** diff --git a/src/embit/bip32.py b/src/embit/bip32.py index 6895afc4..2581c053 100644 --- a/src/embit/bip32.py +++ b/src/embit/bip32.py @@ -49,7 +49,9 @@ def __init__( @classmethod def from_seed(cls, seed: bytes, version=NETWORKS["main"]["xprv"]): - """Creates a root private key from 64-byte seed""" + """Creates a root private key from a 16- to 64-byte BIP32 seed.""" + if not 16 <= len(seed) <= 64: + raise HDError("Seed must be between 16 and 64 bytes") raw = hmac.new(b"Bitcoin seed", seed, digestmod="sha512").digest() private_key = ec.PrivateKey(raw[:32]) chain_code = raw[32:] diff --git a/tests/tests/test_bip32.py b/tests/tests/test_bip32.py index 4a74b72d..d806346d 100644 --- a/tests/tests/test_bip32.py +++ b/tests/tests/test_bip32.py @@ -197,6 +197,18 @@ class Bip32Test(TestCase): + def test_from_seed_length(self): + for length in (0, 1, 15, 65, 128): + self.assertRaises(HDError, HDKey.from_seed, bytes(length)) + + def test_from_seed_valid_lengths(self): + for length in (16, 17, 32, 63, 64): + key = HDKey.from_seed(bytes(range(length))) + self.assertTrue(key.is_private) + self.assertEqual(key.depth, 0) + self.assertEqual(key.child_number, 0) + self.assertEqual(HDKey.from_base58(key.to_base58()), key) + def test_bip32_derive(self): for seed, path, exp_xprv, exp_xpub in DERIVE_VECTORS: root_xprv = HDKey.from_seed(unhexlify(seed))