Skip to content

使用 bitcoinjs-lib 创建 HD 钱包

HD 钱包(Hierarchical Deterministic Wallet)是一种特殊类型的比特币钱包,它使用一种树状结构来生成地址。HD 钱包的算法决定了只要给定根扩展私钥,整棵树的任意节点的扩展私钥都可以计算出来。

安装 bitcoinjs-lib

bash
npm install bitcoinjs-lib --save

使用bitconjs-lib注意事项

当你导入 bitcoinjs-lib 时,它不带有捆绑的 ECC 库。相反,你需要使用 initEccLib() 方法将 ECC 库实例提供给 bitcoinjs-lib。 在浏览器端使用时推荐使用@bitcoin-js/tiny-secp256k1-asmjs包,避免wasm加载失败。

js
import * as bitcoin from 'bitcoinjs-lib';
import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs';
bitcoin.initEccLib(ecc);

生成 HD 钱包

js
import * as bitcoin from 'bitcoinjs-lib';

// 生成根私钥
const rootPrivateKey = bitcoin.ECPair.makeRandom().privateKey;

// 生成 HD 钱包
const hdWallet = bitcoin.HDWallet.fromPrivateKey(rootPrivateKey);

// 生成地址
const address = hdWallet.getAddress(0); // 生成第一个地址

console.log(address.toString()); // 输出地址

BIP44

BIP44 是一种标准的 HD 钱包格式,它定义了一种树状结构来生成地址。BIP44 的格式如下:

m / purpose' / coin_type' / account' / change / address_index

其中,purpose 固定是 44,代表使用 BIP44。coin_type 用来表示不同币种,例如 BTC 是 0,BTC 测试网是 1,ETH 是 60,ETC 是 61。account 表示账户,change 表示是否是外部链,address_index 表示地址索引。

生成 BIP44 格式的 HD 钱包

js
import * as bitcoin from 'bitcoinjs-lib';

// 生成根私钥
const rootPrivateKey = bitcoin.ECPair.makeRandom().privateKey;

// 生成 BIP44 格式的 HD 钱包
const bip44Wallet = bitcoin.HDWallet.fromPrivateKey(rootPrivateKey, {
  purpose: 44,
  coinType: 0, // BTC
  account: 0,
  change: 0,
  addressIndex: 0
});

// 生成地址
const address = bip44Wallet.getAddress(0); // 生成第一个地址

console.log(address.toString()); // 输出地址