Bitcoinjs-lib: Derive Addresses from xpub key

Created on 29 May 2016  路  4Comments  路  Source: bitcoinjs/bitcoinjs-lib

Dear all, sry to ask this question here... However, I am not able to figure out how to use the API and derive addresses from a xpub key only.

The same functionality is available in bitcore-lib e.g. (https://github.com/bitpay/bitcore-lib/blob/master/test/hdpublickey.js#L189)

Can anybody give me an example, how this works with? In a way like: var address1 = hdnode.derive(1234). _The question is how to configure hdnode with the respective xpub key._

how to / question / docs

Most helpful comment

You basically already had it.

var node = HDNode.fromBase58(xpub)
var address = node.derive(0).getAddress()

If you want to guarantee that it is only using the public version derivation, use .neutered(). However, for an address, it is always going to be public so this really only impacts node.

var node = HDNode.fromBase58(xpub).neutered()
var address = node.derive(0).getAddress()

All 4 comments

You basically already had it.

var node = HDNode.fromBase58(xpub)
var address = node.derive(0).getAddress()

If you want to guarantee that it is only using the public version derivation, use .neutered(). However, for an address, it is always going to be public so this really only impacts node.

var node = HDNode.fromBase58(xpub).neutered()
var address = node.derive(0).getAddress()

Works great! Thank you!

Excellent! Let us know if we could improve the examples at all :+1:

I would love to see how to generate a SegWit address using the xpub key as well. Also, am I correct in thinking that by only using the xpub key, even if someone gained access to my server, they'd never be able to steal the bitcoin because all they have is the public key, correct?

Actually after a quick attempt, that was pretty easy!

let node = HDNode.fromBase58( "xpub key" );
console.log( "normal address", node.derive(0).getAddress() );

let script_pub_key = script.witnessPubKeyHash.output.encode( crypto.hash160(node.getPublicKeyBuffer() ) );
let segwit_address = address.fromOutputScript( script_pub_key );
console.log( "segwit address", segwit_address );
Was this page helpful?
0 / 5 - 0 ratings

Related issues

coingeek picture coingeek  路  4Comments

panpan2 picture panpan2  路  3Comments

ishwarchandratiwari picture ishwarchandratiwari  路  3Comments

namnv04 picture namnv04  路  3Comments

dakk picture dakk  路  3Comments