moneybutton / bsv

Bitcoin SV javascript library
Other
204 stars 107 forks source link

How to get address and private key from a mnemonic? #140

Closed soulmachine closed 4 years ago

soulmachine commented 4 years ago

Basically I need a function as the following:

export function getBSVAddress(mnemonic: string): { address: string; privateKey: string } {
  return { address: 'xxx', privateKey: 'yyy' };
}

I've done similar things with other coins such as BTC, BCH, EOS, ETH quite smoothly, but I'm having a hard time with this library, any suggestions?

calvogenerico commented 4 years ago

Hi! You can find information here:

https://docs.moneybutton.com/docs/bsv-mnemonic.html https://docs.moneybutton.com/docs/bsv-hd-private-key.html https://docs.moneybutton.com/docs/bsv-hd-public-key.html

You need to include bsv and bsv/mnemonic. And then you can derive keys and create addreses:

const mnemonic = new bsv.Mnemonic()
const hdPrivKey = bsv.HDPrivKey.fromSeed(mnemonic.toSeed())
const someKey = hdPrivateKey.deriveChild("m/5/2/8") // Private key
const somePubkey = someKey.publicKey
const address = somePubKey.toAddress()

I did this from my memory, so there might be some mistake, but in those docs I sent there are details about this.

calvogenerico commented 4 years ago

I closed the thread by mistake. Feel free to close if the question was answered.

soulmachine commented 4 years ago

Finally make it work:

// import * as bip39 from 'bip39';
import * as bip39 from 'bip39';
import bsv from 'bsv';

// eslint-disable-next-line import/prefer-default-export
export function getBSVAddressFromMnemonic(
  mnemonic: string,
): { address: string; privateKey: string } {
  const seed = bip39.mnemonicToSeedSync(mnemonic);
  // const seed = Mnemonic.fromString(mnemonic).toSeed(); // TypeError: Cannot read property 'fromString' of undefined
  const hdPrivateKey = bsv.HDPrivateKey.fromSeed(seed, bsv.Networks.mainnet);

  const child = hdPrivateKey.deriveChild("m/44'/236'/0'/0/0");

  const address = child.publicKey.toAddress(bsv.Networks.mainnet);

  return { address: address.toString(), privateKey: child.privateKey.toWIF() };
}
mathiasrw commented 4 years ago

@soulmachine Why the 236 in hdPrivateKey.deriveChild("m/44'/236'/0'/0/0"); ?

soulmachine commented 4 years ago

@mathiasrw According to this SLIP-0044 : Registered coin types for BIP-0044, BSV standard path is m/44'/236'/0'/0/0