Making blockchain real: Explaining Bitcoin

In this first episode of the Making blockchain real Series, we take a look at Bitcoin, and put light on some of the ideas that flourished through the publication of its whitepaper.
In case you don’t know us, Making blockchain real presents a Series of episodes about blockchain projects and reviews their programmability by explaining implementation details through simplistic showcases.

Table of contents

What is a digital currency?

Bitcoin was firstly introduced as a peer-to-peer electronic cash system, borrowing the ideas of multiple modern technologies of our time, to provide with a digital form of cash that prevents from double-spending.
Announced as an experiment, Bitcoin made a long way since its inception on January 3rd, 2009 and the Bitcoin protocol source code was updated many times over the years. More details about technicalities and ideas or features of the protocol can be found in the whitepaper, as written by Satoshi Nakomoto and initially published in a cypherpunk mailing list on October 31st, 2008.
In this article, we try to illustrate the main ideas described in the Bitcoin whitepaper with a series of simple questions and follow along with a series of simple blockchain features implementations.

Can I spend the same money twice?

The terms “double spending” are used when the same money is being spent twice. It is a well known fact that cash, for instance, cannot be double spent.
Bitcoin – in contrast to what the whitepaper would tell you at a first glance – is not cash. Bitcoin is fully digital, and as you may well know, anything that is digital can also be copied.
In earlier digital money systems, such as e.g.: Paypal, a central authority (i.e.: a company) would act upon your balance to make sure that balances cannot be double spent. Bitcoin presents a trustless solution to this problem. In fact, a solution that is for the people.

How does public key cryptography help the case?

A transaction in the Bitcoin network is represented by a chain of digital signatures that are created with a technology called public key cryptography.
Furthermore, for a user to spend Bitcoin, the protocol defines that they have to sign a transaction digitally, using the correct private key used to solve a mathematical equation (a.k.a. “solve a script”). The network of nodes that are running the Bitcoin protocol will then include the transaction in a so-called block.
What really matters about one such block of data, is that it includes an algorithmic hash of its’ content, that it is timestamped (i.e. it is stamped upon creation) and even more, that it includes a reference to the preceding block – effectively building a chain of blocks.
As to how exactly these blocks are signed using public key cryptography, it’s easier to imagine an account with two important pieces for information: a public key, and a private key. These keys are to be treated with care – the public key gives allowance to view your Bitcoin balance(s), whereas the private key gives allowance to spend your Bitcoin. Never reveal your private key to anyone.

What is mining and how does it relate to digital currency?

In addition to public key cryptography, Bitcoin uses a technique previously used by mail filters to fight SPAM (i.e. Hashcash): Proof of Work which consists in executing an amount of computational work before blocks can be added to the ledger.
The amount of work required to send your usual e-mail is not to be compared to the amount of work required to find a valid Bitcoin block. That is because Bitcoin requires a certain minimum amount of work to be performed, whereas by sending an e-mail, proof-of-work is merely implemented as a form of automated captcha system.

Mining Bitcoin: Who are the yellow suit miners?

It could be you! In fact, Bitcoin can be mined by anyone and with any type of device which disposes of a CPU – yet, please note that mining with a smart watch will not yield as many results. On top of being open, Bitcoin’s protocol introduces a mining difficulty which adapts to the current network load as to keep an average of 10 minutes block time over a period of two weeks.
The mining difficulty automatically adjusting itself every two weeks is what makes Bitcoin mining really complicated. We will try to skim through this topic by analysing some of the benefits of it.
Miners are just computers that focus on finding the next Bitcoin block. In order to find a valid block, with for instance a difficulty of 5, it would require a miner to find a block for which the double SHA-256 hash of its content, produces a hash with at least 5 leading zeroes (e.g.: 00000af).
As such, miners will be running one simple algorithm on and on and over and over again. Following is a simplistic reproduction of the difficulty algorithm as showcased in UsingBlockchain/ChainTs, our blockchain for beginners:


/**
* Mine a block’s hash to match a minimum \a difficulty
* of leading zeros. This method increases an internal
* nonce and calculates SHA-256 hashes of a block.
*
* @param number difficulty
* @return Block
*/
public mineBlock(difficulty: number = 1) {
let leadingZeros = ‘0’.repeat(difficulty)
 
this.nonce = 0
while (this.blockHash.substring(0, difficulty) != leadingZeros) {
this.nonce++;
this.blockHash = Block.calculateHash(this);
}
}

Source: Method mineBlock in class Block of @ubcdigital/chaints

This simplistic reproduction snippet above, basically loops until it finds a satisfying SHA-256 hash (i.e. until it finds a hash that starts with a given number of leading zeroes).
We want you to understand proof-of-work and therefor we prepared a custom blockchain implementation in Typescript, which you can find at Github.
Beware that this custom miner implementation is not compatible with Bitcoin. It is merely an attempt for us to explain blockchain with the help of simplistic showcases such that the value of underlying principles can be caught and understood.
After you downloaded the @ubcdigital/chaints package from Github or installed it with npm through: npm install -g @ubcdigital/chaints, you can simply call the Miner command from your terminal, as shows the following snippet:


$ ./chaints Miner –difficulty 1 –blocks 3 –message “My awesome blockchain”

This shall give you a similar output as shown in below screenshot:

Three hashes produced with difficulty 1

Now go ahead and execute the same miner process, but pass a difficulty of 3, this time. This has the consequence to increase the amount of time needed to find valid hashes, ergo the amount of work needed. Yet, even for a difficulty of 3, it is easy enough for our miner to find matching blocks, as demonstrates the following screenshot:

Three hashes produced with difficulty 3

Do you note the difference in the hashes presented in both screenshots? In the first screenshot, we find hashes that start with one leading zero because the difficulty is set to 1. In the second screenshot, we find hashes that start with three leading zeroes because the difficulty is set to 3.
Now, go ahead and execute the same command with a difficulty of five (5) – it will take more time for your computer to find matching hashes. The amount of work required to find a matching hash increases if the difficulty increases, this same principle also applies to Bitcoin mining.

Automatic difficulty adjustment

As opposed to the above examples, Bitcoin’s protocol defines an adaptive difficulty. That is, Bitcoin defines that the difficulty adapts over time and sets an average block time of 10 minutes. This has very important implications.

  • (1) Mining blocks for Bitcoin should always require an approximate 10 minutes of computational work.
  • (2) After a period of two weeks, Bitcoin automatically adjusts the difficulty depending on the average time the network needed to mine two weeks worth of blocks.

Could proof-of-work be a market for energy?

As showcased above, the work being executed is that of trying to find a good enough value that will be accepted as the next block. The innovation in this work is not only that everyone can participate, but also that the work needed to find blocks is adaptive and changes depending on the time it took the whole network to generate the last two weeks worth of blocks.
With this, Bitcoin also incentivizes miners by automatically adding Bitcoin into circulation when a new block is mined. In simpler words: when a miner is done with the necessary work to mine a block, they are rewarded with Bitcoin.
The operation of mining Bitcoin blocks is oftenwise referred to as a waste of energy. I would like you to reconsider this, taking into account the following statement:

Bitcoin enables an alternative market for energy where CPU power, or energy, is the input and Bitcoin is the output (or the reward).

In fact, the market for Bitcoin mining has grown so fast – and the price of it as well – that it is now possible to trade your over-production of energy for Bitcoin by redirecting your waste of energy to mine Bitcoin.

What is peer-to-peer and why does it matter?

The terms peer-to-peer (“P2P”) refer to a network topology in which work load is partitioned between peers of the network.
While P2P systems had previously been used in many application domains, the architecture was popularized by the file sharing system Napster, originally released in 1999.
In Bitcoin, peer-to-peer is used to communicate transactions and blocks with an open network of peers.

Distribution as an automatic defense mechanism

The peer-to-peer nature of the Bitcoin protocol is in fact a defense against badly behaving participants. As more nodes are added to the Bitcoin network, it gets more and more difficult to overrule a majority of those about the rightfulness of Bitcoin (some tried…).
For an attacker to succeed in rewriting the Bitcoin data, they would have to not just rewrite their local copy of the data but they would also have to overrule a majority of other participants that their copy of the data is the rightful one. In practise, with each new block added to the Bitcoin network, it gets more difficult to rewrite the history of blocks – with more than 11 years of runtime, it is getting nearly impossible to rewrite the history of Bitcoin blocks.
From another perspective, this means that by attaching data to a Bitcoin transaction, the said data is made redundant (i.e. many copies are created), it is also made immutable (i.e. can never be changed) and it is made verifiable (i.e. anyone can verify by whom it was signed).
Now, let’s analyse one such peer-to-peer topology, with a simplistic showcase reproduction in @ubcdigital/chaints:


/**
* Broadcast block information
*
* @param Block block The block that we’ll broadcast.
* @return any
*/
public async broadcastBlock(
block: Block,
): boolean {
// – Other peers will receive block hash information
for (let i = 0, m = this.clients.length; i < m; i++) {
this.clients[i].emit(‘peer-msg’, block.blockHash)
}
 
return true
}

Source: Method broadcastBlock in class PeerToPeer of @ubcdigital/chaints

For a full implementation, please refer to the src/network/PeerToPeer class in @ubcdigital/chaints.
The snippet above gives you a simplistic example of broadcasting block information to all known peers. The important bit here is that the message is being emitted to all known peers.

Publishing proofs over a peer-to-peer network

Following the above showcase of peer-to-peer communication, we know that all peers of a network will know about all blocks of a network. As teaches the protocol, the list of blocks in Bitcoin is a reverse-linked list where each entry owns a link to the previous entry in the list.
This linked list of blocks is important when an attacker tries to corrupt data from a previously confirmed block (i.e. a block to which a subsequent block holds a link), as this effectively means the attacker also has to re-do the work (i.e. mining) for all blocks following it.
Every peer of the Bitcoin network is effectively a validator for future blocks. For miners to find out about data corruption is trivial as we showcased in the src/chain/Auditor class in @ubcdigital/chaints


/**
* Verify the integrity of a chain of blocks. This method iterates
* through all available blocks and validates their height, hashes
* and previous block links.
*
* @return boolean
*/
public verify(): boolean {
// – Iterate all blocks in the chain
for (let i = 0, m = this.chain.blocks.length; i < m; i++) {
if (true === this.verifyBlock(i)) {
continue;
}
 
// – Bail out given corruption
return false
}

// – Full chain audited
return true
}

Source: Method verify in class Auditor of @ubcdigital/chaints

We also included a timestamping mechanism in our miner but it is not as powerful as Bitcoin’s timestamping because Bitcoin is distributed through a network of peers, whereas our ChainTs showcase is a simplistic attempt at explaining Bitcoin.
In action, the timestamping mechanism actually allows us to prove that some data X existed at a previous point in time. A more in-depth example of timestamping can be found at OpenTimestamps.
Following snippet is an attempt at explaining how mining is done for Bitcoin blocks, again – this is another simplistic showcase as found in @ubcdigital/chaints


// – Create at max `-b` blocks
while(blockchain.blocks.length < maxBlocks) {
 
// – Search for matching block hash
let block: Block = blockchain.createBlock(‘Another block’);
 
// – Start mining process
blockchain.appendBlock(block)
 
// – Broadcast block to network
network.broadcastBlock(blockchain.blocks[0])
}

Source: Block miner generation in class Miner of @ubcdigital/chaints

Break it down to form a network!

In our showcase implementation @ubcdigital/chaints, we implemented a simplistic blockchain networking topology and block miner.
In a production environment, it is necessary to upgrade the peer-to-peer networking features, as well as introduce a consensus mechanism, different than the very simplistic one we have which only checks: (1) for a valid block height, (2) for a valid previous block height and (3) for a valid previous block hash.

Book a call with a UBC blockchain expert for assistance or guidance on integrating the technology in your business.

We hope that this article was insightful for you and are looking forward to any feedback and messages. Please share your thoughts in the comments section below!

Disclaimer

This website may contain information about financial firms, employees of such firms, and/or their products and services such as real estate, stocks, bonds, and other types of investments. While this website may intend - as the author deem necessary - to provide information on financial matters and investments, such information or references should not be construed or interpreted as investment advice or viewed as an endorsement.