Skip to content

Instantly share code, notes, and snippets.

@ivanminutillo
Last active September 29, 2016 10:46
Show Gist options
  • Select an option

  • Save ivanminutillo/6394584d379cad84586c776c8676258e to your computer and use it in GitHub Desktop.

Select an option

Save ivanminutillo/6394584d379cad84586c776c8676258e to your computer and use it in GitHub Desktop.
Function that return the xpub or a xprv of a given HDNode, (using the bitcoinjs-lib) heavily based on the method .toBase58()
let HDtoBase58 = function (HDNode, key) {
var network = HDNode.keyPair.network
if(key === 'xpub') {
var buffer = new Buffer(78)
buffer.writeUInt32BE(network.bip32.public, 0)
buffer.writeUInt8(HDNode.depth, 4)
buffer.writeUInt32BE(HDNode.parentFingerprint, 5)
buffer.writeUInt32BE(HDNode.index, 9)
HDNode.chainCode.copy(buffer, 13)
HDNode.keyPair.getPublicKeyBuffer().copy(buffer, 45)
//return the encoded pubkey
return bs58check.encode(buffer)
}
else if (key === 'xprv') {
var buffer = new Buffer(78)
buffer.writeUInt32BE(network.bip32.private, 0)
buffer.writeUInt8(HDNode.depth, 4)
buffer.writeUInt32BE(HDNode.parentFingerprint, 5)
buffer.writeUInt32BE(HDNode.index, 9)
HDNode.chainCode.copy(buffer, 13)
buffer.writeUInt8(0, 45)
HDNode.keyPair.d.toBuffer(32).copy(buffer, 46)
//Return the encoded xprv Key
return bs58check.encode(buffer)
}
else {
'Second argoument not accepted : [xprv or xpub]'
}
}
// To test the function
//let hdNode = bitcoin.HDNode.fromSeedHex(yourSeedinHexadecimal)
//console.log(HDtoBase58(hdNode, 'xprv')
//console.log(HDtoBase58(hdNode, 'xpub')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment