bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.62k stars 2.09k forks source link

How to generate address, public key, and private key #1203

Closed Eithcowich closed 5 years ago

Eithcowich commented 5 years ago

I need to create accounts for users. Looking at bitcoinjs-lib examples I came up with this code:

function rng () {
  return Buffer.from('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz')
} // get a much more secure random

const keyPair = bitcoin.ECPair.makeRandom({ rng: rng })
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey })
console.log("address " + address) // 17wqX8P6kz6DrDRQfdJ9KeqUTRmgh1NzSk
var publicKey = keyPair.publicKey.toString('hex')

console.log("public key " + publicKey) // 0279bf075bae171835513be1056f224f94f3915f9999a3faea1194d97b54397219

var wif = keyPair.toWIF()
console.log("private key WIF " + wif) // 200424e3612358db9078760d4f652a105049187c29f2d03d7d65bc9e27a007d0

My questions are:

  1. Bitcoin private keys seem to start with 5. The ones I generate with this code does not. Do I need to convert it? Or get it in another way?
  2. In general is this the right way to use bitcoinjs-lib?
dcousens commented 5 years ago

@Eithcowich I don't get the same results as you.

address 1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64
public key 03e05ce435e462ec503143305feb6c00e06a3ad52fbf939e85c65f3a765bb7baac
private key WIF L1Knwj9W3qK3qMKdTvmg3VfzUs3ij2LETTFhxza9LfD5dngnoLG1
Eithcowich commented 5 years ago

@dcousens Yes, the results I have in the question are from

const keyPair = bitcoin.ECPair.makeRandom();

Without the seed. When I use the zzzz... seed I get the same results you get.

But regardless, the privake key still doesn't start with a 5, and also seem to have one extra character.

dcousens commented 5 years ago

What does the private key start with?

Eithcowich commented 5 years ago

Just like in your comment above,

address 1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64
public key 03e05ce435e462ec503143305feb6c00e06a3ad52fbf939e85c65f3a765bb7baac
private key L1Knwj9W3qK3qMKdTvmg3VfzUs3ij2LETTFhxza9LfD5dngnoLG1

So the private key starts with L1Knwj

dabura667 commented 5 years ago

L and K are compressed keys.

5 is uncompressed, meaning higher fees.

you can also get lower fees by using segwit.