# Derive HD keys with BIP32

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Derive child keys and testnet addresses from a BIP32 extended key or a BIP39 recovery phrase with the HD class of @bsv/sdk.

import BlueTable from '/snippets/BlueTable.jsx';

Derive child keys and testnet addresses from a BIP32 (Bitcoin Improvement Proposal 32: hierarchical deterministic keys, a tree of keys derived from one master key) master key with the `HD` class of `@bsv/sdk`, then derive the same addresses from an xpub (Extended public key, a string that starts with xpub) that holds no private key. BRC-100 (The standard interface between apps and wallets) wallets derive their keys with BRC-42 (BSV Key Derivation Scheme), so use BIP32 when your code receives keys from another tool, such as an extended key exported from another wallet, a BIP39 (Bitcoin Improvement Proposal 39: a list of words that encodes the seed of a master key) recovery phrase, or a service that asks for an xpub. The SDK marks `HD` as deprecated in favor of BRC-42, and keeps it for compatibility with BIP32 keys. The scripts run offline in a standalone Node project and need no wallet, network or funds.

## Before you begin

You need:

- [Node.js](https://nodejs.org/) 22 or newer, which reads a `.env` file with the `--env-file` flag.
- An empty folder for the project.

In that folder, run these commands to create an ES module project, install the SDK and keep `.env` out of git:

```bash
npm init -y
npm pkg set type=module
npm install @bsv/sdk
echo ".env" >> .gitignore
```

This page was written against `@bsv/sdk` 4.0.1.

## How it works

A BIP32 key is an extended key, a key plus a chain code. An xprv (Extended private key, a string that starts with xprv) derives child private keys, and the matching xpub derives child public keys. A path such as `m/0'/0/1` names one child. In a path, `m` is the key you derive from, and each number below it is a child index from 0 to 2,147,483,647. An apostrophe marks a hardened index, which only an xprv can derive. A path made only of plain indexes can be derived from the xpub too, so a server can watch addresses without holding a private key.

Both schemes are in `@bsv/sdk`, and they differ in what a child depends on. The BRC-42 column follows [BRC-42](https://bsv.brc.dev/key-derivation/0042):

<BlueTable>

| Aspect | BIP32 (`HD`) | BRC-42 (`KeyDeriver`, `ProtoWallet`) |
|---|---|---|
| What names a child key | A path of numeric indexes, such as `m/0'/0/1` | A protocol ID, a key ID and a counterparty, as set by [BRC-43](https://bsv.brc.dev/key-derivation/0043) |
| Who can derive public children | Anyone who has the xpub, for plain indexes | The two parties, each from their own private key and the other party's public key |
| Key universes | One per master public key | One for each pair of parties |

</BlueTable>

Use `HD` to read, derive and export keys that follow BIP32 and BIP39. For keys that your app and a BRC-100 wallet work with, use BRC-42, as the [wallet backend guide](https://bsvblockchain.com/docs/wallet-dev/infrastructure/) does with `KeyDeriver`.

## Create a master key

The first step is to generate a random master key and store its xprv in `.env`, where the next scripts read it:

**1. Write the script**

> The xprv controls every key derived from it. Keep it in `.env`, never in code or in a terminal log, and check that `.gitignore` lists `.env` before you commit.

Save this as `create-master.mjs` in the project folder:

```javascript create-master.mjs
import { appendFileSync } from 'node:fs'
import { HD } from '@bsv/sdk'

const master = HD.fromRandom()
appendFileSync('.env', `XPRV=${master.toString()}\n`)

console.log('Master xpub:', master.toPublic().toString())
```

The script writes the xprv to `.env` and prints only the xpub, which `toPublic()` returns without the private part.

**2. Run the script**

Run it from the project folder:

```bash
node create-master.mjs
```

The script prints the master xpub, shortened here:

```text
Master xpub: xpub661M...dsvZdn
```

The `.env` file now has an `XPRV=` line. Run the script once: a second run adds another `XPRV=` line, and Node reads the last one, so the next steps would use a different key.

## Derive child keys and addresses

With the xprv in `.env`, derive three receiving addresses under one hardened account and export the xpub of that account:

**1. Write the derivation script**

Create `derive.mjs` next to the first script:

```javascript derive.mjs
import { HD } from '@bsv/sdk'

const master = HD.fromString(process.env.XPRV)

for (let i = 0; i < 3; i++) {
  const path = `m/0'/0/${i}`
  const child = master.derive(path)
  console.log(path, child.pubKey.toAddress('testnet'))
}

const account = master.derive("m/0'")
console.log('Account xpub:', account.toPublic().toString())
```

- The `HD.fromString()` call reads an xprv or an xpub, including one exported by another tool.
- Each `derive()` call takes the full path and returns a new `HD` for that child.
- The `toAddress('testnet')` call encodes the child public key as a testnet address. Without the argument, it returns the Mainnet address of the same key.
- The `child.privKey` property is a `PrivateKey` that signs for that address. The script does not print it.

**2. Run the derivation**

Pass `.env` to Node so that the script can read `XPRV`:

```bash
node --env-file=.env derive.mjs
```

Each line pairs a path with its testnet address, and the last line is the xpub of `m/0'`:

```text
m/0'/0/0 n1wRCGjLreHFaDgZMVZtUeVxMmHLGCcoVQ
m/0'/0/1 mqjY4wVZmNuMwjkZzDhGRscWzxU4GsSszj
m/0'/0/2 mhikdk3oEVScuS2ViXRu5MwFCb2BjeuQAo
Account xpub: xpub69ST...dJAWXv
```

## Derive addresses from an xpub

The account xpub derives the same addresses as the xprv for the plain indexes under it, which lets a watch-only service generate receiving addresses:

**1. Add the xpub to the environment**

Open `.env` and add a line with the account xpub that the last script printed:

```text .env
ACCOUNT_XPUB=ACCOUNT_XPUB_FROM_DERIVE
```

Replace `ACCOUNT_XPUB_FROM_DERIVE` with the full `xpub` string. An xpub cannot sign, but it reveals every address under it, so treat it as private data. Never give a child private key to anyone who has this xpub: together they reveal the account private key.

**2. Write the watch-only script**

Save `watch.mjs` in the project folder:

```javascript watch.mjs
import { HD } from '@bsv/sdk'

const account = HD.fromString(process.env.ACCOUNT_XPUB)

for (let i = 0; i < 3; i++) {
  const child = account.derive(`m/0/${i}`)
  console.log(`m/0'/0/${i}`, child.pubKey.toAddress('testnet'))
}
```

Here `m` stands for the account key, so `m/0/0` from the account is `m/0'/0/0` from the master.

**3. Compare the addresses**

Run the script with the same `.env`:

```bash
node --env-file=.env watch.mjs
```

The addresses match the ones from the xprv:

```text
m/0'/0/0 n1wRCGjLreHFaDgZMVZtUeVxMmHLGCcoVQ
m/0'/0/1 mqjY4wVZmNuMwjkZzDhGRscWzxU4GsSszj
m/0'/0/2 mhikdk3oEVScuS2ViXRu5MwFCb2BjeuQAo
```

A child derived from an xpub has no `privKey`, and a hardened index such as `m/1'` throws an error.

## Start from a recovery phrase

The `Mnemonic` class reads a BIP39 phrase and turns it into the seed of a master key, for a key that another wallet created from a phrase:

**1. Add the phrase to the environment**

> A recovery phrase gives full control of every key derived from it. Test with a new phrase, never with one that holds funds, and keep it in `.env` only.

Add the phrase to `.env` on one line, with the words separated by spaces:

```text .env
MNEMONIC=YOUR_RECOVERY_PHRASE
```

Replace `YOUR_RECOVERY_PHRASE` with the words of the phrase. To create a new 12-word test phrase instead, this command writes it to `.env` without printing it:

```bash
node -e "import('@bsv/sdk').then(({ Mnemonic }) => require('node:fs').appendFileSync('.env', '\nMNEMONIC=' + Mnemonic.fromRandom().toString() + '\n'))"
```

For 24 words, pass `256` to `Mnemonic.fromRandom()`.

**2. Write the import script**

Create `from-phrase.mjs` in the project folder:

```javascript from-phrase.mjs
import { HD, Mnemonic } from '@bsv/sdk'

const seed = Mnemonic.fromString(process.env.MNEMONIC).toSeed(process.env.BIP39_PASSPHRASE)
const master = HD.fromSeed(seed)

console.log('Master xpub:', master.toPublic().toString())
```

- If the phrase has a passphrase, add it to `.env` as `BIP39_PASSPHRASE='YOUR_PASSPHRASE'`, with the single quotes. Without them, Node cuts the value at a `#` and trims spaces at the ends, and the master key changes. Without that line, `toSeed()` uses no passphrase. A different passphrase gives a different master key.
- The checksum in `Mnemonic.fromString()` catches most typing mistakes, but not every wrong word. Compare the master xpub with the one the original wallet shows before you rely on the key.

**3. Run the import**

Pass `.env` to Node again:

```bash
node --env-file=.env from-phrase.mjs
```

The script prints the master xpub of the phrase, shortened here:

```text
Master xpub: xpub661M...WWDd1D
```

The same phrase and passphrase always give the same master key, so the derivation steps above work on it unchanged.

## Troubleshooting

**Key is missing when the script starts**

The error `BIP32 extended key must be a bounded string` means the script did not get `XPRV` or `ACCOUNT_XPUB`. Run it with `node --env-file=.env`, and check that `.env` has that line.

**Hardened path fails from an xpub**

The error `Cannot do private key derivation without private key` means the path has a hardened index, marked with an apostrophe, and the key is an xpub. Derive that level from the xprv, or export the xpub at the last hardened level and derive only plain indexes from it.

**Path copied from another tool is rejected**

The error `invalid path` means `derive()` could not read the path. It accepts only paths that start with `m` and mark hardened indexes with an apostrophe, so write `m/0'/1` instead of `m/0h/1` or `0'/1`.

**Extended key that starts with tprv or tpub is rejected**

The error `Invalid key` from `HD.fromString()` appears with testnet extended keys, because `HD` reads and writes only `xprv` and `xpub` strings. Export the key in its `xprv` or `xpub` form from the tool that created it. The key does not depend on the network, and `toAddress('testnet')` returns its testnet address.

**Master xpub differs from the one the original wallet shows**

The phrase is right but the passphrase is not the one the wallet used. Check that `BIP39_PASSPHRASE` is in single quotes in `.env`. Without quotes, Node cuts the value at a `#` and trims spaces at the ends, so `toSeed()` gets a different passphrase and no error appears.

**Recovery phrase is rejected**

The error `Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?` means a word is wrong, missing or out of order, or the line has extra spaces. Check the phrase in `.env` word by word.

## Related articles

To learn how BRC-42 key derivation replaces BIP32 in wallets, review these articles:

- [How keys and identity work](https://bsvblockchain.com/docs/concepts/keys-identity/)
- [BRC-100 Wallet Interface](https://bsvblockchain.com/docs/concepts/wallet-model/)