Working with Bitcoin Mnemonics in JavaScript


When you are want to generate Bitcoin addresses for your users, you are really creating a public-private key pair. To operate in a trustless manner as advocated for the blockchain, it is best if you do all wrangling within the user browser, taking only the public key to the server.

The way to do it is to use bitcore-lib together with bitcore-mnemonic.

Create a Key Pair

var Mnemonic = require('bitcore-mnemonic');
var bitcore = require('bitcore-lib');

Generate a new mnemonic:

var code = new Mnemonic(Mnemonic.Words.ENGLISH);
var mnemonic = code.toString();
var data = codeToDetails(code);

Get the public and private keys:

function codeToDetails(code) {
  var xpriv = code.toHDPrivateKey(bitcore.Networks.livenet);
  var derived = xpriv.derive("m/0'");
  var privateKey = derived.privateKey;
  var pk = new bitcore.PrivateKey(privateKey.toString(), bitcore.Networks.livenet);

  var privateKeyStr = pk.toString();
  var publicKey = new bitcore.PublicKey(pk);
  var publicKeyStr = publicKey.toString();
  var address = new bitcore.Address(publicKey, bitcore.Networks.testnet);
  return {
    privateKeyStr: privateKeyStr,
    publicKeyStr: publicKeyStr

Pay to the User

Now you want to pay the user. For this you want to create a raw transaction in your server, sign it, and broadcasts it. So you need the user private key.

We use the same function codeToDetails from above, given the seed phrase provided by the user.

First, we check if it is a valid mnemonic,

var valid = Mnemonic.isValid(seed);

And if it is valid,

var code = new Mnemonic(seed);
var data = codeToDetails(code);
var pk = new bitcore.PrivateKey(data.privateKeyStr, bitcore.Networks.livenet);
var wif =  pk.toWIF();

We need the WIF format to create the raw transaction.

Yoram Kornatzky

Yoram Kornatzky