Skip to content

Instantly share code, notes, and snippets.

@mixdev
Created June 6, 2017 14:30
Show Gist options
  • Save mixdev/0b3862ccd198a9598ebffe00befa3b1d to your computer and use it in GitHub Desktop.
Save mixdev/0b3862ccd198a9598ebffe00befa3b1d to your computer and use it in GitHub Desktop.
How to recreate a Bitcoin wallet address from a public key
/*
How to recreate a Bitcoin wallet address from a public key
Ref: https://github.com/bitcoinjs/bitcoinjs-lib/issues/590
*/
var bitcoin = require('bitcoinjs-lib')
var assert = require('assert')
var bigi = require('bigi')
var crypto = require('crypto')
/* New hash */
var hash = bitcoin.crypto.sha256('correct horse battery staple')
var d = bigi.fromBuffer(hash)
/* Create a new Eleptic Curve key pair from hash */
var keyPair = new bitcoin.ECPair(d)
/* Extract public key buffer(compressed) */
var publicKeyBuffer = keyPair.getPublicKeyBuffer()
/* Copy the (compressed) pub key from the ECPair we have created above */
var publicKey = bitcoin.ECPair.fromPublicKeyBuffer(publicKeyBuffer)
/* Create a new keypair from the copied public key */
var newKeyPair = new bitcoin.ECPair(null, publicKey.Q, { compressed: true })
/* The old address */
console.log(keyPair.getAddress())
/* should be same as the new address */
console.log(newKeyPair.getAddress())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment