Skip to content

Instantly share code, notes, and snippets.

@Anderson-Juhasc
Created February 23, 2023 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anderson-Juhasc/7b67a021e0dcf70a18e22d2944164530 to your computer and use it in GitHub Desktop.
Save Anderson-Juhasc/7b67a021e0dcf70a18e22d2944164530 to your computer and use it in GitHub Desktop.
bitcoinjs-lib and Elliptic.js to generate a bech32 address
const bitcoin = require('bitcoinjs-lib');
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
// Generate a random private key
const privateKey = ec.genKeyPair().getPrivate('hex');
// Convert the private key to a BitcoinJS keypair
const keyPair = bitcoin.ECPair.fromPrivateKey(Buffer.from(privateKey, 'hex'));
// Get the public key and convert it to a bech32 address
const publicKey = keyPair.publicKey;
const publicKeyHash = bitcoin.crypto.hash160(publicKey);
const address = bitcoin.payments.p2wpkh({ pubkey: publicKey, hash: publicKeyHash }).address;
console.log('Private key: ', privateKey);
console.log('Bech32 address: ', address);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment