Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active February 17, 2024 05:58
Show Gist options
  • Save sharmaabhinav/68a86a05f2ee7fbf62db1d6ea7b8809f to your computer and use it in GitHub Desktop.
Save sharmaabhinav/68a86a05f2ee7fbf62db1d6ea7b8809f to your computer and use it in GitHub Desktop.
// refer https://medium.com/coinmonks/journey-from-key-to-bitcoin-address-mainnet-and-testnet-variations-edb7c9d69665
const crypto = require('crypto');
const bs58check = require('bs58check')
function generateCompressedPublicKey(x, y) {
// Convert x and y from hexadecimal to BigInt
const xBigInt = BigInt('0x' + x);
const yBigInt = BigInt('0x' + y);
console.log(2n)
// Determine the prefix byte based on the parity of y
const prefixByte = (yBigInt % 2n === 0n) ? '02' : '03';
// Concatenate prefix byte with x and convert to hexadecimal
const compressedPublicKey = prefixByte + x + y;
return compressedPublicKey;
}
const hashPublicKey = (publicKey) => {
const sha256Hash = crypto.createHash('sha256').update(publicKey).digest();
return crypto.createHash('ripemd160').update(sha256Hash).digest();
};
const createBitcoinAddress = (hashedPublicKey, networkByte = 0x00) => {
const versionBuffer = Buffer.alloc(1, networkByte);
const payload = Buffer.concat([versionBuffer, hashedPublicKey]);
return bs58check.encode(payload);
};
const x = "720153d8a6a7c325f771ae6b193074dddfe6f5f6deab446ab29ea809ba49daa"; // This is from web3auth keydetails method x and y
const y = "2395fdfe4f84cda4adc12dca0dbdfb211829dfbea124d0dbe2359563ad64b053";
const compressedPublicKey = generateCompressedPublicKey(x, y);
const hashedPublicKey = hashPublicKey(compressedPublicKey)
const bitcoinAddressMainnet = createBitcoinAddress(hashedPublicKey, 0x00);
const bitcoinAddressTestnet = createBitcoinAddress(hashedPublicKey, 0x6f);
// one address generated --> muPKj3i7ufN2y6yc9powvp8qMP5KtAroWY ([email protected])
// for balance check https://live.blockcypher.com/btc-testnet/address/muPKj3i7ufN2y6yc9powvp8qMP5KtAroWY/
// second address generated --> mxnaP6VfN7P5HZKHJARvCCLf2FpukzaVeb ([email protected])
// for balance https://live.blockcypher.com/btc-testnet/address/mxnaP6VfN7P5HZKHJARvCCLf2FpukzaVeb/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment