Technical Guide To Blockchain

GUPTA, Gagan       Posted by GUPTA, Gagan
      Published: June 8, 2021
        |  

Enjoy listening to this Blog while you are working with something else !

   

Cryptocurrencies


Cryptocurrencies are made from four components:
- The data structure (most of the time a blockchain)
- Cryptography
- Rewards for running a nodes
- Decentralized (Peer-to-peer) consensus


Cryptographic Hash function

Before starting with cryptocurrencies, let's see the definition of one of the core element of Cryptocurrencies: the cryptographic hash function. They are used in many ways in cryptocurrencies, such as identifier but also to verify that data are not modified.

It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash) and is designed to be a one-way function, that is, a function which is infeasible to invert.

There are many cryptographic hash functions, such as SHA-256 or Scrypt, X11 (using 11 different hashing functions).
You can test SHA-256 here: https://jsfiddle.net/sandoche/e0jmqLok/


Data structure


The data structure is the skeleton of every cryptocurrency. Let's talk about the most famous one: the Blockchain.

Blocks

Most of the cryptocurrencies are using the blockchain data structure. As its name sounds, it is a chain of blocks containing data. Easy right? Find below an example of a simple block's structure:

- previousHash ? the hash of the previous block
- timetamp ? the date time code
- data ? in the case of cryptocurrencies it will contain the transactions
- nonce ? an integer (it's used for mining we will explain it later)
- hash ? the hash of the current block calculated like this:


Hash of Blockchain


Now that you have seen the block structure it gets easier. The power of this data structure is that, if you change the data of one block, you will have to re-calculate the hash of the block which will invalidate the value previousHash of the next block.

Note that there is one very special block, the first block, it doesn't have any previousHash, it's called the GenesisBlock.

The blockchain data structure is used by most of the coins such as Bitcoin, Litecoin or Ethereum. By adding transactions to the blocks of a blockchain you can turn it into a ledger.

Transactions and cryptography

Now we know what is a blockchain, let's talk about the transactions and how they are processed.

Transactions
Here is the structure of a transaction before it's made:
- transactionInputs[] ? Array of transactionInput
- transactionOutputs[] ? Array of transactionOutput
- id ? Hash calculated from the content of transactionInputs[] and transactionOutputs[]

Now the structure of transactionOutput and transactionInput.

transactionOutput:

- address - Address of the receiver of the transaction
- amount - Amount of the cryptocurrency to be sent to the address

transactionInput:

transactionOutputId ? id / hash of a previous transaction where the output is taken and use as an input
transactionOutputIndex ? index of the output to find the right output from the transactionOutputs[] array

The rule is the following in every transaction the sum of inputs should be equal to the sum of outputs! So what should be done is: if, let's say Alice, has received 30 and she wants to send 10, she has to send also 20 to herself! This is how bitcoin works in order to verify transactions faster. It avoids checking the full history every time a transaction is issued.

Once the transaction is created it has to be signed before being broadcast to the nodes to be part of a block.

Our On-Premise Corporate Classroom Training is designed for your immediate training needs

Technical Guide To Blockchain
Technical Guide To Blockchain

Cryptography

Bitcoin as many other cryptocurrencies are using the Elliptic Curve Digital Signature Algorithm (ECDSA) to secure the transactions but also to create public keys and private keys.

Every user of bitcoin needs two keys: the private key (secret key) and the public key that is used as an address also to receive money. The private key is generated randomly and the public key is gotten with the ECDSA algorithm.

If you want to know how precisely the public key is made read this: https://bitcoin.stackexchange.com/questions/25024/how-do-you-get-a-bitcoin-public-key-from-a-private-key#29880
(it's very technical).

Also, note that this algorithm works only one way, you can get a public key from the private key but not a private key from a public key.

These two keys are used to sign the transaction (that we previously created). A signature can be verified with another function that takes the transaction data and the public key which was used to sign, and will return if it is valid or not.

If you want the technical explanation you can find it here:
https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm

Once the transaction is signed it can be broadcasted to the network.
When a node receives transactions, it first checks if it is valid or not: no double spend, valid account balance, transaction amounts input equals transaction amount output and valid signature. Then it adds it to his transaction pool that it's also shared with other nodes. Then it adds them to blocks.



Accounts balance

In order to calculate the balance of each accounts bitcoin and some other cryptocurrencies are using the UTxO: Unspent Transaction Output.

To simplify, bitcoin stores outside of the blockchain the transactions that are received by each address and not spent. By doing the sum of the unspent transaction of an account you can know the balance of an account. This value is used to ensure that someone is not spending more that what he can.

This UTxO is stored in a database that is managed and updated locally by every node in order to process the transactions and validate them faster without checking the full blockchain.


Proof of Work, Mining, and Puzzles

Since cryptocurrencies are decentralized in a peer to peer network, nodes, which are computers who are running the cryptocurrency software, have to decide which transactions should be included in the next block and agree on that.

There are different consensus to define the rules of agreement. The very first one used in bitcoin is Proof of Work and it is also the most used.

In reallity, bitcoin blockchain adds one block to the blockchain every 10 minutes, and there is not any limit of 3 transactions per block, but a size limit of 1 megabyte per block. There are currently 18,726,056 bitcoins in existence (as of 2021.06.08). This number changes about every 10 minutes when new blocks are mined. Right now, each new block adds 6.25 bitcoins into circulation, and over 83,000 bitcoin nodes are running. Bitcoin fight against Sybil attack using the Proof of Work consensus.

Proof of Work consensus

Instead of choosing randomly the block of a node, nodes have to resolve a computational puzzle. The first who resolves it will be the chosen one, its block will be added to the blockchain

it's always possible to run a bitcoin node without mining, the only purpose is when you make a transaction having a node you don't rely on any intermediary that can save your IP for example. But nodes that are not mining don't get rewards


Rewards & transaction fees

The reward is an incentive to make users become miners, in order to secure the network. Without miners, the network cannot be secured, and without rewards, no one will want to waste its energy, therefore their money.

Every currency has it's own rewards rules that you can find in the source code. For example, Dogecoin (the meme coin) was giving random rewards in its first months of existence.

In bitcoin every node that validates a block receive currently 6.25 BTC, this amount is halved every 4 years. It's a way for bitcoin creators to pre-define an inflation rate! No one can change it.

In order to get this reward, the miner adds a transaction called Coinbase transaction to the block before doing the mining puzzle. This Coinbase transaction doesn't contain any input and contains one output with the reward's amount and the miner's address as a recipient. So once the block is added in the blockchain the miner will keep this reward.

Also when you do a transaction you have to set a transfer fee. This fee is collected by miners. If there are too many transactions happening, the miners will take in priority the transactions with more fees. So you will have to pay higher fees to see your transaction happening fast.


Confirmations & branches

One last and important thing to understand is what is the number of confirmations of a transaction. Confirmations are the number of blocks in the blockchain that are after the block containing the transaction.

As explained before, it happens sometimes that the blockchain has branches, and the miners tend to add blocks to the longest chain (the one with more mining power used to build it actually). If you make a transaction that is added to the blockchain and another branch becomes more important, the smaller branch will become orphan and your transaction will not be part of the ledger.

In bitcoin, if a transaction gets more than 6 confirmations it's considered as secured, and it's unlikely that it will get orphaned. So if you sell goods or services with bitcoin be sure to get the 6 confirmation before giving their due.

Also if you want to check how blocks look like here is the content of one from bitcoin: https://blockchain.info/fr/block/

Our On-Premise Corporate Classroom Training is designed for your immediate training needs

Build Your 1st Blockchain using Python

Step #1: Create a Blockchain Class
import hashlib
import json
from time import time

class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.pending_transactions = []

        self.new_block(previous_hash="The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.", proof=100)
    
Step #2: Write a Function to Build New Blocks
                                
def new_block(self, proof, previous_hash=None):
block = {
    'index': len(self.chain) + 1,
    'timestamp': time(),
    'transactions': self.pending_transactions,
    'proof': proof,
    'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
self.pending_transactions = []
self.chain.append(block)

return block
Step #3: Write Functions to Create New Transactions & Get the Last Block
@property
def last_block(self):

    return self.chain[-1]

# Add a transaction with relevant info to the 'blockpool' - list of pending tx's. 

def new_transaction(self, sender, recipient, amount):
    transaction = {
        'sender': sender,
        'recipient': recipient,
        'amount': amount
    }
    self.pending_transactions.append(transaction)
    return self.last_block['index'] + 1
Step #4: Write a Function to 'Hash' Our Blocks
                                
def hash(self, block):
string_object = json.dumps(block, sort_keys=True)
block_string = string_object.encode()

raw_hash = hashlib.sha256(block_string)
hex_hash = raw_hash.hexdigest()

return hex_hash
Step #5: Create a new Blockchain & Send Some Money!
blockchain = Blockchain()
t1 = blockchain.new_transaction("Satoshi", "Mike", '5 BTC')
t2 = blockchain.new_transaction("Mike", "Satoshi", '1 BTC')
t3 = blockchain.new_transaction("Satoshi", "Hal Finney", '5 BTC')
blockchain.new_block(12345)

t4 = blockchain.new_transaction("Mike", "Alice", '1 BTC')
t5 = blockchain.new_transaction("Alice", "Bob", '0.5 BTC')
t6 = blockchain.new_transaction("Bob", "Mike", '0.5 BTC')
blockchain.new_block(6789)

print("Genesis block: ", blockchain.chain)
As easy as eating a pie, isn't it ?

Support our effort by subscribing to our youtube channel. Update yourself with our latest videos on Data Science.

Looking forward to see you soon, till then Keep Learning !

Our On-Premise Corporate Classroom Training is designed for your immediate training needs

Technical Guide To Blockchain
                         



Corporate Scholarship Career Courses