Bitcoinjs-lib: Add example for storing, deserializing HDNodes

Created on 21 Jun 2017  路  3Comments  路  Source: bitcoinjs/bitcoinjs-lib

I have two questions to ask you wise men that I feel would be useful to future generations.

I'm creating what is, for all intents and purposes, a web merchant, and following the BIP44 design of an HD wallet structure. Currently, I keep a separate server to handle bitcoin logic (and keys). The web application server talks to the btc server to request new addresses to receive payments, and to make requests for refunds.

First issue, what is the correct way to store an HDNode? Should I store it in a db in some canonical serialized format? Should I store the original mnemonic seed and rebuild all nodes as needed? The latter is easily done by following your examples. Ideally, I would want to store the top level key(s) offline, so as not to expose the entire wallet to this server.

Which brings me to...

Second issue, is there a way to initialize, possibly deserialize, a 'downstream' HDNode (let's say path "m/44'/0'/0") without building out the higher-up pairs in the tree. It is my understanding that BIP32 is designed for this, and I have a layman's understanding of the raw derivation, but I am unsure how to get there with bitcoinjs-lib.

If I can initialize such a lowly HDNode, hd_low, I assume hd_low.derive(index) is the right way.

Thanks, gentlemen.

how to / question / docs

Most helpful comment

Yes, this works out great.

var bitcoin = require('bitcoinjs-lib')
var assert = require('assert')

var seed = ...
var node = bitcoin.HDNode.fromSeedBuffer(seed)
var address1 = node.getAddress()

var backup = node.toBase58()
var restored = bitcoin.HDNode.fromBase58(backup, bitcoin.networks.bitcoin)

var address2 = restored.getAddress()

assert.strictEqual(address1, address2)

Problem solved!

All 3 comments

HDNode.prototype.toBase58?

Don't want the xpriv? Only xpub?
hdnode.neutered().toBase58()

If that is the answer, I'll re-tag this as "add an example for BIP32 serialization"

Yes, this works out great.

var bitcoin = require('bitcoinjs-lib')
var assert = require('assert')

var seed = ...
var node = bitcoin.HDNode.fromSeedBuffer(seed)
var address1 = node.getAddress()

var backup = node.toBase58()
var restored = bitcoin.HDNode.fromBase58(backup, bitcoin.networks.bitcoin)

var address2 = restored.getAddress()

assert.strictEqual(address1, address2)

Problem solved!

See #844

Was this page helpful?
0 / 5 - 0 ratings

Related issues

prahaladbelavadi picture prahaladbelavadi  路  3Comments

zhaozhiming picture zhaozhiming  路  3Comments

askucher picture askucher  路  3Comments

itsMikeLowrey picture itsMikeLowrey  路  3Comments

tuyennvtb picture tuyennvtb  路  3Comments