Skip to content

Instantly share code, notes, and snippets.

@dakk
Last active March 26, 2018 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakk/4c448bdc052dfa7e8f83b92f89a00096 to your computer and use it in GitHub Desktop.
Save dakk/4c448bdc052dfa7e8f83b92f89a00096 to your computer and use it in GitHub Desktop.
Mastering Bitcoin - Chapter 4
// First install bitcoinjs-lib and bip39 in the current working directory
// npm install bitcoinjs-lib bip39
const bitcoin = require ('bitcoinjs-lib');
const bip39 = require ('bip39');
/// Generate a random keypair and display private and public key and the address (compressed by default)
let keypair = bitcoin.ECPair.makeRandom ();
console.log ('Address:', keypair.getAddress());
console.log ('Public key:', keypair.getPublicKeyBuffer().toString('hex'));
console.log ('Private key in wif format:', keypair.toWIF());
/// Generate a random deterministic wallet (bip39) and get the HD
let mnemonic = bip39.generateMnemonic ();
let seed = bip39.mnemonicToSeed (mnemonic);
console.log ('Mnemonic:', mnemonic);
console.log ('Seed:', seed.toString('hex'));
let hd = bitcoin.HDNode.fromSeedBuffer(seed, bitcoin.networks.bitcoin);
let keypair2 = hd.keyPair;
console.log ('First wallet of the hd:', keypair2);
console.log ('The first grandchild private key of the second child (m/1)', hd.derivePath ('m/1/0').keyPair);
console.log ('The first normal grandchild of the first hardened child (m/0')', hd.derivePath ('m/0\'/0').keyPair);
/// Generate a vanity address
let toFind = 'cat';
let keypair3 = bitcoin.ECPair.makeRandom ();
let n = 0;
while (keypair3.getAddress().substring (1, toFind.length + 1).toLowerCase() != toFind) {
keypair3 = bitcoin.ECPair.makeRandom ();
n += 1;
console.log (n, '->', keypair3.getAddress(), keypair3.getAddress().substring (1, toFind.length + 1).toLowerCase());
}
console.log ('Found vanity address:', keypair3.getAddress(), '( wif:', keypair3.toWIF(),')')
// Found vanity address: 1Cat2Jjrcj3XvcWLZpPKF8MsUnAF9wgVYM ( wif: L5KtrHJQy3Rh74dfdgWT62mcwbxnUg4rjBsZ2WD5ziAZYMUthBnC )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment