bitcoinjs / bitcoinjs-lib

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

Generating child public keys out of an extended pub key #1525

Closed yuradmt closed 4 years ago

yuradmt commented 4 years ago

I'm using this code

const ypub = 'tpubDCoXW1puhTARDmuk8UXieCYPuVR6GpY7yHLEMoKM1iXfMui8crafMFUbKA6QtjT6RZkajE4nXBNCTNp98rMZQfjdqxLEZrzbmUPY6zAFviU';
const network = bitcoin.networks.testnet;

let data = b58.decode(ypub);
data = data.slice(4);
data = Buffer.concat([Buffer.from('043587cf', 'hex'), data]);
const xpub = b58.encode(data);

const p2wpkh = bitcoin.payments.p2wpkh({ pubkey: bitcoin.bip32.fromBase58(xpub, network).derive(0).derive(0).publicKey, network });
const payment = bitcoin.payments.p2sh({ redeem: p2wpkh, network });
const addressString = payment.address;

to generate child public keys from an ypub (BIP 49) and zpub (BIP84) extended public keys. It works great.

Now I want to generate these child public keys for a different (non-zero) account, i.e. to derive a public key for m'/49'/1'/1'/0/0 instead of m/49'/1'/0'/0/0 and so on. How would I go about that? The reason is that wallets have multiple accounts, and they expose an extended public key for each of these accounts. I want to derive addresses for all the accounts, not just for 0.

junderw commented 4 years ago

derivePath with the path string should work.

check the tests for examples of bip32 derivation.