In last blog post we had seen how bitcoin wallet is generated. In this blog post we will see how we can generate bitcoin wallet using javascript.

I'll list few code snippets here, link to full code is given at the end of post.

This blog post is for learning purposes, the code used here is not fit for production systems or generating new addresses, USE AT YOUR OWN RISK

Libraries used: CryptoJS library from Jeff Mott,
BigInteger and Elliptic Curve implementation javascript libraries by Tom Wu.

Code snippet below fetches random data fetchEntropy function to create a private key & then generates bitcoin address formatAddress function.

    function(num) {
		var url = this.URL.concat(num);
		var objArray = [];
		var that = this;
 		return this.fetchEntropy(url).then(function(keyArray) {
				objArray = keyArray.map(function(key) {
				return that.formatAddress(key);
			});
			return objArray;		
		}); 
		
	}

Next code snippet uses fetch api to get random data from QRNG server, so make sure you run this code in browser supporting fetch api.

    function(url) {
			return fetch(url).then(function(response) {
				var contentType = response.headers.get("content-type");
				if(contentType && contentType.includes("application/json")) {
				  return response.json();
				}
				throw new TypeError("Oops, we haven't got JSON!"); }).then(function(json) {
				return json.data;	
			}); 
	}

used quantum random number generator server,[1] to fetch random data

Code snippet below takes secret key as input, creates a public key using elliptic curves cryptography, then formats public key to make it into a bitcoin address.

steps to get bitcoin address out of public key are already explained in previous blog post[2].

    function(key) {
		var pubkey = this.util.bytesToHex(this.getPubKey(key.toUpperCase())).toUpperCase();
		var hashHex = this.hashSHA256RIPMED160(pubkey).toString();
		// Prefix Version Bytes 00
		hashHex = "00".concat(hashHex);
		var doubleHashHex = this.doubleHashSHA256(hashHex).toString();
		var checksum = doubleHashHex.slice(0,8);
		// Suffix Checksum Bytes
		hashHex = hashHex.concat(checksum);
		// Base58 Encoding
		addStr = this.Base58.encode(this.util.hexToBytes(hashHex));
	
		return { sk:key.toUpperCase(),pk:pubkey,bitcoinAddr:addStr}; 
      }

Below is full working code:


  1. ANU Quantum Random Numbers Server ↩︎

  2. How to create a Bitcoin Wallet ↩︎