2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-02-26

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")))
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?