Created
February 23, 2023 19:31
-
-
Save Anderson-Juhasc/7b67a021e0dcf70a18e22d2944164530 to your computer and use it in GitHub Desktop.
bitcoinjs-lib and Elliptic.js to generate a bech32 address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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