Discover Blockchain Fundamentals

Introduction

The Blockchain is a virtual ledger, where each record is a block. These records are distributed in a network where anyone can read and write, but not modify existing information.

The size of a block varies depending on the configuration of the blockchain. When the data to be written on the blockchain has reached the maximum block size, it is added and a new block is created. The block size is around 1Mb for Bitcoin .

The objective of this article is to understand how a blockchain works. We will start with the content of a block. The diagram below illustrates a block.

Block

BlockNumber
Each block in a blockchain has a number that represents your position in the chain. The first block added to the chain has a special name, it is called genesis block.

PrevBlockHash
Each block has a reference to the hash number of the previous block. This is very important, because this is how the blockchain stays consistent and controls immutability. The genesis block does not reference a previous block since it is the first block.

MerkleRoot
This is the result of hashing all transactions inside the block. If anything is modified inside the block, this hash will invalidate the modified block. The name comes from the fact that Bitcoin uses the Merkle tree to generate the hash from block data.

Nonce
This is a 32-bit number that is related to the mining process of a block. This number is only used once to find a hash that matches the difficulty of the blockchain.

CreationTimestamp
This is the creation date of the block.

Data
This is transaction data.

Hashage

The hash used in the block corresponds to a function that will calculate a digital fingerprint from input data. The hashing algorithm depends on the configuration of the blockchain. Bitcoin uses the SHA-256 (Secure Hash Algorithm).

The MerkleRoot is obtained by calculating the hash of the transactions recursively so as to obtain a single hash for all the transactions. To understand how it works, we take these four transactions:

const tA = 'Hello'
const tB = 'How are you?'
const tC = 'This is Thursday'
const tD = 'Happy new Year'

We start by calculating the hash of each of these transactions.

const sha256 = require('js-sha256').sha256

// Double-hashing here
const hA = sha256(sha256(tA))
const hB = sha256(sha256(tB))
const hC = sha256(sha256(tC))
const hD = sha256(sha256(tD))

//Results
52c87cd40ccfbd7873af4180fced6d38803d4c3684ed60f6513e8d16077e5b8e //hA
426436adcaca92d2f41d221e0dd48d1518b524c56e4e93fd324d10cb4ff8bfb9 //hB
6eeb307fb7fbc0b0fdb8bcfdcd2d455e4f6f347ff8007ed47475481a462e1aeb //hC
fd0df328a806a6517e2eafeaacea72964f689d29560185294b4e99ca16c63f8f //hD

We must concatenate these hashes in pairs to obtain a single hash.

//Pairing hA and hB
const hAB = sha256(sha256(hA + hB))
//5dc23d1a2151665e2ac258340aa9a11ed227a4cc235e142a3e1738333575590b

//Pairing hC and hD
const hCD = sha256(sha256(hC + hD))
//ff220daefda29821435691a9aa07dd2c47ca1d2574b8b77344aa783142bae330

// We do it again. We pair hAB and hCD to obtain the root
const hABCD = sha256(sha256(hAB + hCD))
//301faf21178234b04e1746ee43e126e7b2ecd2188e3fe6986356cc1dd7aa1377

The information that will be stored in the block corresponds to the last hash, that is to say: “301faf21178234b04e1746ee43e126e7b2ecd2188e3fe6986356cc1dd7aa1377”. All the transactions of a block are therefore summarized in 32 bytes. If a transaction is modified, then this last hash will not be the same. The diagram below illustrates how the Merkle tree works.

Merkle Tree

Blockchain

The diagram below illustrates the blocks linked together thanks to the PrevBlockHash , we then speak of blockchain.

Chained Blocks

Reading data on a blockchain is free and unlimited. If the blockchain is public, anyone can verify the information recorded. For example, block 500312 of Bitcoin can be accessed. It contains the information of the block presented previously.

Bloc Bitcoin

Mining

Writing on a blockchain requires maintaining its immutability, this implies the establishment of a consensus. Bitcoin’s consensus algorithm is Proof Of Work , this operation is called mining.

Bitcoin mining involves finding the hash of the current block first. It must be valid and take into account CreationTimestamp creation date, Nonce and difficulty .

The difficulty indicates how difficult and long it will be to find the hash. The validity of a hash depending on the implementation of the blockchain, it can be the fact that it must contain a sequence of characters. The nonce makes it possible to vary the result of the hash until a valid hash is found.

Implementation

To go further in understanding a blockchain, we create a blockchain.js file with the code of our simplified blockchain.

const sha256 = require('js-sha256').sha256

const blockchain = (function(){
  const blocks = []

  const initBlockchain = () => {
    const data = 'Hello World!'
    const timestamp = new Date()
    const previousHash = 0
    const index = 0
    hashBlock(data, timestamp, previousHash, index)
  }

  const hashBlock = (data, timestamp, prevHash, index) => {
    let hash = '', nonce = 0

    while( !isHashValid(hash) ){
      let input = `${data}${timestamp}${prevHash}${index}${nonce}`
      hash = sha256(input)
      nonce += 1
    }
    console.log(nonce)
    blocks.push(hash)
  }

  const getLastHash = blocks => blocks.slice(-1)[0]

  const isHashValid = hash => hash.startsWith('0000') // Difficulty

  const addNewBlock = data => {
    const index = blocks.length
    const previousHash = getLastHash(blocks)
    hashBlock(data, new Date(), previousHash, index)
  }

  const getAllBlocks = () => blocks

  return {
    initBlockchain,
    getLastHash,
    blocks,
    getAllBlocks,
    addNewBlock
  }
})()

module.exports = blockchain

This javascript module contains 5 accessible methods:

initBlockchain : This method starts the blockchain by creating the first block, the genesis block. I give it a timestamp, a message, the index of the block in the blockchain (0) and an arbitrary previous hash because there are no previous blocks in the chain yet.

hashBlock : This method takes all the data from the block and creates a hash. As you can see, the first time we run the function for a specific block, the nonce is set to 0. We calculate the hash of our block and check if the hash is valid with isHashValid . In our case, a hash is valid if the first four characters are 0, this is called the difficulty. This is the problem we need to solve to make sure the block can be part of the blockchain. Once the hash is valid, we add it to our block array.

addNewBlock : Adds a new block with an input message. The method calls hashBlock with the data to create and validate the new block.

getLastHash : Gets the previous hash which is needed to create a new block.

getAllBlocks : Returns all Blockchain blocks

We now create an index.js file to use our blockchain.

const blockchain = require('./blockchain')

blockchain.initBlockchain()
blockchain.addNewBlock('First new block')
blockchain.addNewBlock('I love blockchains')
blockchain.addNewBlock('Make me a new hash!!')

console.log(blockchain.getAllBlocks())

This script adds 4 blocks, the result obtained is the following:

Initializing the blockchain
139355
30720
68789
51486
[ '0000d87875f12e8c00d60cdfc8c21c4867eb1e732d3bb0e4d60bd0febcfafbaf',
  '0000331d80f4e83461bad846e082baa08c5e739edfa19a4880c1dcbe4eed1984',
'00000dcab247410050e357158edc20555cc0110429023fdadb1d8cda3e06da5e',
  '0000a16968811cf75c33d877e99f460d396c46b5485f669c8e55b193b862106d' ]

The values ​​139355, 30720, 68789 and 51486 correspond to the nonces , ie the number of times the hashBloc method was executed to obtain a valid hash.

Boundaries

We have seen that the blockchain is based on known algorithms and simple to set up. This technology has revolutionized P2P data exchange , but there are still problems to be solved.

Transaction throughput

There is a limit in the amount of transactions that can be recorded in a block. We can therefore measure the number of transactions per second (tps) of the blockchain. Bitcoin has a tps count of 7 and Ethereum of 15 currently. The throughput is far too low for mass use, so there is a lot of research in this area. A reasonable goal to achieve is 10,000 transactions per second for global use and 100,000 for changing the world.

Transaction propagation

The propagation latency of a new block is as important as the throughput. It makes it possible to avoid a hard fork of the chain, that is to say that the chain is divided into two distinct chains. When making a purchase on the internet in Bitcoin, the merchant waits for several block confirmations to be certain that the transaction has been recorded on the correct chain. This process may take several minutes depending on the number of confirmations required.

Transaction fees

The limit on the block size of a public blockchain can cause an increase in transaction fees in the event of heavy use of a public blockchain. It is practical to be able to choose whether you want to pay a transaction fee of 10 cents or €1 to speed up the processing of your transaction, but when it comes to paying €40 to transfer €100, it is not sustainable. . The game Cryptokitties had increased transaction fees from $0.10 to $4 on Ethereum because it generated a lot of transaction.

Transaction storage

All transactions are stored on each node to keep the immutable side of the blockchain, so as the size of the node increases. In the long run, it will be more difficult to download an entire node, as it will take up the necessary space. The Bitcoin blockchain currently uses over 300 GB of disk space so this reduces the number of people who can participate in the decentralization of the network.

Conclusion

This presentation of the fundamentals of a blockchain will allow you to better understand the research of the development teams concerning the Blockchain. Do not hesitate to tell us in the comments if this article was useful to you and if you have any questions about certain parts so that we can complete the content.

Sources
https://dev.to/damcosset/blockchain-what-is-in-a-block-48jo
https://dev.to/damcosset/trying-to-understand-blockchain-by-making-one-ce4

5/5 - (1 vote)
SAKHRI Mohamed
SAKHRI Mohamed

The blog of a computer enthusiast who shares news, tutorials, tips, online tools and software for Windows, macOS, Linux, Web designer and Video games.

Articles: 3746

Leave a Reply

Your email address will not be published.