How to send & receive bitcoin using bitcoinjs-lib?

2.7k Views Asked by At

First I create HD Wallet using BIP32 using mnemonics.

Now I want to generate new child addresses with private key using xpub & xpriv for every receive.

Then, for example, I received BTC in 2 child addresses, i.e. 3 BTC & 2 BTC.

Now, I have to send 4 BTC to someone, then How can I send it as I have 3 BTC but in a separate account with utxo.

How can I manage these accounts & transactions, and also how can I show the total balance to the user?

So, I don't know how to implement this using bitcoinjs-lib, BIP32.

1

There are 1 best solutions below

2
On

To create 2 addresses, for example:

const path = "m/0'/0/0"
const mnemonic = 'praise you muffin lion enable neck grocery crumble super myself license ghost'
const seed = bip39.mnemonicToSeed(mnemonic)
const root = bip32.fromSeed(seed)

const child1 = root.derivePath("m/0'/0")
const child2 = root.derivePath("m/0'/1")

const child1Address = bitcoin.payments.p2pkh({ pubkey: child1.publicKey }).address
const child2Address = bitcoin.payments.p2pkh({ pubkey: child2.publicKey }).address

Next, in order to manage these accounts, and show a balance to the user, you must create a database of every transaction that occurs using their addresses. This means you must scan every block for any transactions that use their address and keep track of whether that transaction is spent, much like building a block explorer. Bitcoinjs-lib doesn't do this for you, it provides the primitive building blocks for you to create your own wallet application.

In order to spend outputs from both addresses, you must get the unspent outputs from your database, and create the transaction and sign using the keys you created. See README for more examples.