Programming Blah

Blockchain - Part 2, Bitcoin

2020-06-22tutorialhow-toblockchainbitcoin

In the previous article, I gave a brief introduction about blockchain and the underlying cryptographic technologies required by it. If you haven’t read the first article i will strongly suggest you to read it before continuing.

In this article i will try to explain the working of blockchain by taking cryptocurrency Bitcoin an an example (Since it is the most popular implementation of blockchain).

How does bitcoin works?


Bitcoin is a cryptocurrency that uses blockchain technology as distributed ledger. To understand the working of bitcoin, let’s look at the following scenario where Alice wants to send 12 bitcoins to Bob.

Let us assume Alice has 15 bitcoins in her bitcoin wallet which she received via some previous transactions to her bitcoin addresses. Now you will ask, what is bitcoin wallet and bitcoin address? So before moving further, let’s take a moment to understand these.



Bitcoin Wallet :- Contrary to popular belief, bitcoin wallet does not stores bitcoin, It is actually used to store private and corresponding public keys, which can be used to do transactions in bitcoin network.

There are different kinds of wallet :-

  • Paper Wallet- As the name suggest, it is a paper or a document with bunch of public and private key written on it. The biggest advantage of paper wallet that it is offline and is unhackable, but special care has to be taken, since it can easily get lost or destroyed.
  • Digital Wallet- It is a software program that can be used to generate and store public and private keys. Usually, digital wallet also has a bitcoin client embedded in them, which talks to bitcoin network and can be used to do transactions.

Bitcoin Address :- Like email address, a bitcoin address is a destination where bitcoin can be sent to, but unlike email address, for security and privacy concerns, a new bitcoin address is generated for every transaction. Bitcoin address can be generated freely and can be done offline. This is usually done by a bitcoin wallet.

A bitcoin address is simply a hash of the public key. If you want to know more on how to generate a bitcoin address you can read about it here

following are some examples of bitcoin address :-

1) 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2
2) 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy
3) 1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs


Moving forward, let us suppose following are the contents of Alice’s and Bobs’s bitcoin wallet

Alice’s wallet :-

Private Key Public Key Bitcoin Address Amount
prv(Alice_1) pub(Alice_1) hash(pub(Alice_1)) 5
prv(Alice_2) pub(Alice_2) hash(pub(Alice_2)) 10
prv(Alice_3) pub(Alice_3) hash(pub(Alice_3)) 0

Bobs’s wallet :-

Private Key Public Key Bitcoin Address Amount
prv(Bob_1) pub(Bob_1) hash(pub(Bob_1)) 0

As you can see from the above table, Alice has 3 private and corresponding public keys in her wallet, having a total value of 15 bitcoins whereas Bob has only 1 public private key pair.

To send 12 bitcoins to Bob’s bitcoin address (hash(pub(Bob_1))), Alice needs to create a transaction which will be broadcasted to the bitcoin network. Before going further let us understand what is a transaction.



Transaction :- A transaction is a data structure that is used to transfer bitcoins. A transaction created by a user depends upon previous transactions which are already in the blockchain.

A transaction has 2 parts, Input and Output.

  • Input - An input in the transaction refers to the output of some previous transaction already in the blockchain. It contains data and instruction which allows a user to redeem the bitcoins it received on its bitcoin address which is in the output of some previous transaction. A transaction can have multiple inputs. Following are the fields in an input (for sake of simplicity i have only mentioned fields which are required for this article):-

    Field Description
    Transaction Hash Pointer to the previous transaction
    Output Index A transaction can have multiple output. Index number is used to refer a to a specific output in previous transaction. Starts with 0.
    Unlocking Script script used to meet the condition to unlock the output of the previous transaction (more on this later).
  • Output - Output of a transaction contains instruction and data which specify the destination of the bitcoins. A transaction can have multiple outputs. Following are the fields in an output :-

    Field Description
    Value Bitcoin Value
    Locking Script A script defining the conditions needed to spend this output (more on this later).

A single transaction output is indivisible. You have to spend all the bitcoins received at that particular address or transfer the balance or change to one of the bitcoin addresses that you own. If you do not specify the change in the output, the balance will be lost, i.e, it will be consumed by the miner as transaction fee.

The bitcoin value of all the inputs in a transaction should be equal to the bitcoin value of all the outputs plus the transaction fees.

Total of all inputs = total of all outputs + transaction fee

You must have noticed above, that input and output have fields called as unlocking and locking script. Bitcoin uses a scripting language for transaction called as Script. It is a stack-based language and is intentionally made turing incomplete, which means it lacks in features that modern programming languages has, like loops. We will learn more about this scripting language and how it is used in bitcoin later.




Continuing with our example of Alice and Bob, To transfer 12 bitcoins to Bob, Alice creates a transaction.
bitcoin transaction example
Alice to Bob transaction

You can see from the above diagram that Alice has received a total of 15 bitcoins from two different transactions (transaction_to_alice_1, transaction_to_alice_2) already in the blockchain. If you will look at the output sections of the two transactions, you will notice that Alice’s bitcoin address hash(pub(Alice_1)) has received 5 bitcoins and address hash(pub(Alice_2)) has received 10 bitcoins.

To send 12 bitcoins to Bob, Alice has created a new transaction (transaction_alice_to_bob). The input part of this transaction has 2 entries where each of those entries points to the output of the previous transactions. Each input entry contains a pointer to the previous transaction, an index of the output, a digital signature (created using the private key) and public key of corresponding bitcoin address. All these information together enables Alice to spend the bitcoins.

The output part of this transaction specifies the amount and destination address (mentioned in the locking script) for bitcoin transfer. In the above diagram you can see output section contains 2 entries, one to transfer 12 bitcoins to Bob (hash(pub(Bob_1))) and other to transfer 2 bitcoins as balance or change back to Alice (hash(pub(Alice_3))). You must have noticed that there is still 1 bitcoin unaccounted for, this unaccounted bitcoin is used by the miner as a transaction fee.

Once the transaction is created, it is broadcasted to bitcoin network so that miners can validate and add this transaction to the blockchain.

Before going further, let’s have a look at miners and their roles and responsibilities.




Miners :- Miners are nodes in bitcoin network whose job is to validate transactions and add those transactions into a block and add that block to the blockchain. To do this, miners in the bitcoin network uses proof of work consensus algorithm where miners try to solve a complex mathematical problem and whichever miner solves it first, its block will be added to blockchain. By doing this, the winning miner gets some bitcoins as compensation, called as block reward.

At the start of the bitcoin, the block reward was 50 coins. As per bitcoin protocol, block reward gets halved after every 210,000 blocks. At the time of writing this article, the block reward is 6.25 bitcoins. Once the block reward reaches 0, miners will earn bitcoins only through transaction fees which users pay each time they create a transaction. Transaction fees are optional, transactions without a transaction fee might wait a long time to be processed if the network is congested.




Moving forward with our example, Upon receiving the newly created transaction from Alice, miners in the bitcoin network have to validate the transaction.

As mentioned before, bitcoin protocol uses a stack-based scripting language (Script) to validate a transaction. On receiving the transaction, miners reads the input part of the transaction and gets the reference to the output of the previous transaction on which this one depends. By combining the unlocking script of the input and the locking script of the output, miners executes the script and if it evaluates to true, then it means that Alice is the owner of the bitcoin address and is authorised to spend it. Following is a diagram of the execution process.

script execution
Script Execution Example

In the above diagram, OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG are operators that operates on the elements in the stack. The above example merges the unlocking script mentioned in the input of transaction “transaction_alice_to_bob” with the locking script mentioned in the output of transaction “transaction_to_alice_1”. The merged script is executed and it evaluates to true. You can read more about the scripting language here.

Once it is established that Alice is indeed the owner of the bitcoin addresses refered by the input part of transaction, miners than check whether Alice has enough bitcoins to send.

Once the validation is done, miners will then add this transaction to a candidate block. Since each miner in the bitcoin network have their own candidate block, they uses a consensus algorithm to decide whose block will be added to the blockchain. Bitcoin uses proof of work consensus algorithm. Let us take a moment to understand how this algorithm works.




Proof of Work (Consensus Algorithm) :- Miners in the bitcoin network uses proof of work consensus algorithm to decide on the state of the blockchain. In proof of work, Miners has to solve a complex mathematical problem which is time consuming and requires lot of resources (electricity, computing power) but easy to verify.

Bitcoin uses Hashcash proof of work algorithm. In Hashcash, the idea is to find data whose hash is smaller or equal to the target hash. For example, imagine you are playing a game in which you have to choose a number between 1 to 100. Lets say you have choosen 24, and without disclosing the number, you ask your friends to guess a number which is smaller or equal to number you have chosen (24). The person who guesses the correct number first is the winner.

The number you choose decides the difficulty of game. If you choose a number which is closer to 100 it will be easier for your friends to guess as compared to the number closer to 1.

Similarly, In context of bitcoin to understand proof of work, lets first look at the block header :-

BytesNameData TypeDescription
4versionint32_tThe block version number indicates, the set of block validation rules to follow.
32previous block header hashchar[32]A SHA256 hash of the previous block’s header. This ensures no previous block can be changed without also changing this block’s header.
32merkle root hashchar[32]The transactions in the block are stored in form of merkle tree. Merkle tree is important because it allows a user to verify transaction without downloading the complete blockchain and also merkle root ensures that none of the transaction has been modified without changing the header
4timeuint32_tThe block time is a Unix epoch time when the miner started hashing the header (according to the miner). Must be strictly greater than the median time of the previous 11 blocks.
4nBitsuint32_tAn encoded version of the target hash that this block’s header hash must be less than or equal to.
4nonceuint32_tA number which miners change to modify block header to generate a hash which is less than or equal to the target hash.


As you can see from the above table, except nonce, everything in the header is fixed. When a miner verify all the transactions and creates a candidate block, it starts finding the block hash which is smaller or equal to the target hash by modifying nonce.

flowchart proof of work
Flowchart: proof of work

The difficulty level or target hash changes after every 2016 blocks. As per bitcoin protocol a new block is to be added into the system every 10 minutes, which means 2016 blocks will take exactly 2 weeks. If it takes more than 2 weeks, the difficulty is reduced or if it takes less than 2 weeks, difficulty is increased. The formula for calculating difficulty is

difficulty = largest_possible_difficulty/current_difficulty

You can read more about difficulty or target hash here.




Moving on with our example, once a miner is able to find a hash of the block header which is smaller or equal to the target hash, it broadcast that block to the bitcoin network where other nodes validates and then add it to the blockchain. Once the block is added it cannot be altered or modified in anyway.

If a malicious miner modifies a block, the block hash will change. Since in blockchain each block is linked to its previous block via block hash, the malicious miner has to modify all blocks following it, which is an extremely time consuming and resource hungry process. We will read more about security of blockchain in the next article.

It is possible that two miners broadcasts a block into the network same time. In this scenerio, nodes in the network chooses blockchain that is longest. The longest chain doesn’t means that it has the most number of block, it is the chain that took most effort to build, i.e most computing power and resource were used in creating the chain.

Once the block is added to the blockchain, the transaction is complete and Bob has received bitcoins from Alice and he can further spend those coins.

In the next article we will go through the applications, security and known vulnerabilties of blockchain technolgy.

References