sipa / bech32

Code snippets and analysis of the Bech32 format
191 stars 107 forks source link

P2PKH to bech32 #72

Closed random9brat closed 2 years ago

random9brat commented 2 years ago

Sry if this is a dumb questions. But as title says.

I have for example 1LKp8CTu2b4VDvybY9iMn3DoV1cm6ZLsrR address created from bitcoinjs-lib/coinjs-lib/bip39 and i want to convert it to bech32?

How can i do it? Thanks for the responses in advance <3

sipa commented 2 years ago

You don't ever want to convert an address from one type to another.

As the sender, the address you were given is where the receiver expects the payment to go. Changing it to another type, however well intended, can break that expectation. The receiver may not support the new type you turned it into, may just not recognize it as a valid payment, or may even be incapable of accessing the sent funds at all.

As the receiver, it is your own software that constructed the address. If you want to use a more modern address type, you should upgrade/switch wallet software that supports this new address type. Because just converting an address is not enough - your wallet also needs to be ready to deal with it.

random9brat commented 2 years ago

Hey Sipa, thanks for replay, means a lot since im learning to develop within btc space. I kinda understand the answer, i guess i will need native bech32 output rather than converting it. Is there any chance of helping me create bech32 output public address within this code? Im gtting P2PKH which is not compatible (from what i learn) within a lot softwware wallets etc. Mnemonic words are good, private key is good from derivation path, but im getting 1..... instead bc1....

Thanks a lot again.

var bip39 = require('bip39')
var crypto = require('crypto')
var bitcoin = require('bitcoinjs-lib')
const coinjs = require('coinjs-lib')
const bech32 = require("bech32")

var  randomBytes = crypto.randomBytes(16)
var mnemonic = bip39.entropyToMnemonic(randomBytes.toString('hex')) 

const seed = coinjs.bip39.mnemonicToSeed(mnemonic);
const rootNode = coinjs.HDNode.fromSeedBuffer(seed);
const btcchild = rootNode.derivePath(`m/84'/0'/0'/0/0`); 

// get public addresses
const btcaddress = btcchild.getAddress();

// get private key
const btcprivkey = btcchild.getPrivateKey();
sipa commented 2 years ago

@random9brat You'll need to figure out how to make the library/framework you're using to construct bech32 addresses. You cannot generally just convert one address into another. I'm unfamiliar with the software you're using here.

random9brat commented 2 years ago

Will listen to your advice. Thanks again for the replays.