How does Bitcoin work – Part 2 | The “Billcoin” Block Chain

bitcoin
Fri Mar 14 2014

Introduction

In the previous post we mentioned that in order to have a solid and concrete understanding of all of the underlying principles of Bitcoin we’ll try to create our own crypto-currency. It will be muuch more simple but this way we can see what problems occur during the process of creating an online crypto-currency. The steps completed in the previous post were

1) The logo of the coin (important)
2) The algorithm for the creation of the “Wallet”.

The wallet is our reference point as an individual to send and receive Billcoins. It also has a public key and a private key. The public key is visible to everybody. The private key is necessary to sign transactions that prove our identity and integrity. Everybody can verify that the transaction requests are done by our wallet but no-one can create a new request. The next step would be to create a decentralized system that would keep track of how many money everybody has.

In this part we will go over the Block Chain.

The Billcoin Block Chain Theory

A standard way to send money electronically today (it is a gif).

How does a decentralized system work? Instead of having one place to store everything and a central authority to approve or not a transaction.

1) The transaction request is being sent to the network.
2) Everybody has all of the previous transactions made. This transaction list is the Block Chain.
3) Once the transaction is approved by a miner (we’ll see this in the mining post) and transmitted back to the network with a signature. Everybody can update their block chain.
4) Instead of having a “ledger” you can see how many money someone has just by looking at his previous requests and calculate how many coins were sent and received from that wallet.

 

So the whole Billcoin economy is nothing else than a file (the block chain). This file is a series of transactions. If we can all agree with the series of the transactions then we have a robust crypto-economy.

Below you can see a series of events that is the Block Chain. Each block has some transactions. We will go in depth how a transaction is made in the next post. But you can notice at a first glance that to send money I have to send the amount I want to any wallet and send the remaining amount back to me. This way we can calculate how much money Bill has by easily seeing one block where Bill sent money and the blocks after that where he received.

 

How can I have this chain of events recognized by everybody on the network. It is just a file, can’t I just create my own series of events and broadcast it to the network? How can the nodes in the network know what new blocks to attach in their block chain and which to remove? Ha! This is the most innovative and important part of the Bitcoin algorithm and we’ll use it in Billcoin as well. It is a bit hard to grasp in the beginning but we’ll tackle this one step at a time at this blog post.

Hashes

There are these algorithms called hash functions. These take some data and return a fixed-size bit string with that data

1) Each input returns one unique output.
2) It is easy to know the output from the input.
3) It is almost impossible to calculate the input from the output.

You can checkout a SHA256 generator below. Enter any text you want and you’ll notice as an output you’ll get a fixed-size string.
For each input you’ll get a unique output.
And even with a very small change in the input the output is completely different.

You can see the algorithm of Sha256 below. It has a lot of recursions and bitwise operations that create the magic. To have an output from an input but cannot find the input from the output. You can give it a glance again but don’t try too hard to understand what is going on, just know what it does.

var Sha256 = function(){

	var self = this;

	self.W = [];
	self.K = [];
	self.n = 2;
    self.nPrime = 0;

    self.isPrime = function(n) {
        var sqrtN = Math.sqrt(n);
        for (var factor = 2; factor <= sqrtN; factor++) {
            if (!(n % factor)) {
                return false;
            }
        }

        return true;
    };

    self.getFractionalBits = function(n) {
        return ((n - (n | 0)) * 0x100000000) | 0;
    };

    while (self.nPrime < 64) {
        if (self.isPrime(self.n)) {
            self.K[self.nPrime] = self.getFractionalBits(Math.pow(self.n, 1 / 3));
            self.nPrime++;
        }

        self.n++;
    };

	self.bytesToHex = function(bytes) {
		for (var hex = [], i = 0; i < bytes.length; i++) {
			hex.push((bytes[i] >>> 4).toString(16));
			hex.push((bytes[i] & 0xF).toString(16));
		}
		return hex.join("");
	};

	self.binaryBytesToString = function (bytes) {
		return bytes.map(function(x){ return String.fromCharCode(x) }).join('');
	};

	self.wordsToBytes = function (words) {
	    var bytes = [];
	    for (var b = 0; b < words.length * 32; b += 8) {
	        bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
	    }
	    return bytes;
	};

	self.bytesToWords = function (bytes) {
	  var words = []
	  for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
	    words[b >>> 5] |= bytes[i] << (24 - b % 32)
	  }
	  return words
	}

	self.stringToBytes = function (str) {
		return self.binaryStringToBytes(unescape(encodeURIComponent(str)));
	};

	self.binaryStringToBytes = function (str) {
		for (var bytes = [], i = 0; i < str.length; i++)
			bytes.push(str.charCodeAt(i));
		return bytes;
	};

	self.generate = function(message, options) {

		self.W = [];

	    if (message.constructor === String) {
		    message = self.stringToBytes(message);
		  }

		  var H =[ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
		           0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 ];

		  var m = self.bytesToWords(message);
		  var l = message.length * 8;

		  m[l >> 5] |= 0x80 << (24 - l % 32);
		  m[((l + 64 >> 9) << 4) + 15] = l;

		  for (var i=0 ; i<m.length; i += 16) {
		    self.processBlock(H, m, i);
		  }

		  var digestbytes = self.wordsToBytes(H);
		  return options && options.asBytes ? digestbytes :
		         options && options.asString ? self.bytesToString(digestbytes) :
		         self.bytesToHex(digestbytes)

	};

	self.processBlock = function (H, M, offset) {

	    // Working variables
	    var a = H[0];
	    var b = H[1];
	    var c = H[2];
	    var d = H[3];
	    var e = H[4];
	    var f = H[5];
	    var g = H[6];
	    var h = H[7];

	    // Computation
	    for (var i = 0; i < 64; i++) {
	        if (i < 16) {
	            self.W[i] = M[offset + i] | 0;
	        } else {
	            var gamma0x = self.W[i - 15];
	            var gamma0  = ((gamma0x << 25) | (gamma0x >>> 7))  ^
	                          ((gamma0x << 14) | (gamma0x >>> 18)) ^
	                           (gamma0x >>> 3);

	            var gamma1x = self.W[i - 2];
	            var gamma1  = ((gamma1x << 15) | (gamma1x >>> 17)) ^
	                          ((gamma1x << 13) | (gamma1x >>> 19)) ^
	                           (gamma1x >>> 10);

	            self.W[i] = gamma0 + self.W[i - 7] + gamma1 + self.W[i - 16];
	        }

	        var ch  = (e & f) ^ (~e & g);
	        var maj = (a & b) ^ (a & c) ^ (b & c);

	        var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
	        var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7)  | (e >>> 25));

	        var t1 = h + sigma1 + ch + self.K[i] + self.W[i];
	        var t2 = sigma0 + maj;

	        h = g;
	        g = f;
	        f = e;
	        e = (d + t1) | 0;
	        d = c;
	        c = b;
	        b = a;
	        a = (t1 + t2) | 0;
	    }

	    // Intermediate hash value
	    H[0] = (H[0] + a) | 0;
	    H[1] = (H[1] + b) | 0;
	    H[2] = (H[2] + c) | 0;
	    H[3] = (H[3] + d) | 0;
	    H[4] = (H[4] + e) | 0;
	    H[5] = (H[5] + f) | 0;
	    H[6] = (H[6] + g) | 0;
	    H[7] = (H[7] + h) | 0;
	};

};

OK now you know what a hash is. Have the algorithm and an example on top. How does this help in creating a list of events that is universally accepted and unhackable?

Proof-of-Work

Remember above that we said that it is almost impossible to figure out an input from an hash output? So if I give you a random string “asdf” and tell you I want you to find a string where when I concatenate asdf with that string for it to give me a hash that starts with a zero. What would you do? The only way to answer this is to begin to randomly add strings at the end of “asdf” until you find a hash that starts with a zero.

Below we can see various tries to find a hash starting with zero. After a couple of tries we see that 4 returns a hash that starts with zero!!

 

Now you can imagine how hard this can become if we want a hash starting with two zeros, or three zeros e.t.c. It becomes exponentially harder.

To add a block in the blockchain you should grab a couple of transactions pending for approval that are wandering around our p2p network. Filter them and create a hash key with the whole data of those transactions.

You’ll create a big string of all of the data and sha256() that string. Then you’ll have a nice unique hash number. On top we used “asdf” but in the Bitcoin case that will be a hash number which is generated from the transactions data. Then you should try to find a magic number that will create a hash from that hash and it will have a number of zeros in the front depending on the “power of the network”. If we have a lot of computers trying to grab transactions, creating a bundle of those and finding the unique number that will give a hash with some zeros in front, you’ll have to increase the zeros needed to be found. This way you’ll create a nice pace of blocks being added.

All of the nodes in the network accept the block chain in existence with the most blocks. With node we mean each computer that is connected to the Bitcoin p2p network. And as we know a p2p network transfers data from one computer to another. So there is no central authority, no central system and no central database.

For someone now to hack the network and add a big chain of events by himself that will surpass the chain of the network is extremely difficult. Since he is constantly in competition with the whole process power of the whole network. Each PC in the network that is trying to find a magic number that will generate a hash with X amount of zeros is securing the network. A hacker could never generate the process power necessary to create a chain of events larger than the chain generated by thousands of computers and cpu cycles in the network. He could never keep up.

 

Billcoin Block Chain

You can checkout now Step 2 in the Billcoin economy over here => http://bstavroulakis.com/demos/billcoin/ and get an overview of the Billcoin Block Chain!

Conclusion

In this post we went over what is a Hash and the Block Chain at a very high level. In the next post we’ll see what is a Transaction and try to write some code on how to make a transaction and add it in our own Block Chain of the “Billcoin” economy. So, as Bitcoin has its own Block Chain which is the whole Bitcoin economy, we’ll create a Billcoin Block Chain which will be the Billcoin economy.

References

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!