How an HD Wallet Works: BIP-39, BIP-32 and BIP-44 in TypeScript, Tested Against Official Vectors
Every non-custodial wallet you have used, from a browser extension to a hardware device, hides the same pipeline behind its “write down these 12 words” screen. An HD wallet (hierarchical deterministic wallet) turns a few
Every non-custodial wallet you have used, from a browser extension to a hardware device, hides the same pipeline behind its “write down these 12 words” screen. An HD wallet (hierarchical deterministic wallet) turns a few bytes of randomness into a mnemonic, the mnemonic into a seed, the seed into a tree of keys, and the leaves of that tree into addresses. If you build a wallet, a custody back office, or even a test harness for a dApp, you will eventually debug one of those steps. Keys that are lost or exposed mean funds that are gone for good, so “it seems to work” is not a standard you want here.
This post rebuilds the pipeline in TypeScript, step by step, and checks every step against official test vectors instead of trusting screenshots:
- Entropy to a BIP39 mnemonic (checksum and the 2048-word list), written by hand and compared with the library.
- Mnemonic to a 512-bit seed with PBKDF2, including the BIP39 passphrase.
- Seed to a BIP-32 master key, then BIP-44 paths like
m/44'/60'/0'/0/i. - Public keys to Ethereum addresses with EIP-55 checksums.
- Hardened vs non-hardened derivation, and a working demo of why a leaked
xpubplus one child private key exposes the whole branch. - Gotchas: NFKD normalization, “wrong” passphrases that silently open another wallet, and a seed function that does not validate the checksum.
Stack: Node.js 22, TypeScript 5.9.3, @scure/bip39 2.4.0, @scure/bip32 2.4.0, @noble/hashes 2.4.0, @noble/curves 2.4.0, tsx 4.23.15, vitest 5.0.5. All output below is copied from real runs.
Safety note. Every mnemonic in this article is a public test value: the BIP-39 vectors and Hardhat’s default development mnemonic. Anything sent to their addresses on a real network can be taken by anyone. Never paste a real seed phrase into example code, a REPL, a test file, or a website. Nothing here is financial advice.
The pipeline at a glance
![HD wallet pipeline: entropy and checksum to 12 words, PBKDF2 to a 64-byte seed, HMAC-SHA512 to the master key, BIP-44 path to a child key, Keccak-256 and EIP-55 to the address]

HD wallet pipeline: entropy and checksum to 12 words, PBKDF2 to a 64-byte seed, HMAC-SHA512 to the master key, BIP-44 path to a child key, Keccak-256 and EIP-55 to the address
| Layer | Standard | Input | Output |
|---|---|---|---|
| Mnemonic | BIP-39 | 128-256 bits of entropy | 12-24 words from a 2048-word list |
| Seed | BIP-39 | words + optional passphrase | 64-byte seed (PBKDF2-HMAC-SHA512, 2048 iterations) |
| Key tree | BIP-32 | seed | master private key + chain code, then child keys |
| Path layout | BIP-44 + SLIP-44 | tree | m / purpose' / coin_type' / account' / change / address_index |
| Address | Ethereum + EIP-55 | secp256k1 public key | last 20 bytes of Keccak-256, mixed-case checksum |
The layers are independent: BIP-39 knows nothing about Ethereum, BIP-32 knows nothing about words. That is what makes the pipeline testable piece by piece.
Project setup:
mkdir hd-wallet && cd hd-wallet && npm init -y
npm i -E @scure/[email protected] @scure/[email protected] @noble/[email protected] @noble/[email protected]
npm i -E -D [email protected] [email protected] [email protected] @types/[email protected]
Set "type": "module" in package.json. The @scure and @noble packages are small, dependency-light libraries; their READMEs list a cure53 audit of the 1.x versions in January 2022 (funded by the Ethereum Foundation) and a self-audit of version 2.2.0 in April 2026.
Step 1. Entropy to a BIP39 mnemonic
BIP-39 allows 128 to 256 bits of entropy. The checksum is the first ENT / 32 bits of SHA-256(entropy). Append it, split everything into 11-bit groups, and use each group (0 to 2047) as an index into the BIP39 wordlist. With 128 bits you get a 4-bit checksum, 132 bits in total, and 12 words. With 256 bits you get 8 checksum bits and 24 words.
Here is the whole algorithm, without the library:
// BIP-39 step 1: entropy -> checksum -> 11-bit indexes -> words (by hand)
import { sha256 } from '@noble/hashes/sha2.js';
const toBits = (bytes: Uint8Array) =>
[...bytes].map((b) => b.toString(2).padStart(8, '0')).join('');
export function entropyToMnemonicByHand(entropy: Uint8Array, wordlist: string[]) {
if (![16, 20, 24, 28, 32].includes(entropy.length)) {
throw new RangeError('BIP-39 entropy must be 128-256 bits in 32-bit steps');
}
if (wordlist.length !== 2048) throw new Error('wordlist must have 2048 words');
const ENT = entropy.length * 8;
const CS = ENT / 32; // checksum length in bits
const checksum = toBits(sha256(entropy)).slice(0, CS);
const bits = toBits(entropy) + checksum; // ENT + CS is always a multiple of 11
const indexes = bits.match(/.{11}/g)!.map((chunk) => parseInt(chunk, 2));
return { ENT, CS, checksum, indexes, words: indexes.map((i) => wordlist[i]) };
}
And a demo that compares it with @scure/bip39 on a public test vector:
import { entropyToMnemonic, validateMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english.js';
import { hexToBytes } from '@noble/hashes/utils.js';
import { entropyToMnemonicByHand } from '../src/mnemonic.js';
// Public BIP-39 test vector entropy. Never use test vectors for real funds.
const entropy = hexToBytes('7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f');
const r = entropyToMnemonicByHand(entropy, wordlist);
console.log(`ENT=${r.ENT} bits, CS=${r.CS} bits, checksum bits=${r.checksum}`);
console.log('indexes:', r.indexes.join(' '));
console.log('by hand :', r.words.join(' '));
console.log('library :', entropyToMnemonic(entropy, wordlist));
// The last word carries the checksum: change it and validation fails
const words = r.words.slice();
words[11] = 'zoo';
console.log('last word -> zoo, valid?', validateMnemonic(words.join(' '), wordlist));
// How many of the 2048 words are a valid 12th word after 11 x "abandon"?
const prefix = Array(11).fill('abandon').join(' ');
const valid = wordlist.filter((w) => validateMnemonic(`${prefix} ${w}`, wordlist));
console.log(`valid 12th words: ${valid.length} of ${wordlist.length}; first five: ${valid.slice(0, 5).join(', ')}`);
ENT=128 bits, CS=4 bits, checksum bits=1000
indexes: 1019 2015 1790 2039 1983 1533 2031 1919 1019 2015 1790 2040
by hand : legal winner thank year wave sausage worth useful legal winner thank yellow
library : legal winner thank year wave sausage worth useful legal winner thank yellow
last word -> zoo, valid? false
valid 12th words: 128 of 2048; first five: about, actual, age, alpha, angle
![Bit layout of a 12-word mnemonic: twelve 11-bit indexes, the last one mixing 7 entropy bits with the 4-bit checksum]

Bit layout of a 12-word mnemonic: twelve 11-bit indexes, the last one mixing 7 entropy bits with the 4-bit checksum
Three things are worth noticing in that output.
The checksum lives inside the last word. The 12th word holds 7 bits of entropy and 4 bits of checksum. Replace it with zoo and validation fails. That is why a wallet can tell you “invalid phrase” on a typo but cannot tell you which word is wrong.
Only 1 in 16 last words is valid. For eleven abandons, 128 of the 2048 candidates pass. So a random wrong word slips past the 4-bit checksum about once in 16 tries: it is a typo detector, not a security feature. It also shows why user-chosen words are a bad idea: given eleven words, enumerating the valid twelfth ones takes milliseconds.
The wordlist is designed for humans. BIP-39 asks that the first four letters identify a word unambiguously and that similar words such as “build” and “built” be avoided. The English list passes the four-letter check (there is a test for it below), so an input field can autocomplete a word after four letters. BIP-39 also defines lists in other languages, but the scure README points out that non-English wordlists are officially discouraged by BIP-39. If you support them anyway, you need to know which list a phrase came from, because the phrase alone does not say.
In real code, the mnemonic comes from a CSPRNG: generateMnemonic(wordlist, 128) in @scure/bip39. Never derive entropy from Math.random(), timestamps, or user-chosen words.
Step 2. Mnemonic to seed: PBKDF2 and the BIP39 passphrase
The words are not the key. BIP-39 feeds them into PBKDF2 with HMAC-SHA512 as the PRF, 2048 iterations, and a salt equal to the string "mnemonic" plus an optional passphrase. Both strings are first normalized to UTF-8 NFKD. The output is 512 bits (64 bytes).
// BIP-39 step 2: mnemonic (+ optional passphrase) -> 64-byte seed via PBKDF2-HMAC-SHA512
import { pbkdf2 } from '@noble/hashes/pbkdf2.js';
import { sha512 } from '@noble/hashes/sha2.js';
import { utf8ToBytes } from '@noble/hashes/utils.js';
export function seedByHand(mnemonic: string, passphrase = '', opts = { nfkd: true }) {
const norm = (s: string) => (opts.nfkd ? s.normalize('NFKD') : s);
return pbkdf2(sha512, utf8ToBytes(norm(mnemonic)), utf8ToBytes(norm('mnemonic' + passphrase)), {
c: 2048, // iteration count fixed by BIP-39
dkLen: 64, // 512-bit seed
});
}
The nfkd switch exists only to demonstrate a bug later. The demo compares the hand-written version with the library, then tries a few passphrases on the same 12 words:
import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english.js';
import { bytesToHex } from '@noble/hashes/utils.js';
import { seedByHand } from '../src/seed.js';
import { deriveEthAccounts } from '../src/eth.js';
const TEST = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
const short = (b: Uint8Array) => bytesToHex(b).slice(0, 16) + '...';
console.log('seed("", by hand) :', short(seedByHand(TEST)));
console.log('seed("", library) :', short(mnemonicToSeedSync(TEST)));
console.log('seed("TREZOR") :', short(mnemonicToSeedSync(TEST, 'TREZOR')));
// Every passphrase is "valid" and opens a different wallet
for (const pass of ['', 'TREZOR', 'trezor', 'TREZOR ']) {
const [acc] = deriveEthAccounts(mnemonicToSeedSync(TEST, pass), 1);
console.log(`passphrase ${JSON.stringify(pass).padEnd(9)} -> ${acc.address}`);
}
// NFKD: the same visible passphrase typed as NFC vs NFD
const nfc: string = 'caf\u00e9'; // precomposed é
const nfd: string = 'cafe\u0301'; // e + combining acute accent
console.log('NFC === NFD as JS strings?', nfc === nfd);
console.log('no normalization : same seed?', bytesToHex(seedByHand(TEST, nfc, { nfkd: false })) === bytesToHex(seedByHand(TEST, nfd, { nfkd: false })));
console.log('NFKD (BIP-39) : same seed?', bytesToHex(seedByHand(TEST, nfc)) === bytesToHex(seedByHand(TEST, nfd)));
// mnemonicToSeed does not check the checksum
const bad = Array(12).fill('abandon').join(' ');
console.log('12 x abandon valid?', validateMnemonic(bad, wordlist), '| seed anyway:', short(mnemonicToSeedSync(bad)));
try {
mnemonicToSeedSync(TEST.replace(' ', ' '));
} catch (e) {
console.log('double space ->', (e as Error).message);
}
seed("", by hand) : 5eb00bbddcf06908...
seed("", library) : 5eb00bbddcf06908...
seed("TREZOR") : c55257c360c07c72...
passphrase "" -> 0x9858EfFD232B4033E47d90003D41EC34EcaEda94
passphrase "TREZOR" -> 0x9c32F71D4DB8Fb9e1A58B0a80dF79935e7256FA6
passphrase "trezor" -> 0xF57a402315aa9E2E20244335C3B45156221465a6
passphrase "TREZOR " -> 0x30eD3A3D1ec5C61bEFEC16b9552c5E5533ab2760
NFC === NFD as JS strings? false
no normalization : same seed? false
NFKD (BIP-39) : same seed? true
12 x abandon valid? false | seed anyway: 94cfb81f135f8d85...
double space -> Invalid mnemonic
The first three lines match the official BIP-39 vector for abandon ... about: the vectors use the passphrase TREZOR, and the seed starting with c55257c3 is the one in the vector file.
A BIP39 passphrase is a different wallet, not a password check
There is no “wrong passphrase” error in BIP-39. The spec says every passphrase generates a valid seed and calls this plausible deniability. In practice it means:
-
"","TREZOR","trezor"and"TREZOR "(trailing space) produced four unrelated addresses from the same 12 words. - A user who mistypes their passphrase sees an empty wallet, not an error. Your UI should say so explicitly (“empty wallet? check your passphrase”) instead of letting them panic or, worse, deposit into the wrong wallet.
- Do not trim, lowercase or “clean up” passphrases. The trailing space above is part of the key.
PBKDF2 with 2048 iterations is not a strong password hash by modern standards. OWASP’s Password Storage Cheat Sheet suggests 220,000 iterations for PBKDF2-HMAC-SHA512. The BIP-39 iteration count was fixed long ago and cannot change without breaking every wallet, so a short passphrase adds little protection against someone who already has the words. The words themselves (128+ bits of entropy) carry the security.
Step 3. Seed to master key: BIP-32
BIP-32 computes I = HMAC-SHA512(key = "Bitcoin seed", data = seed). The left 32 bytes become the master private key, the right 32 bytes the master chain code. The key string says “Bitcoin seed” even when you derive Ethereum keys; it is a constant, not a network choice.
Each node in the tree is the pair (key, chain code). A child is computed as:
-
Non-hardened child (index
i < 2^31):I = HMAC-SHA512(chainCode, serP(parentPublicKey) || ser32(i)), thenchildKey = (IL + parentKey) mod n. -
Hardened child (index
i >= 2^31, writteni'oriH):I = HMAC-SHA512(chainCode, 0x00 || ser256(parentPrivateKey) || ser32(i)).
The difference in the HMAC input is the whole security story, and we will exploit it in Step 5. One more rule from the spec: if IL >= n or the resulting key is zero, the key is invalid and you move on to the next index. @scure/bip32 implements that retry, and the odds of hitting it are negligible, but a hand-rolled implementation that skips it is not BIP-32.
An extended key (xprv / xpub) is a 78-byte structure (version, depth, parent fingerprint, index, chain code, key) encoded in Base58Check. The version bytes 0x0488ADE4 and 0x0488B21E are why mainnet keys start with xprv and xpub.
BIP-32 ships its own test vectors. Test vector 1 starts from the seed 000102030405060708090a0b0c0d0e0f and lists xpub/xprv strings for six paths. The test copies all of them from the BIP and also checks that public-only derivation from an xpub produces the same keys:
import { describe, expect, it } from 'vitest';
import { HDKey } from '@scure/bip32';
import { hexToBytes } from '@noble/hashes/utils.js';
// BIP-32 Test vector 1 (copied from the BIP; H = hardened)
const seed = hexToBytes('000102030405060708090a0b0c0d0e0f');
const chains: [string, string, string][] = [
['m', 'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8', 'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi'],
["m/0'", 'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw', 'xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7'],
["m/0'/1", 'xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ', 'xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs'],
["m/0'/1/2'", 'xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5', 'xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM'],
["m/0'/1/2'/2", 'xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV', 'xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334'],
["m/0'/1/2'/2/1000000000", 'xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy', 'xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76'],
];
describe('BIP-32 test vector 1', () => {
const master = HDKey.fromMasterSeed(seed);
it.each(chains)('%s', (path, xpub, xprv) => {
const node = master.derive(path);
expect(node.publicExtendedKey).toBe(xpub);
expect(node.privateExtendedKey).toBe(xprv);
});
it('public derivation from an xpub matches private derivation for non-hardened steps', () => {
const parent = HDKey.fromExtendedKey(chains[3][1]); // xpub at m/0'/1/2'
expect(parent.derive('m/2/1000000000').publicExtendedKey).toBe(chains[5][1]);
});
it('an xpub cannot derive a hardened child', () => {
expect(() => HDKey.fromExtendedKey(chains[0][1]).derive("m/0'")).toThrow();
});
});
Step 4. BIP-44 paths and Ethereum addresses
This is the part most people look for in an Ethereum HD wallet tutorial. BIP-44 gives the tree a fixed shape:
m / purpose' / coin_type' / account' / change / address_index
m / 44' / 60' / 0' / 0 / i
-
purposeis always44'. -
coin_typecomes from the SLIP-0044 registry:0'is Bitcoin,1'is testnet for all coins,60'is Ether. -
accountseparates independent accounts. The first three levels are hardened. -
changeis0for external (receiving) addresses and1for internal (change) addresses. All Ethereum paths in this article stay on0. -
address_indexcounts up from 0. BIP-44 sets the address gap limit at 20 for account discovery.
The Ethereum part is short. Take the uncompressed secp256k1 public key (65 bytes, 0x04 || X || Y), drop the prefix byte, hash with Keccak-256, keep the last 20 bytes. Then apply EIP-55: hash the lowercase hex address with Keccak-256 and uppercase each letter whose matching hash nibble is 8 or higher.
// BIP-44 paths + Ethereum addresses with EIP-55 checksums
import { HDKey } from '@scure/bip32';
import { secp256k1 } from '@noble/curves/secp256k1.js';
import { keccak_256 } from '@noble/hashes/sha3.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
export const ethPath = (account = 0, index = 0) => `m/44'/60'/${account}'/0/${index}`;
export function toChecksumAddress(address: string): string {
const lower = address.toLowerCase().replace(/^0x/, '');
if (!/^[0-9a-f]{40}$/.test(lower)) throw new Error('not a 20-byte hex address');
const hash = bytesToHex(keccak_256(utf8ToBytes(lower))); // hash of the ASCII hex string
return '0x' + [...lower].map((c, i) => (parseInt(hash[i], 16) >= 8 ? c.toUpperCase() : c)).join('');
}
export function isValidChecksumAddress(address: string): boolean {
return /^0x[0-9a-fA-F]{40}$/.test(address) && toChecksumAddress(address) === address;
}
// Works with a compressed (33-byte) or uncompressed (65-byte) secp256k1 public key
export function publicKeyToAddress(publicKey: Uint8Array): string {
const uncompressed = secp256k1.Point.fromBytes(publicKey).toBytes(false); // 0x04 || X || Y
const digest = keccak_256(uncompressed.slice(1)); // drop the 0x04 prefix
return toChecksumAddress(bytesToHex(digest.slice(-20))); // last 20 bytes
}
export function deriveEthAccounts(seed: Uint8Array, count: number, account = 0) {
const root = HDKey.fromMasterSeed(seed);
const external = root.derive(`m/44'/60'/${account}'/0`); // derive the hardened part once
return Array.from({ length: count }, (_, i) => {
const node = external.deriveChild(i);
return { path: ethPath(account, i), address: publicKeyToAddress(node.publicKey!), node };
});
}
The demo uses Hardhat’s default development mnemonic, because its addresses are documented, so we can compare against something independent:
import { mnemonicToSeedSync } from '@scure/bip39';
import { HDKey } from '@scure/bip32';
import { deriveEthAccounts, publicKeyToAddress } from '../src/eth.js';
// Hardhat's public development mnemonic. Anything sent to these addresses on mainnet gets swept.
const DEV = 'test test test test test test test test test test test junk';
const seed = mnemonicToSeedSync(DEV);
const root = HDKey.fromMasterSeed(seed);
console.log('master depth', root.depth, 'fingerprint', root.fingerprint.toString(16));
for (const { path, address, node } of deriveEthAccounts(seed, 3)) {
console.log(path, address, `depth=${node.depth} index=${node.index}`);
}
// Watch-only: an xpub of the external chain derives the same addresses, no private keys
const chainXpub = root.derive("m/44'/60'/0'/0").publicExtendedKey;
console.log('xpub prefix:', chainXpub.slice(0, 4), 'length:', chainXpub.length);
const watch = HDKey.fromExtendedKey(chainXpub);
const fromXpub = [0, 1, 2].map((i) => publicKeyToAddress(watch.deriveChild(i).publicKey!));
console.log('from xpub :', fromXpub.join(' '));
console.log('has private key?', watch.privateKey !== null);
master depth 0 fingerprint 16a93ed0
m/44'/60'/0'/0/0 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 depth=5 index=0
m/44'/60'/0'/0/1 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 depth=5 index=1
m/44'/60'/0'/0/2 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC depth=5 index=2
xpub prefix: xpub length: 111
from xpub : 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC
has private key? false
0xf39Fd6e5...2266 is the first address Hardhat Network lists for test test ... junk with its default path m/44'/60'/0'/0. The second half of the demo is the watch-only pattern: a server that only needs to generate receiving addresses can hold the xpub of m/44'/60'/0'/0 and derive the same addresses without any private key. Remember that pattern; the next step shows its sharp edge.
Note that wallets do not all walk the tree the same way. The ethers v6 docs describe two patterns: one increments the account level (they cite Ledger), the other increments the last address_index level (they cite MetaMask). If a user imports the same mnemonic into two wallets and sees different accounts, the derivation path is the first thing to check.
The EIP-55 tests use the eight addresses listed in the EIP itself:
import { describe, expect, it } from 'vitest';
import { mnemonicToSeedSync } from '@scure/bip39';
import { HDKey, HARDENED_OFFSET } from '@scure/bip32';
import { deriveEthAccounts, isValidChecksumAddress, toChecksumAddress } from '../src/eth.js';
import { recoverParentPrivateKey } from '../src/leak.js';
// EIP-55 test cases from the EIP
const eip55 = [
'0x52908400098527886E0F7030069857D2E4169EE7',
'0x8617E340B3D01FA5F11F306F4090FD50E238070D',
'0xde709f2102306220921060314715629080e2fb77',
'0x27b1fdb04752bbc536007a920d24acb045561c26',
'0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
'0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB',
'0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb',
];
const DEV = 'test test test test test test test test test test test junk'; // Hardhat default
describe('EIP-55', () => {
it.each(eip55)('%s', (addr) => {
expect(toChecksumAddress(addr.toLowerCase())).toBe(addr);
expect(isValidChecksumAddress(addr)).toBe(true);
});
it('one flipped letter case breaks the checksum', () => {
const bad = eip55[4].replace('aAeb', 'aaeb');
expect(isValidChecksumAddress(bad)).toBe(false);
});
});
describe("BIP-44 m/44'/60'/0'/0/i", () => {
it('matches Hardhat account #0 for the default dev mnemonic', () => {
const [acc0] = deriveEthAccounts(mnemonicToSeedSync(DEV), 1);
expect(acc0.address).toBe('0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266');
});
});
describe('xpub + non-hardened child private key leak', () => {
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(DEV));
const chain = root.derive("m/44'/60'/0'/0");
it('recovers the parent xprv from xpub + child key', () => {
for (const i of [0, 7, 1999]) {
const leaked = chain.deriveChild(i).privateKey!;
expect(recoverParentPrivateKey(chain.publicExtendedKey, leaked, i).privateExtendedKey).toBe(chain.privateExtendedKey);
}
});
it('does not work for a hardened child', () => {
const account = root.derive("m/44'/60'/0'");
const i = HARDENED_OFFSET + 1;
const leaked = account.deriveChild(i).privateKey!;
expect(recoverParentPrivateKey(account.publicExtendedKey, leaked, i).privateExtendedKey).not.toBe(account.privateExtendedKey);
});
});
EIP-55 adds 15 check bits per address on average; the EIP estimates that a mistyped address passes the check with a probability of 0.0247%. An all-lowercase address carries no checksum at all, so treat “valid hex” and “valid checksum” as two different checks in your input validation.
Step 5. Hardened vs non-hardened keys: the xpub leak
The BIP-32 Security section warns that knowing a parent extended public key plus any non-hardened private key descending from it is equivalent to knowing the parent extended private key. It sounds abstract until you write the five lines that do it.
For a non-hardened child, every input to the HMAC is public: the parent chain code and the parent public key are both inside the xpub, and the index is just a number. So the attacker can compute IL and subtract it:
// Why xpub + one non-hardened child private key = parent private key (BIP-32 "Security")
import { HDKey, HARDENED_OFFSET } from '@scure/bip32';
import { secp256k1 } from '@noble/curves/secp256k1.js';
import { hmac } from '@noble/hashes/hmac.js';
import { sha512 } from '@noble/hashes/sha2.js';
import { bytesToNumberBE, numberToBytesBE } from '@noble/curves/utils.js';
const n = secp256k1.Point.Fn.ORDER;
export function recoverParentPrivateKey(parentXpub: string, childPrivateKey: Uint8Array, index: number) {
// For a hardened index the real HMAC input is 0x00 || parent PRIVATE key || index.
// An attacker only has public data, so the formula below yields a wrong key.
if (index >= HARDENED_OFFSET) console.warn('warning: hardened index, result will be garbage');
const parent = HDKey.fromExtendedKey(parentXpub); // public data only
const ser32 = new Uint8Array(4);
new DataView(ser32.buffer).setUint32(0, index); // big-endian
const data = new Uint8Array([...parent.publicKey!, ...ser32]);
const I = hmac(sha512, parent.chainCode!, data); // everything here is public
const IL = bytesToNumberBE(I.slice(0, 32));
// child = (IL + parent) mod n => parent = (child - IL) mod n
const parentKey = (((bytesToNumberBE(childPrivateKey) - IL) % n) + n) % n;
return new HDKey({
privateKey: numberToBytesBE(parentKey, 32),
chainCode: parent.chainCode!,
depth: parent.depth,
index: parent.index,
parentFingerprint: parent.parentFingerprint,
});
}
The scenario: a payment server holds the xpub of m/44'/60'/0'/0 to generate deposit addresses. Separately, the private key of address /0/7 leaks (a debug log, a hot wallet that exported one key, a support ticket).
import { mnemonicToSeedSync } from '@scure/bip39';
import { HDKey, HARDENED_OFFSET } from '@scure/bip32';
import { recoverParentPrivateKey } from '../src/leak.js';
import { publicKeyToAddress } from '../src/eth.js';
const DEV = 'test test test test test test test test test test test junk'; // public test mnemonic
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(DEV));
// Scenario: the server holds the chain xpub (m/44'/60'/0'/0) and one child private key leaks.
const chain = root.derive("m/44'/60'/0'/0");
const leakedIndex = 7;
const leakedChildKey = chain.deriveChild(leakedIndex).privateKey!;
const recovered = recoverParentPrivateKey(chain.publicExtendedKey, leakedChildKey, leakedIndex);
console.log('recovered xprv == real xprv?', recovered.privateExtendedKey === chain.privateExtendedKey);
for (const i of [0, 1, 2]) {
const k = recovered.deriveChild(i);
console.log(`attacker signs for /0/${i}:`, publicKeyToAddress(k.publicKey!));
}
// Climb one more level: with the ACCOUNT xpub, the recovered chain key is itself a non-hardened child
const account0 = root.derive("m/44'/60'/0'");
const climbed = recoverParentPrivateKey(account0.publicExtendedKey, recovered.privateKey!, 0);
console.log("account xprv m/44'/60'/0' recovered?", climbed.privateExtendedKey === account0.privateExtendedKey);
// Same attack against a hardened child fails: the HMAC input includes the parent private key
const account = root.derive("m/44'/60'/0'");
const hardenedChild = account.deriveChild(HARDENED_OFFSET + 1).privateKey!;
const guess = recoverParentPrivateKey(account.publicExtendedKey, hardenedChild, HARDENED_OFFSET + 1);
console.log('hardened: recovered == real?', guess.privateExtendedKey === account.privateExtendedKey);
try {
HDKey.fromExtendedKey(account.publicExtendedKey).deriveChild(HARDENED_OFFSET);
} catch (e) {
console.log('xpub -> hardened child:', (e as Error).message);
}
recovered xprv == real xprv? true
attacker signs for /0/0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
attacker signs for /0/1: 0x70997970C51812dc3A010C7d01b50e0d17dc79C8
attacker signs for /0/2: 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC
account xprv m/44'/60'/0' recovered? true
warning: hardened index, result will be garbage
hardened: recovered == real? false
xpub -> hardened child: Could not derive hardened child key
![Derivation tree: a leaked key at /0/7 plus xpubs lets an attacker climb to the account key, and the climb stops at the hardened level]

Derivation tree: a leaked key at /0/7 plus xpubs lets an attacker climb to the account key, and the climb stops at the hardened level
What the output shows:
- One leaked child key plus the chain
xpubgives back the exact chainxprv. From there the attacker can sign for/0/0,/0/1, and every other address on that chain, including ones you will generate next year. - It climbs.
m/44'/60'/0'/0is itself a non-hardened child of the account node, so if the account-levelxpubis also exposed (wallets often export it for watch-only mode), the attacker recovers the accountxprvas well. - It stops at a hardened level. For
0'the HMAC input contains the parent private key, which the attacker does not have; the same arithmetic produces a meaningless key. And anxpubcannot derive hardened children at all, which is the error on the last line.
That is why BIP-44 hardens purpose, coin_type and account: a compromise is contained to one account. Practical rules:
- Treat an
xpubas sensitive. It cannot spend by itself, but it reveals every address and balance in the branch, and it is half of the attack above. - Never export single private keys from a branch whose
xpublives anywhere else. - If you need isolation between tenants, customers or environments, put the boundary at a hardened level (a separate
account'), not ataddress_index.
Step 6. Run the official test vectors
The whole pipeline is pinned down by public vectors, so there is no excuse to ship it untested. The BIP-39 spec points to the vector file in Trezor’s python-mnemonic repository: each entry has entropy, mnemonic, seed (with passphrase TREZOR) and the BIP-32 master xprv. The same test checks the hand-written code and the library:
// Official vectors from trezor/python-mnemonic (referenced by BIP-39). Passphrase is "TREZOR".
type Vector = [entropy: string, mnemonic: string, seed: string, xprv: string];
const vectors: Record<string, Vector[]> = JSON.parse(readFileSync('vectors/bip39-vectors.json', 'utf8'));
describe('BIP-39 official vectors (english)', () => {
it.each(vectors.english)('%s', (entropy, mnemonic, seed, xprv) => {
expect(entropyToMnemonicByHand(hexToBytes(entropy), english).words.join(' ')).toBe(mnemonic);
expect(entropyToMnemonic(hexToBytes(entropy), english)).toBe(mnemonic);
expect(bytesToHex(mnemonicToEntropy(mnemonic, english))).toBe(entropy);
expect(bytesToHex(seedByHand(mnemonic, 'TREZOR'))).toBe(seed);
expect(bytesToHex(mnemonicToSeedSync(mnemonic, 'TREZOR'))).toBe(seed);
expect(HDKey.fromMasterSeed(hexToBytes(seed)).privateExtendedKey).toBe(xprv);
});
});
The suite also runs the 24 Japanese vectors (more on why below) and the gotchas from Step 2.
npx vitest run
✓ test/bip39.test.ts (52 tests) 6095ms
✓ test/eth.test.ts (12 tests) 353ms
✓ test/bip32.test.ts (8 tests) 266ms
Test Files 3 passed (3)
Tests 72 passed (72)
72 tests: 24 English BIP-39 vectors, 24 Japanese vectors, 4 gotcha tests, 8 BIP-32 tests, 8 EIP-55 vectors, and 4 tests for the Hardhat address and the leak. When they pass, the hand-written entropy and seed code, the library, and the Ethereum address code all agree with three independent sources.
Gotchas that bite real wallets
![The same 12 words with four passphrases give four unrelated addresses; NFC and NFD forms of café match only after NFKD]

The same 12 words with four passphrases give four unrelated addresses; NFC and NFD forms of café match only after NFKD
1. Unicode normalization (NFKD). "café" can be typed as one code point (é, NFC) or two (e + combining accent, NFD). They render identically but are different bytes. The demo in Step 2 shows that without normalization the two produce different seeds, and with NFKD (what BIP-39 requires) they match. The Japanese vectors are a stronger test: the phrases are separated by an ideographic space (U+3000). NFKD maps it to a regular space, so a correct implementation derives the expected seed, and the test asserts that skipping NFKD does not. If you implement BIP-39 in another language or call PBKDF2 directly, normalize both the mnemonic and "mnemonic" + passphrase.
2. mnemonicToSeed does not validate. Twelve abandons fail the checksum, yet mnemonicToSeedSync returned a seed. The scure source says it plainly: the seed helpers normalize the phrase but do not verify checksum or wordlist membership. Always call validateMnemonic(phrase, wordlist) first. Otherwise a typo during recovery silently creates a fresh, empty wallet.
3. Whitespace and case. The library splits on a single space after NFKD, so a double space gives a word count that is not 12/15/18/21/24 and throws Invalid mnemonic. That is better than silently deriving a different seed, but your input field should collapse whitespace and lowercase the words before validation. Never apply that cleanup to the passphrase.
4. The passphrase is part of the key. Losing it is equivalent to losing the words. Storing it next to the words removes the point of having one.
5. Paths are a convention, not a property of the mnemonic. The same phrase gives different addresses on m/44'/60'/0'/0/i and m/44'/60'/i'/0/0. Record which path scheme your product uses, and if you scan for existing funds during recovery, scan the plausible ones up to the gap limit.
6. Key material in memory and logs. HDKey has wipePrivateData(). Use it for long-lived objects, never log privateExtendedKey, and keep test mnemonics out of anything that could be deployed against a real network.
Production checklist
- Generate entropy with a CSPRNG only (
generateMnemonic), 128 bits minimum, 256 if your threat model warrants it. -
validateMnemonicbeforemnemonicToSeed, with a clear error that does not echo the phrase. - NFKD for mnemonic and passphrase; no trimming of passphrases; explain in the UI that a different passphrase opens a different wallet.
- Pin library versions and run the BIP-39, BIP-32 and EIP-55 vectors in CI on every upgrade.
- Harden every level that separates trust domains; treat
xpubexports as sensitive data. - Never export single child private keys from a branch whose
xpubis stored elsewhere. - Document the derivation path scheme and the gap limit you scan during recovery.
- Validate EIP-55 checksums on input and produce checksummed addresses on output.
- Keep signing in an isolated component (HSM, secure enclave, hardware wallet or MPC), and let everything else work with public data.
Wrapping up
An HD wallet is four small, well-specified transformations stacked on each other: BIP-39 for words and seeds, BIP-32 for the key tree, BIP-44 for the path layout, and Keccak plus EIP-55 for Ethereum addresses. Each step fits in a few dozen lines, and each has official vectors, so you can prove your implementation correct instead of eyeballing addresses. The parts that cause real incidents are not the hashes but the conventions around them: unnormalized strings, unvalidated phrases, “wrong” passphrases that work, and xpubs treated as public.
Have you run into a derivation path mismatch or a passphrase surprise in production? How did you detect it?
The complete code (sources, demos, tests) is about 350 lines plus the vector file, and runs with ./run-all.sh.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.