dlystyr

Bitcoin Address Creation - Node.JS

Nov 22nd, 2017
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const crypto = require('crypto');
  2. const EC = require('elliptic').ec;
  3. const RIPEMD160 = require('ripemd160');
  4. const bs58 = require('bs58');
  5. const buffer = require('buffer');
  6. const ec = new EC('secp256k1');
  7.  
  8. function hasha256(data) {
  9.     return crypto.createHash('sha256').update(data).digest();
  10. } // A small function I created as there is a lot of sha256 hashing.
  11.  
  12. const addrVer = Buffer.alloc(1, 0x00); // 0x00 P2PKH Mainnet, 0x6f P2PKH Testnet
  13. const wifByte = Buffer.alloc(1, 0x80); // 0x80 Mainnet, 0xEF Testnet
  14.  
  15. var key = ec.genKeyPair();
  16. var privKey = key.getPrivate().toString('hex');
  17. var pubPoint = key.getPublic();
  18. var x = pubPoint.getX(); // elliptic x
  19. var y = pubPoint.getY(); // elliptic y
  20.  
  21. // Private Key Hashing
  22. var bufPrivKey = Buffer.from(privKey, 'hex');
  23. var wifBufPriv = Buffer.concat([wifByte, bufPrivKey], wifByte.length + bufPrivKey.length);
  24. var wifHashFirst = hasha256(wifBufPriv);
  25. var wifHashSecond = hasha256(wifHashFirst);
  26. var wifHashSig = wifHashSecond.slice(0, 4);
  27. var wifBuf = Buffer.concat([wifBufPriv, wifHashSig], wifBufPriv.length + wifHashSig.length);
  28. var wifFinal = bs58.encode(wifBuf);
  29.  
  30. // Public Key Hashing
  31. var publicKey = pubPoint.encode('hex');
  32. var publicKeyInitialHash = hasha256(Buffer.from(publicKey, 'hex'));
  33. var publicKeyRIPEHash = new RIPEMD160().update(Buffer.from(publicKeyInitialHash, 'hex')).digest('hex');
  34. var hashBuffer = Buffer.from(publicKeyRIPEHash, 'hex');
  35. var concatHash = Buffer.concat([addrVer, hashBuffer], addrVer.length + hashBuffer.length);
  36. var hashExtRipe = hasha256(concatHash);
  37. var hashExtRipe2 = hasha256(hashExtRipe);
  38. var hashSig = hashExtRipe2.slice(0, 4);
  39. var bitcoinBinaryStr = Buffer.concat([concatHash, hashSig], concatHash.length + hashSig.length);
  40.  
  41. var bitcoinWifAddress = wifFinal.toString('hex');
  42. var bitcoinAddress = bs58.encode(Buffer.from(bitcoinBinaryStr));
  43.  
  44. // Log our new Bitcoin Address and WIF
  45. console.log("WIF Private Key : %s", bitcoinWifAddress.toString('hex'));
  46. console.log("Bitcoin Address : %s", bitcoinAddress.toString('hex'));
Advertisement
Add Comment
Please, Sign In to add comment