Edited at

bitcoinjs-lib v4を使ったhdwalletスニペット


bitcoinjs-lib hdwallet


  • 階層的決定性ウォレット

  • この記事はbitcoinjs-lib@4系です

  • バージョン3系と後方互換性がなくなっています


v3との簡単な違い


  • モジュールの名前空間変更 HDNode -> bip32

  • address取得方法の変更

  • bip32周りのメソッド名の変更


install

npm i bip39 bitcoinjs-lib


mnemonic generate


12 word

const mnemonic = bip39.generateMnemonic();


24 word

const mnemonic = bip39.generateMnemonic(256);


mnemonic to masternode

const mnemonicToM = (mnemonic, password, network) => {

const seed = bip39.mnemonicToSeed(mnemonic, password || "")
const m = bitcoin.bip32.fromSeed(seed, bitcoin.networks[network || "bitcoin"])
return m
}


master extended private key

m.toBase58()


extended private key

m.deriveHardened(44).deriveHardened(0).deriveHardened(0).toBase58()

m.derivePath("m/44'/0'/0'").toBase58()


extended public key

m.deriveHardened(44).deriveHardened(0).deriveHardened(0).neutered().toBase58()

m.derivePath("m/44'/0'/0'").neutered().toBase58()


bitcoin address


address


  • address生成用のラッパーを作ったほうが楽です

const getAddress = (node) => {

return bitcoin.payments.p2pkh({ pubkey: node.publicKey }).address
}
getAddress(m.derivePath("m/44'/0'/0'/0/0"))


private key

m.derivePath("m/44'/0'/0'/0/0").toWIF()


とりあえず実行してみる

const bitcoin = require("bitcoinjs-lib")

const bip39 = require("bip39")

const mnemonicToM = (mnemonic, password, network) => {
const seed = bip39.mnemonicToSeed(mnemonic, password || "")
const m = bitcoin.bip32.fromSeed(seed, bitcoin.networks[network || "bitcoin"])
return m
}

const getAddress = (node) => {
return bitcoin.payments.p2pkh({ pubkey: node.publicKey }).address
}

const mnemonic = bip39.generateMnemonic();
const m = mnemonicToM(mnemonic, '', 'bitcoin')
console.log(mnemonic)
console.log(m.derivePath("m/44'/0'/0'").toBase58())
console.log(m.derivePath("m/44'/0'/0'").neutered().toBase58())
console.log(getAddress(m.derivePath("m/44'/0'/0'/0/0")))