bitcoinjs / bitcoinjs-lib

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

Generating testnet address compatible with Electrum #1662

Closed thegrandpoobah closed 3 years ago

thegrandpoobah commented 3 years ago

I'm trying to generate addresses that match up with the addresses that are in my Electrum wallet. This is the code I've written:

  getWalletAddress(chainNumber = 0): string {
    const btcNetwork = this.configService.get('BTC_NETWORK');
    let network = networks.bitcoin;
    if (btcNetwork === 'testnet') {
      network = networks.testnet;
    }

    const root = bip32.fromBase58(
      this.configService.get('BTC_PUBLIC_KEY'),
      network,
    );
    const child = root.derivePath(`m/0/${chainNumber}`);
    const { address } = payments.p2pkh({ pubkey: child.publicKey });

    return address;
  }

This code works fine when I'm creating mainnet addresses, but when I put in my testnet public key in the config, it generates addresses different than what Electrum created. I used the following value for BTC_PUBLIC_KEY: tpubD6NzVbkrYhZ4YSeta433ubKfJ1CmKyw5wdTnWot7NCn4xhAEAf1aKgbFor8BegsuyHd368gXP5PFwUbV581C1xRYVTbFPmmwSQ1o6KvSrpu.

For example, for chainNumber=0, and the public key above, this returns 1A45fGYj6377oFfLqBqSnR9A2GLSBVdBPK which I understand to be a mainnet address, but the wallet in Electrum says the address should be msmV9362Lxw5UREC2VvvJQ6qrMzuBG64cq.

Before anybody asks, I've verified that network = bitcoin.networks.testnet when running my tests.

What am I doing wrong? :)

junderw commented 3 years ago

you need to pass network to p2pkh

thegrandpoobah commented 3 years ago

thank you! that fixed it.