LogoLogo
LogoLogo
  • Intro
    • Welcome
    • The Benefits of BSV Blockchain
    • What Can I Do?
    • Overview of GitHub repositories
    • Quick Start
  • Protocol
    • Introduction
    • BSV Blockchain
      • Blocks
      • Transactions
      • Proof of Work
      • Capabilities
      • Economic Model of Governance
      • Digital Asset Recovery
    • Network Policies
      • High-Level Architecture
      • Mining
      • Standard and Local Policies
      • Consensus Rules
      • Local Policies
    • Node Operations
      • Node Software
      • Bitcoin Server Network (BSN)
      • ChainTracker
      • Transaction Validation
      • UTXO Storage
      • Mempool
      • Block Assembler
      • Block Validation
      • Mining Software
      • Pruning transactions
      • Responsibilities of a Node
    • SPV Wallets, Overlays and SPV Processes
      • Simplified Payment Verification (SPV)
      • Instant Payments
      • Integrity Checks
      • SPV Wallets & Overlays
    • Transaction Lifecycle
      • Transaction Inputs and Outputs
      • Script
      • Transaction Flow
      • Constructing a transaction
      • Sequence Number and Time Locking
      • Transaction Templates
      • Transaction Processing
      • Opcodes used in Script
    • Privacy
      • Keys and Identity
      • Private vs Anonymous
      • Digital Signatures
      • Privacy on the Public Blockchain
  • Network Access Rules
    • Rules
      • Table of Contents
      • Background to the Rules
      • PART I - MASTER RULES
      • PART II - GENERAL RULES
      • PART III - ENFORCEMENT RULES
      • PART IV - DISPUTE RESOLUTION RULES
      • PART V - INTERPRETIVE RULES
    • FAQs
      • Miners
      • Professionals
      • Users
  • Important Concepts
    • High Level
      • Web3
      • Timestamping
      • SPV
      • UTXO vs Account Based
      • Linked Keys
      • Smart Contracts
    • Details
      • Hash Functions
      • Merkle Trees
      • Sighash Flags
      • Script
      • SPV
        • Deep Dive
        • Payments Flow
        • Data Models
        • Broadcasting
  • Network Topology
    • Mandala Upgrade
    • Nodes
      • SV Node
        • Architecture
        • System Requirements
        • Installation
          • SV Node
            • Configuration
            • AWS Volumes Setup
            • DDOS Mitigation
            • Docker
            • Genesis Settings
            • GetMiningCandidate
            • GKE
            • Network Environments
              • Regtest
              • STN
              • Testnet
        • Alert System
          • Alert Messages
          • Running the Alert System
            • Startup Script
          • Webhooks
        • RPC Interface
          • RPC Methods
        • Frequently Asked Questions
          • Blocks
          • Initial Block Download
          • Transactions
          • Log File Warnings
          • Safe Mode
          • Bug Bounty
        • Chronicle Release
      • Teranode
    • Overlay Services
      • Overlay Example
    • SPV Wallet
      • Quickstart
      • Key Concepts
      • AWS Deployment
        • Installation
        • Manage & Maintain
        • Update
        • Delete
      • Components
        • SPV Wallet Server
        • Storage
        • Web Admin
        • Block Headers Service
        • Web App & API
      • Who is it for?
      • Functionality & Roadmap
      • Contribute
      • Developers Guide
        • SPV Wallet
          • Authentication
          • Configuration
          • Notification
        • Go Client
          • Authentication
        • JS Client
          • Authentication
        • Admin
        • Keygen
        • Block Headers Service
          • Authentication
          • Configuration
      • Additional Components
  • paymail
    • Overview
    • BRFC Specifications
      • Specification Documents
      • BRFC ID Assignment
    • Service Discovery
      • Host Discovery
      • Capability Discovery
    • Public Key Infrastructure
    • Payment Addressing
      • Basic Address Resolution
      • Sender Validation
      • Receiver Approvals
      • PayTo Protocol Prefix
    • Verify Public Key Owner
    • Recommendations
  • Guides
    • Local Blockchain Stack
      • Mockchain Stack
    • Business Use Cases
      • Creating a Tranche of Event Tickets
    • SDKs
      • Concepts
        • BEEF
        • Fees
        • SPV
        • Transactions
        • Op Codes
        • Script Templates
        • Signatures
        • Verification
      • TypeScript
        • Node, CommonJS
        • React
        • Low Level
          • Verification
          • ECDH
          • Numbers & Points
          • Signatures
          • 42
          • ECDSA
          • Hmacs
          • Keys
          • Scripts
        • Examples
          • Creating a Simple Transaction
          • Verifying a BEEF Structure
          • Creating Transactions with Inputs, Outputs and Templates
          • Creating the R-puzzle Script Template
          • Message Encryption and Decryption
          • Message Signing
          • Building a Custom Transaction Broadcast Client
          • Verifying Spends with Script Intrepreter
          • BIP32 Key Derivation with HD Wallets
          • Using Type 42 Key Derivation for Bitcoin Wallet Management
          • Creating a Custom Transaction Fee Model
          • Building a Pulse Block Headers Client
          • Using ECIES Encryption
      • Go
        • Examples
          • Simple Tx
          • Keys
          • Encryption
          • Broadcasting
          • Inscribing
          • Data Markers
          • Linked Keys
          • ECIES
          • Fees
          • HD Keys
          • Headers
          • Secure Messages
          • Merkle Path Verification
      • Python
        • Examples
          • Simple Tx
          • Verifying BEEF
          • Complex Tx
          • Script Templates
          • Encryption
          • Message Signing
          • Building A Custom Broadcaster
          • HD Wallets
          • Linked Keys
          • Fees
          • Merkle Path Verification
          • ECIES
  • BSV Academy
    • Getting Started
    • BSV Basics: Protocol and Design
      • Introduction
        • Bit-Coin
      • The BSV Ledger
        • The Ledger
        • Triple Entry Accounting
        • Example
      • Coins and Transactions
        • Coins
        • Transactions
        • Transaction Fees
      • Theory
      • Conclusion
    • BSV Enterprise
      • Introduction
      • About BSV Blockchain
        • Introduction
        • Safe, Instant Transactions at a Predictably Low Cost
          • Reliably Low Fees
          • Comparison to Legacy Transaction Systems
          • Payment Channels
        • Scalability to Accommodate Global Demand
          • Big Blocks Show Big Potential
        • A Plan for Regulatory Acceptance
          • Ready-made Compliance
          • The Open BSV License
        • Protocol Stability
          • Building Foundations on a Bedrock of Stone
      • Technical Details
        • The Network
          • The Small World Network
          • Robust In Its Unstructured Simplicity
        • The Bitcoin SV Node Client
          • Teranode - The Future of BSV
        • The Protocol - Simple, Robust and Unbounded
          • What is the BSV Protocol?
        • Proof of Work
          • The Algorithm
          • Efficiency of Proof of Work
        • Privacy and Identity
        • Permissions and Privacy
      • Resources and Tools
        • The Technical Standards Comittee
          • TSC Principles
          • Standard Development Process
          • Status of Current and In-progress Standards
        • The Working Blockchain
          • Pruning to Create a Working Blockchain
          • Building a Working Blockchain from a List of Block Headers
          • A World View Backed by Proof of Work
    • Hash Functions
      • What are Hash Functions?
        • The Differences Between Hashing and Encryption
        • The Three Important Properties of Hash Functions
        • The Hash Functions Found in BSV
      • Base58 and Base58Check
        • What is Base58 and Why Does Bitcoin use it?
        • What is Base58 and How Does BSV use it?
      • SHA256
        • BSV Transactions and SHA-256
        • BSV Blocks and SHA-256
        • Proof-of-Work and HASH-256
      • Walkthrough Implementation of SHA-256 in Golang
        • Overview of SHA-256
        • SHA-256 Input and Processing
        • SHA-256 Compression
        • SHA-256 Final Value Construction and Output
      • RIPEMD-160
        • BSV Addresses & WIFs
      • Walkthrough Implementation of RIPEMD-160 in Golang
        • Overview of RIPEMD-160
        • RIPEMD-160 Input and Processing
        • RIPEMD-160 Compression
        • RIPEMD-160 Final Value Construction and Output
      • Doubla Hashing and BSV's Security
        • Why is Double Hashing Used in BSV
        • Hash Functions and BSV's Security Model
    • Merkle Trees
      • The Merkle Tree
        • What is a Merkle Tree?
        • Why use a Merkle Tree?
        • Merkle Trees in Action
      • Merkles Trees in BSV
        • The Data Elements
        • Transaction Merkle Trees
        • Transaction Merkle Trees in Action
      • Merkle Trees and the Block Header
        • What is the Block Header
        • The Hash Puzzle
        • Proof-of-Work in Action
      • Merkle trees and Verifying Proof of Work
        • Broadcasting the Block
        • The Coinbase Transaction
        • Data Integrity of the Block
        • Saving Disk Space
      • Standarised Merkle Proof
        • What is a Merkle Proof?
        • The BSV Unified Merkle Path (BUMP) Standard
        • Simple and Composite Proofs
      • Merkle Trees and Simplified Payment Verification
        • SPV
        • Offline Payments
    • Digital Signatures
      • What are Digital Signatures
        • Background
        • Introduction
        • Digital Signatures Protocol
        • Properties of Digital Signatures
      • ECDSA Prerequisites
        • Disclaimer
        • Modular Arithmetic
        • Groups, Rings and Finite Fields
        • Discrete Logarithm Problem
        • Elliptic Curve Cryptography (ECC)
        • Discrete Logarithm Problem with Elliptic Curves
      • ECDSA
        • Introduction
        • ECDSA
        • Further Discussion
      • BSV and Digital Signatures
        • Introduction
        • BSV Transaction
        • ECDSA (secp256k1) for BSV Transaction
        • Summary
        • Signed Messages
        • Miner Identification and Digital Signatures
    • BSV Theory
      • Abstract
        • Peer-to-Peer Cash
        • Digital Signatures and Trusted Third Parties
        • Peer-to-Peer Network
        • Timechain and Proof-of-Work
        • CPU Power
        • Cooperation in the Network
        • Network Structure
        • Messaging Between Nodes
      • Introduction
        • Commerce on the Internet
        • Non Reversible Transactions
        • Privacy in Commerce
        • The Paradigm of Fraud Acceptance
        • What is Needed...
        • Protecting Sellers From Fraud
        • Proposed Solution
        • Security and Honesty
      • Transactions
        • Electronic Coins
        • Spending a Coin
        • Payee Verification
        • Existing Solutions
        • First Seen Rule
        • Broadcasting Transactions
        • Achieving Consensus
        • Proof of Acceptance
      • Timestamp Server
        • Timestamped Hashes
        • A Chain of Timestamped Hashes
      • Proof of Work
        • Hashcash
        • Scanning Random Space
        • Nonce
        • Immutable Work
        • Chain Effort
        • One CPU, One Vote
        • The Majority Decision
        • The Honest Chain
        • Attacking the Longest Chain
        • Controlling the Block Discovery Rate
      • Network
        • Running the Network
        • The Longest Chain
        • Simultaneous Blocks
        • Breaking the Tie
        • Missed Messages
      • Incentive
        • The Coinbase Transaction
        • Coin Distribution
        • Mining Analogy
        • Transaction Fees
        • The End of Inflation
        • Encouraging Honesty
        • The Attacker's Dilemma
      • Reclaiming Disk Space
        • Spent Transactions
        • The Merkle Tree
        • Compacting Blocks
        • Block Headers
      • Simplified Payment Verification
        • Full Network Nodes
        • Merkle Branches
        • Transaction Acceptance
        • Verification During Attack Situations
        • Maintaining an Attack
        • Invalid Block Relay System
        • Businesses Running Nodes
      • Combining and Splitting Value
        • Dynamically Sized Coins
        • Inputs and Outputs
        • A Typical Example
        • Fan Out
      • Privacy
        • Traditional Models
        • Privacy in Bitcoin
        • Public Records
        • Stock Exchange Comparison
        • Key Re-Use
        • Privacy - Assessment 2
        • Linking Inputs
        • Linking the Owner
      • Calculations
        • Attacking the Chain
        • Things the Attacker Cannot Achieve
        • The Only Thing an Attacker Can Achieve
        • The Binomial Random Walk
        • The Gambler's Ruin
        • Exponential Odds
        • Waiting For Confirmation
        • Attack Via Proof of Work
        • Vanishing Probabilities
      • Conclusion
        • Conclusion Explained
    • Introduction to Bitcoin Script
      • Chapter 1: About Bitcoin Script
        • 01 - Introduction
        • 02 - FORTH: A Precursor to Bitcoin Script
        • 03 - From FORTH to Bitcoin Script
        • 04 - Bitcoin's Transaction Protocol
        • 05 - Transaction Breakdown
        • 06 - nLockTime
        • 07 - The Script Evaluator
      • Chapter 2: Basic Script Syntax
        • 01 - Introduction
        • 02 - Rules Around Data and Scripting Grammar
        • 03 - The Stacks
      • Chapter 3: The Opcodes
        • 01 - Introduction
        • 02 - Constant Value and PUSHDATA Opcodes
        • 03 - IF Loops
        • 04 - OP_NOP, OP_VERIFY and its Derivatives
        • 05 - OP_RETURN
        • 06 - Stack Operations
        • 07 - Data transformation
        • 08 - Stack Data Queries
        • 09 - Bitwise transformations and Arithmetic
        • 10 - Cryptographic Functions
        • 11 - Disabled and Removed Opcodes
      • Chapter 4: Simple Scripts
        • 01 - Introduction
        • 01 - Pay to Public Key (P2PK)
        • 02 - Pay to Hash Puzzle
        • 03 - Pay to Public Key Hash (P2PKH)
        • 04 - Pay to MultiSig (P2MS)
        • 05 - Pay to MultiSignature Hash (P2MSH)
        • 06 - R-Puzzles
      • Chapter 5: OP_PUSH_TX
        • 01 - Turing Machines
        • 02 - Elliptic Curve Signatures in Bitcoin
        • 03 - OP_PUSH_TX
        • 04 - Signing and Checking the Pre-Image
        • 05 - nVersion
        • 06 - hashPrevouts
        • 07 - hashSequence
        • 08 - Outpoint
        • 09 - scriptLen and scriptPubKey
        • 10 - value
        • 11 - nSequence
        • 12 - hashOutputs
        • 13 - nLocktime
        • 14 - SIGHASH flags
      • Chapter 6: Conclusion
        • Conclusion
    • BSV Infrastructure
      • The Instructions
        • The Whitepaper
        • Steps to Run the Network
        • Step 1
        • Step 2
        • Step 3
        • Step 4
        • Step 5
        • Step 6
      • Rules and their Enforcement
        • Introduction
        • Consensus Rules
        • Block Consensus Rules
        • Transaction Consensus Rules
        • Script Language Rules
        • Standard Local Policies
      • Transactions, Payment Channels and Mempools
      • Block Assembly
      • The Small World Network
        • The Decentralisation of Power
        • Incentive Driven Behaviour
        • Lightspeed Propagation of Transactions
        • Ensuring Rapid Receipt and Propagation of New Blocks
        • Hardware Developments to Meet User Demand
        • Novel Service Delivery Methods
        • MinerID
      • Conclusion
  • Research and Development
    • BRCs
    • Technical Standards
  • Support & Contribution
    • Join Our Discord
    • GitHub
Powered by GitBook
On this page
  • Generating BIP32 keys
  • Deriving Child Keys
  • Converting Between Formats
  • Hardened vs Non-Hardened Derivation
  • Non-Hardened Derivation
  • Hardened Derivation
  • Summary of Differences
  • Practical Example
  • Real-World Use
  • Disadvantages and Risks

Was this helpful?

Edit on GitHub
Export as PDF
  1. Guides
  2. SDKs
  3. TypeScript
  4. Examples

BIP32 Key Derivation with HD Wallets

PreviousVerifying Spends with Script IntrepreterNextUsing Type 42 Key Derivation for Bitcoin Wallet Management

Last updated 5 months ago

Was this helpful?

For a long time, BIP32 was the standard way to structure a Bitcoin wallet. While has since taken over as the standard approach due to its increased privacy and open-ended invoice numbering scheme, it's sometimes still necessary to interact with legacy systems using BIP32 key derivation.

This guide will show you how to generate keys, derive child keys, and convert them to WIF and Bitcoin address formats. At the end, we'll compare BIP32 to the to key management.

Generating BIP32 keys

You can generate a BIP32 seed with the SDK as follows:

import { HD } from '@bsv/sdk'
const randomKey = HD.fromRandom()

// Convert your "xprv" key to a string
console.log(randomKey.toString())

// Example: xprv9s21ZrQH143K2vF2szsDFhrRehet4iHNCBPWprjymByU9mzN7n687qj3ULQ2YYXdNqFwhVSsKv9W9fM675whM9ATaYrmsLpykQSxMc6RN8V

You can also import an existing key as follows:

const importedKey = HD.fromString('xprv...')

Now that you've generated or imported your key, you're ready to derive child keys.

Deriving Child Keys

BIP32 child keys can be derived from a key using the .derive() method. Here's a full example:

const key = HD.fromString('xprv9s21ZrQH143K2vF2szsDFhrRehet4iHNCBPWprjymByU9mzN7n687qj3ULQ2YYXdNqFwhVSsKv9W9fM675whM9ATaYrmsLpykQSxMc6RN8V')
const child = key.derive('m/0/1/2')
console.log(child.toString())
// 'xprv9yGx5dNDfq8pt1DJ9SFCK3gNFhjrL3kTqEj98oDs6xvfaUAUs3nyvVakQzwHAEMrc6gg1c3iaNCDubUruhX75gNHC7HAnFxHuxeiMVgLEqS'

Any of the standard derivation paths can be passed into the .derive() method.

Converting Between Formats

XPRIV keys can be converted to normal PrivateKey instances, and from there to WIF keys. XPUB keys can be converted to normal PublicKey instances, and from there to Bitcoin addresses. XPRIV keys can also be converted to XPUB keys:

const key = HD.fromString('xprv9s21ZrQH143K2vF2szsDFhrRehet4iHNCBPWprjymByU9mzN7n687qj3ULQ2YYXdNqFwhVSsKv9W9fM675whM9ATaYrmsLpykQSxMc6RN8V')

// Convert XPRIV to XPUB
const xpubKey = key.toPublic()
console.log(xpubKey.toString());
// xpub661MyMwAqRbcFQKVz2QDcqoACjVNUB1DZQK7dF9bKXWT2aKWfKQNfe3XKakZ1EnxeNP5E4MqZnZZw4P7179rPbeJEjhYbwF5ovkbGkeYPdF

// Convert XPRIV to WIF
console.log(key.privKey.toWif())
// L1MZHeu2yMYRpDr45icTvjN7s3bBK1o7NgsRMkcfhzgRjLzewAhZ

// Convert XPUB to public key
console.log(xpubKey.pubKey.toString())
// 022248d79bf217de60fa4afd4c7841e4f957b6459ed9a8c9c01b61e16cd4da3aae

// Convert XPUB to address
console.log(xpubKey.pubKey.toAddress())
// 1CJXwGLb6GMCF46A721VYW59b21kkoRc5D

Hardened vs Non-Hardened Derivation

Child keys are derived in two ways:

  1. Non-Hardened (Normal) Derivation

  2. Hardened Derivation

Both methods are mathematically linked to their parent key, but the hardened keys provide an extra layer of security.

Non-Hardened Derivation

  • Path Notation: m / 0 / 1 / 2

  • Child keys are derived using both the parent public key and chain code.

  • This means only the parent public key (along with the chain code) is required to derive child public keys.

Why Use Non-Hardened Keys?

  • Allows "public key derivation" without exposing the private key.

  • Useful for systems where you want to derive public addresses but do not need access to private keys (e.g., viewing wallets or watch-only wallets).

Key Weakness

If someone compromises a parent private key or the chain code, they can derive child private keys.

Hardened Derivation

  • Path Notation: m / 0' / 1 / 2

    • Hardened keys are indicated by an apostrophe (').

  • Child keys are derived using only the parent private key and chain code.

  • This means the parent public key cannot be used to derive hardened child keys.

Why Use Hardened Keys?

  • Adds security: Even if the parent public key is compromised, the child private keys remain secure.

  • Prevents "public key-based attacks" where an attacker could deduce the private key of a parent by having access to certain information about child keys.

Key Tradeoff

To derive hardened child keys, you must have access to the parent private key (unlike non-hardened keys, which only need the parent public key).

Summary of Differences

Aspect
Non-Hardened
Hardened

Path Notation

m / 0

m / 0'

Derived From

Parent Public Key + Chain Code

Parent Private Key + Chain Code

Public Key Exposure

Can derive child public keys

Cannot derive child public keys

Use Case

Watch-only wallets

Secure child key derivation

Security

Less secure

More secure

Practical Example

  • Master Key: m

    • Derived hardened key: m / 0'

    • Derived non-hardened key: m / 0

If you want to generate child public keys for monitoring transactions (e.g., in a viewing wallet), non-hardened derivation is preferred.

If you need more secure child keys for spending or sensitive applications, hardened derivation is safer because it prevents public key-based compromises.

Real-World Use

In wallets, it's common to use hardened keys for account-level derivation (like m/44'/0'/0') and non-hardened keys for generating specific addresses (m/44'/0'/0'/0/0).

When you hand over an xpub to a counterparty service they will be able to derive non-hardened children of that key only. So it's a way to control who can derive child keys at different levels in your derivation tree. The hardened branch can be anywhere in the derivation path:

If you share the derived xpub at m/0'/3 then anyone with that xpub can go on to derive the pubkey at m/0'/3/1 but if you share the xpub of m only - then only you will be able to derive m/0'/3/1 since the hardened step precludes non-xpriv holders from calculating the children thereafter.

Disadvantages and Risks

This guide has demonstrated how to use BIP32 for key derivation and format conversion. You can continue to use BIP32 within BSV wallet applications, but it's important to consider the disadvantages and risks of continued use, which are discussed below.

BIP32 allows anyone to derive child keys if they know an XPUB. The number of child keys per parent is limited to 2^31, and there's no support for custom invoice numbering schemes that can be used when deriving a child, only a simple integer. Finally, BIP32 has no support for private derivation, where two parties share a common key universe no one else can link to them, even while knowing the master public key. It's for these reasons that we recommend the use of type-42 over BIP32. You can read an equivalent guide .

type-42
type-42 system and encourage you to adopt the new approach
here