BSV blockchainBSV blockchain

Derive HD keys with BIP32

Derive child keys and testnet addresses from a BIP32Bitcoin 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 xpubExtended public key, a string that starts with xpub that holds no private key. BRC-100The standard interface between apps and wallets wallets derive their keys with BRC-42BSV Key Derivation Scheme, so use BIP32 when your code receives keys from another tool, such as an extended key exported from another wallet, a BIP39Bitcoin 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 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:

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 xprvExtended 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:

AspectBIP32 (HD)BRC-42 (KeyDeriver, ProtoWallet)
What names a child keyA path of numeric indexes, such as m/0'/0/1A protocol ID, a key ID and a counterparty, as set by BRC-43
Who can derive public childrenAnyone who has the xpub, for plain indexesThe two parties, each from their own private key and the other party’s public key
Key universesOne per master public keyOne for each pair of parties

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 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:

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:

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.

Run the script

Run it from the project folder:

node create-master.mjs

The script prints the master xpub, shortened here:

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:

Write the derivation script

Create derive.mjs next to the first script:

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.

Run the derivation

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

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':

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:

Add the xpub to the environment

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

.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.

Write the watch-only script

Save watch.mjs in the project folder:

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.

Compare the addresses

Run the script with the same .env:

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

The addresses match the ones from the xprv:

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:

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:

.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:

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().

Write the import script

Create from-phrase.mjs in the project folder:

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.

Run the import

Pass .env to Node again:

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

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

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.

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