Skip to content

Instantly share code, notes, and snippets.

@rllola
Last active November 5, 2024 11:49
Show Gist options
  • Save rllola/d7a89edc2e4a76a4f189f1f95c505ca4 to your computer and use it in GitHub Desktop.
Save rllola/d7a89edc2e4a76a4f189f1f95c505ca4 to your computer and use it in GitHub Desktop.
Tutorials

How to get a bitcoin address from a public key

With Bitcoin one public key can give two different addresses. It will depend if the public key has been hashed first or not.

const bs58check = require('bs58check')
const RIPEMD160 = require('ripemd160')
const crypto = require('crypto')

function hashing (buf) {
  let hash = crypto.createHash('sha256').update(buf).digest()
  hash = new RIPEMD160().update(hash).digest()
  return hash
}

function pubkeyToPubkeyHash (pubkey) {
  return hashing(pubkey)
}

function pubkeyToAddress (pubkey, hash = false) {
  let pubKeyHash = pubkey

  if (!hash) {
    pubKeyHash = pubkeyToPubkeyHash(pubkey)
  }

  networkByte = Buffer.from("6f", 'hex') // '6f' is for regtest and testnet '00' is for mainnet

  const temp = Buffer.concat([networkByte, pubKeyHash])

  return bs58check.encode(temp)

Run a Bitcoin node in regtest mode

Docker run

Using -regtest=1 allow to run the bitcoin node in regtest node. You will have control over the block generation.

$ docker run --name bitcoind -p 18443 -it --rm bitcoin/bitcoin -printtoconsole -regtest=1 -rpcauth='skull:c0a56202ffaaffab2b4c5377ef0c8f9c$07b5ace63d47469c430ecaba1c7a645b20e5d699fe6fde78967c22bdb35c31ee'

Create a wallet

$ docker exec bitcoind bitcoin-cli -regtest -rpcuser=skull -rpcpassword=minitel createwallet "skull"

Generate blocks

In other terminal you cna run command to generate blocks or send tBTC to addresses. You will have to generate some blocks to be able to spend the first tBTC that has been rewarded to you (150 blocks is safe).

$ docker exec bitcoind bitcoin-cli -regtest -rpcuser=skull -rpcpassword=minitel -generate 150 

Get balance

$ docker exec bitcoind bitcoin-cli -regtest -rpcuser=skull -rpcpassword=minitel getbalance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment