Diving Into Blockchain
Discover blockchain basics. Some repetition reinforces concepts. Dive in for a clear understanding.
The need of blockchain when we have banks?
They are the intermediaries
High transaction fees
Problem of double counting
Low security features therefore risking all the data
High international tansfer cost
Lots of documentation setting up
Not 24/7
Have limits
Centralised system
What is a blockchain?
An publically distributeed ledger (database) system secured by cryptography stored in immutable records called ‘blocks’.
Block
A record book consisting of the details of the transaction data. Usually contains 4 elements:
Hash of previous block
Transaction data
Nonce (a random number used once for generating the hash value of the block)
Hash of its own (An alphanumeric value used to identiify a block)
In the first block the value of the previous value is 000, its because it is the first block of the chain and is known as Genesis block and usually doesn’t have any value.
If anyone tries to tamper the values of the 2nd block, the prev hash value in the third block will appear to be different suggesting the block has been tampered. This technique helps to elimminate tampering.
How does blockchain works ?
Imagine a scenario of Alice sending money to bob.
Alice will make a request for transaction
The requested transaction is sent to peer to peer networ of computers called nodes
The transaction sent to nodes is verified by a set of people called miners
Once the transaction is is combined with other transaction to create a new block in the blockchain
Bob recieves the amount
The value can be any crypto, data or asset
Features of blockchain :
SHA ( Secure Hashing Algorithm) 256 (the number of bits taken in the memory) algorithm
Proof of work
Ditributed ledger
Public and private key
Mining
SHA 256 -HASH FUNCTION TAKES AN INPUT DATA AND RETURNS an alphanumeric output of 64 bits. The value returned by an hash function is hash vlaue. Even a minor change can change the whole value .
It is a one way function meaning that an input can produce an hash value as an output but the reverse is not possible. The hash value produced by the hashing algorithm is also known as digest.
Distributed ledger
A Blockchain is a public distributed ledger in which the digital data is recorded and verified by each node for preventing tampering of data. Among a network of nodes , few might be the miners who verify the transactions for which they are then rewarded.
Only a valid transaction is propogated across the network while an invalid transaction will be discarded at the first node which recieves it.
Public & private key
Private key is a key present with the user and public key is the one which is derived from the private key itself but is shared with everyone.
The verification of the transaction is as follows:
The documents are pass through an sha256 function and a hash value is then generated.
The output is then passed htrough a signature algorithm with the user’s private key
The hash value and the user’s private key is used to generate an digitally signed document which is then
Floated on the network with my public key and
Once verified by the miners , the transaction is then included into a block.
POW (Proof Of Work)
It is the process to to determine a number (NONCE) along with a hash algirthm to produce a hash value lower than the predefined target.
In order to determine the nonce, the miners need to try about 20.6 quadrillion nonce values to get a valid hash. This is where all the computing power is used and required for.
So how does it work?
Transaction data is distributed across the users of the Bitcoin network
Miners will validate the unverified transactions and add them to a block
To do so, miners compete to solve a difficult mathematical puzzle based on cryptographic hash function known as proof-of-work
The first miner who solves the puzzle gets rewarded
The verified block is then added to the blockcahin
Here the miners use the NONCE value to generate an Hash value less than the target , if it is so then the puzzle is solved and the miner is rewared but if not the miner will repeat to create a hash value.
Notes;
In the bitcoin network the block target/ the predefined target is adjusted after each 2016 blocks
On an average of 10 mins a new block is mined
The difficulty of a puzzle is maintained in such a way that it never deviates too much from the average time
taken to mine a block.
Transaction pool ; Here transactions are stored until they get verified into the new block. Miners keep listening to it for new verifications.
Candidate block ; Is the current block which has not been yet verified and does not have a valid POW.
Mining :
In Blockchain, when the transactions contained are considered confirmed, a new block is added to the existing Blockchain and the Bitcoin concerned in the transactions can be spent
The miner who solves the puzzle gets a reward of 6.5 Bitcoins
The amount of Bitcoin rewarded for each block added to the Blockchain is halved for every 210,000
blocks (approx. every 4 year). This process is known as HALVING
To see SHA256 in use:
https://andersbrownworth.com/blockchain
Byzantine fault tolerance problem;
Suppose there is a general with three of its lieutenants trying to attack a village.
The general has to ensure that all the lieutenants recieve the same message of either to attack or to retrieve . So he sends the message to attack , but there was a traitor among those three lieutenants, and he spread the wrong message to other three to retrieve which could create a dangerous problem.
To tackle this the general asked the lieutenants to send their nearest crew to share the same message as recieved by the general. This would help to identify the danger and would create a majority based sysetm ensuring zero fault occurence.
In the field of blockchain this falut tolerance is achieved wiht the help of Proof Of Work.
But what if two blocks are added at the same time?
If this situation somehow appears to happen, to 50% of the network miner 1’s block will be considered and to other 50% miner 2’s block eill be considered. But if any other miner adds another block to miner 1’s block, then miner 1’s block will be considered to be valid.
This situation is also called Accidental Fork.
What’s a fork??
A fork takes place when a divergence or split takes place in the blockchain into two potential paths.
This usually occurs when the users of a network cannot come to an agreement with regards to :
A network’s transactional details
New rules to validate transaction
Types of fork:
Soft fork ; This occurs when a change in software protocol makesnew blocks added to the blockchain (following new rules) backward compatible . It also requires amjority of the users to commit the change to be succesfull.
Can be used for:
tighter rules
cosmetic changes
adding functions
not affecting the functions
A scenario:
“If the block size is to be reduced from 1 mb to 100 kb”
The old blockchain will be working on the old version with 1 mb blocks but when approved, the new chian will accept 100kb blocks and will add to that chain only.
Over time, people following the older version of the Blockchain would be forced to move to the new one, since none of their transactions would go through.
Hard fork ; This involves a change in the software protocol so radical that it is forces to create a new blockchain .
To deploy a smart contract
Npm is the node package manager, a package manager for javascript
*g is to install the package globally on your system * truffle is used for smart contract, deployment, testing, project management and much more.
*ganache-cli (ethereumjs-testrpc is deprecated now and ganache is used) is used for etherium development. It is used to create and manage local ethereum blockchain development for testing purposes. Provides a local ethereum blockachain environment that runs entirely on your system.
*mkdir rating will create a directory (a file) with name ‘rating’.
*truffle init initiallizes a new project by setting up the basic directory structure and configuration files needed for Ethereum smart contract development
Cryptocurrencies
A long ago there was only barter system that took place
“You give 5 apples I give 5 oranges, DEAL!”
But it had many problems, what if the other person does not want orange? What if they get rotten after sometime? Who is to blame?
After sometime came gold and silver coins, they also had many problems, different place different value of gold and silvers , difficulty in transactions.
Then came currencies like paper notes & coins which did solve many problems but they too have many problem, what if water got spill on them, what if there was a fire break, counterfeiting(fake notes) and much more.
Came with a rise, the digital wallets ( Paytm, apple pay, g pay etc) . Seems to solve almost every problem right? Hehe, no.
Since everything is centralised i.e. controlled by banks, what if while transferring money the banks server got hampered? What if there is a technical issue at the bank? The user’s account got hacked? TRANSFER LIMITS!!
This is where the future of currency lies with. CRYPTOCURRENCY.
No limits
Accounts cannot be hacked
Pure privacy
No central point of failure since this is a decentralised system
How many cryptocurrencies are there then ?
More than 10000+.
A proper definition:
A cryptocurrency is a digital or virtual vurrency that is meant to be a medium of exchange.
Same as usual currency but does not have any physical form, also uses cryptography. It can be used to easily verify transfer of funds. Decentralised.
Little to no transaction cost
24/7 access to money
No limits on purchases and withdrawals
Freedom for anyone to use
Faster interantional transactions
‘ Crypto ‘ refers to cryptography which is a method of using encryption and decryption to secure communication in the presence of third parties with ill intent.
It uses methods such as :
computational algorithms such as SHA256
Public key (Shares with everyone)
Private key (Acts like a digital signature)
Two of the king pins among the cryptocurrencies:
Bitcoin - Bitcoin is a form of digital currency and is decentralized without a central bank. It uses blockchain to perform transactions on a peer-to-peer network.
Transactions are manual.
Takes 10 minutes to perform a transaction
Used like money for real world transactions
Limit to how many bitcoins can exist [21,000,000]
Used for transactions involving goods and services
Uses SHA 256 for hashing (the process to obtain the password of block)
&. Ether. - Ether is a currency that's accepted in the Ethereum network. Ethereum works on blockchain technology to create an open source platform to build and deploy decentralized applications
Transactions are manual or automatic
Takes about 20 second to finish a transaction
Ether is used to power the ethereum network and power real life transactions
Ether is expected to be continuous but not expected to exceed 100,000,000
Uses blockchain to create a ledger that triggers a transaction when a comsition is met
Uses ethash algorithm for hashing.
Ethereum
A blockchain based distributed computing platform that enables developers to build and deploy their decentralized applications.
So basiically a platform where developers can build and deploy their DApps (decentralised applications)
Features of ethereum :
Cryptocurrencies
Smart contracts
Ethereum virtual machine. (EVMs)
DApps
DAO (Decentralised autonomous applications)
Cryptocurrency :
Ether (eth) is a cryptocurrency that runs on ethereum network. Used to pay for the computational resources and transaction fees on the ethereum network.
Peeer to peer technology.
It is also used to buy GAS which is used to pay for computation.
[Gas is the execution fees paid by a user for running a transaction for running a transaction in ethereum]
Ether can be utilized for building decentralised applications, smart contracts and making standard peer to peer payments.
Smart contracts :
A simple computer program that facilitates the exchange of assets, money, shares, property etc.
It contains the terms and conditions of a mutually agreed contract between the peers.
Once it is executed it cannot be altered.
For the verification process, smart contract is carried out among anonymous parties of the network without the need of a central authority
It provides transfer for currency or asset in a transparent and trustworthy manner.
EVM is a runtime complier to execute smart contract code.
An example of what happens when a smart contract is made.
EVM
A virtual machine desogned to operate as a runtime environment for ethereum based smart contracts.
An engine which understands the language of smart contracts which are written in solidity language for etthereum.
EVM is operated in a sandboxed environement (isolated from the main network). This is a perfect testing environment.
Any language in the smart contract is compiled into ‘bytecode’.
This bytecode can be read and executed using the ethereum feature called ethereum virtual machine
EVM guarrantees security by preventing cyber attacks.
Proof Of Stake
In Ethereum, a process called proof of stake was created as an alternate to proof of work
It was created as a solution to minimize the use of expensive resources spent in mining
In proof of stake, a validator can validate the transactions based on the amount of crypto coins he/she holds
Ethereum virtual machine - Gas
Like a car needs fuel in the same way, to run an application on ethereum network we need gas.
To perform any transaction on ethereum network a user has to make payments (to the miner ) in ether via an intermediary token called ‘gas’.
On ethereum network, gas is a unit that measures the computational work required for running a samrt contract or other transactions
How is the gas fees calculated:
Ether = Tx fees = Gas limit * Gas price
Gas limit- on ethereum network, a gas limit refers to the amount of gas used for the computation
Gas price- the amount of ether a user is required to pay
Gwei is the measuring unit of gas price
If a user provides less amount of gas to run a particular code or operation, then the process will fail with an error message of “out of gas fees”
How is ethereum’s mining different from bticoin’s mining ?
Bitcoin | Ethereum | |
Hashing algorithm | SHA-256 | Ethash |
Time taken to mine | 10 min | On average of 12-15 seconds |
reward | 6.5 BTC | 2ETH |
Usd 16/2/2024 | 1 BTC = 68241.50 USD | 1ETH= 3691.30 USD |
Decentralized Applications :
How does a normal app works?
How do DApps work?
This time the page will call a SMART CONTRACT to access your personal data from the blockchain
A Dapp consists of backend code that runs on a distributed P2P network.
It is a software designed to work on an Ethereum network without being controlled by a centrallized system.
It provides a direcct interaction between the end users and providers
An application qualifies as Dapp when it is open sourced and uses tokens(Acts as a fuel for the Dapp to run).
Decentralized autonomous organizations (DAO)
A digital organization that aims to operate without the hierarchial management.
Basically an organisation where the decision making is not limited to some top level management but in the hands of some designated group of people as a part of authority.
It exist on the blockchain network where it is governed by its protocols and rely upon smart contracts
All decisions are made through smart contracts or voting system.
HOW does it work ??
people add funds to the DAO as it requires funding in order to execute and make decisions
Based on that each member is given a token which represents the percentage of shares in the DAO
These tokens are used to vote in the DAO where the proporsal status is decided based on maximum votes.
Applications of Ethereum :
voting system
Banking system
Shipping
Agreements
Why smart contracts than traditional way?
no third party
Fast execution time
Remittance are automatic. (If any amount is to be transferred, it happens immediately)
Full transparency
Archiving (traceability)is easy
High security through cryptographically public and private keys
Cost is cheap
Digital signature
What are they?
Self-executing contracts which contain the terms and condition of an agreement between the peers. The t&c are written in the code itself. It executes in blockchain’s decentralized platform. These agreements facilitate the exchange of money ,shares ,property etc.
Advantages of smart contracts.
No intermediaries
Automated
High speed
Secure
High accuracy
What is a bitcoin?
The first decentralized digital currency that allows users to transfer money peer to peer without an intermediator (banks, governments etc.) using blockachain technology.Created by satoshi nakamoto
The evolution of Bitcoin mining ;
In the early days people used to do mining on theirr cpus and it took a lot of time even though the difficulty was less.
After sometime it was discovered that GPU’s are also good for mining but require very high electricity consumption
To overcome the problem a hardware device known as ASIC (application specific integrated circuit ) was introduced for mining which consumes less power and is the fastest hardware for mining.
Miners are profitable only when their cost of resources to mine one block is lower than the price of the reward they recieve.
What is a mining pool?
A process where multiple nodes share their resources together to mine a block. When a problem is solved the miners split the reward equally based on the amoint of processing power.
Sharding :
Sharding is a scaling technique used in blockchain networks to improve their throughput and scalability by dividing the network into smaller, more manageable subsets called "shards." Each shard operates as an independent blockchain network, capable of processing transactions and executing smart contracts on its own.
Blockchain wallets :
A blockchain wallet is a cryptocurrency wallet that allows users to manage cryptocurrencies . These helps in the exchange of funds , transactions are secure, privacy is maintained, accessinle through mobile and web browser. It is just like a PayPal account but uses cryptocurrencies.
Examples of blockchain wallets:
Electrum
Jaxx
Samurai
Mycelium
Bitcoin paper wallet
How blockchain wallets works?
Uses public (The one shared with everyone) and private (kept secret with you) keys.
Types of blockchain wallet ;
Hot wallet : are like normal wallets which we carry for day to day transactions. User friendly wallets. Online walletsthrough which cryptocurrencies can be transferred quickly. Private keys are stored in the cloud for fast transfer. Easy to access but have unrecoverable theft when hacked.
Cold wallet : are similar to a vault where cryptocurrencies are stored with a. High level of security. Digital offline wallets where the transactions are signed offline and later disclosed online. Private keys are stored in a hardware or a paper document. This method helps in protecting the wallet from unauthorized access and other vulnerabilities.
Can further be ditinguished between ;
software wallets : A software wallet is an application that is downloaded on a device (either desktop or mobile) and accessed online.
- Desktop wallets : cold wallets in which the private keys are stored in cold servers
- online wallets : hot wallets that run on the cloud
- mobile wallets : similar to online wallets except they are built for only mobile phone usage
Hardware wallets : A hardware wallet is a type of cold storage device which stores the user's private key in a protected hardware device
Paper wallets : an offline process of storing cryptocurrencies (your public private keys) bitaddress.org
Some industries blockchain will distrupt :
Banking
Cyber security
Supply chain management
Healthcare
insurance
Transport
Cloud storage
Real estate
Government (elections)l
What job can you acquire?
core blockchain developer/ blockchan architect : managed the architecture of the network,, supervise blockchain network,, works on consensus algorithms,, sets up blockchain protocols
Blockchain software developers : creates smart contracts,, develops distrivuted applications,, works on front-end and back-end app development.
What is a merkle tree?
A data structure which is used for verifying a block. It is in a form of binary tree containing cryptographic hashes.
List and explain the parts of the EVM memory..
Storage : storage values are stored permanently on the blockchain network.Truly expensive
Memory : a temporary modifiable storage. Can be accessed only during contract execution. Once the data execution is finished, its data is lost
Stack : temporary and non modifiable storage, very cheap
51 % attack.
In Blockchain, 51% attack refers to a vulnerability where an individual or group of people can control the majority of the mining power (hash rate).
This would allow the attackers to prevent new transactions from being confirmed. Further, they can double spend the coins
In 51% attack, smaller cryptocurrencies are being attacked
SPDX-License-Identifier
Software package data exchange is used to indicate the license under which the code is distributed. It is a standard format for communicating and documenting software licenses and copyrights.
DeFiLlama
Is a website/app that gives insights, provides information and analytics about various DeFi protocols and projects.
TVL (Total Value Locked) ; refers to the total value of assets locked or deposited in a decentralized finance (DeFi) protocol. It represents the sum of all assets (cryptocurrencies, tokens, etc.) that users have deposited into the protocol's smart contracts for various purposes like lending, borrowing, providing liquidity, and more.
Traded Value ; it represents the total trades and transactions that take place within a specific period. It represents the liquidity and activity in the market and is often used to measure the level of trading activity and interest in a particular cryptocurrency or token.
Liquidity : Liquidity refers to the ease with which assets can be bought or sold in a market without significantly affecting their price.
APY(Annual Percentage Yield) ; a metric used to calculate the annualized rate of return on an investment, taking into account the effect of compounding
ERC’S ;
ERC stands for Ethereum Request for Comments. It is a formal process used to propose improvements, standards, and technical specifications for the Ethereum blockchain and ecosystem. It's a way for people to propose ideas or standards for the Ethereum blockchain. Think of it like suggesting improvements or new features for Ethereum.
Why do we write them? People write ERCs to share their ideas with the Ethereum community. They describe things like new token standards, smart contract patterns, or protocol improvements.
How does it work?
Someone comes up with an idea for how Ethereum could be better.
They write up their idea in an ERC and submit it to the Ethereum community.
Other people read the ERC, discuss it, and suggest changes or improvements.
If everyone agrees that the idea is good, it can become an official Ethereum standard.
Why does it matter?
ERCs help Ethereum evolve and improve over time. They're like a way for the community to collaborate and make Ethereum better for everyone.They provide guidelines and standards that developers can follow, making it easier to build things that work well together on Ethereum.
Fungible Tokens/ERC 20 ; A technical standard used for fungible tokens on the Ethereum blockchain.
Fungible tokens are digital assets that are identical and interchangeable with each other, similar to traditional currencies or cryptocurrencies like Bitcoin or Ether.
What key features and components does it provide :
Token name
Symbol
Decimals
Total supply
Balances
Transfer
Transfer from
Allowances (how many tokens are to be transferred )
Events (notifying external apps and users about the token transfers)
NFT’s (non fungible tokens) / ERC 721 ; a standard interface for non-fungible tokens (NFTs) on the Ethereum blockchain. Unlike fungible tokens (such as cryptocurrencies), which are interchangeable and have identical value, NFTs are unique digital assets with distinct properties and ownership records. The ERC-721 standard defines a set of rules and functions that NFT contracts must implement to enable the creation, transfer, and management of non-fungible tokens.
What key features and components does it provide :
Unique identifiers
Ownership and transfer
metadata
Approvals and authorizations
Enumerable and non-enumerable tokens
Event notification
ERC 1155 :
ERC-1155 is a standard for creating and managing both fungible (identical and interchangeable) and non-fungible (unique and distinct) tokens on the Ethereum blockchain. It was proposed as an improvement over existing standards like ERC-20 (fungible tokens) and ERC-721 (non-fungible tokens) to provide greater flexibility, efficiency, and scalability for tokenization use cases.
URI (Uniform Resource Identufier ):
a string of characters used to identify a resource on the internet, such as a web page, a file, or a service. A URI consists of a Scheme and a path. It consists of two sub types
URL (Universal Resources Locator)
URN (Universal Resource Name)
Layers in blockchain :
Layer 0 :Blockchain in itself is called layer zero. The components required to make blockchain real are the internet, hardware, and many other connections. Layer zero blockchain is the initial stage of blockchain that allows various networks to function, such as Bitcoin, Ethereum, and many more. Layer 0 also provides blockchain with a facility of cross-chain interoperability communication from top to different layers. Layer 0 provides the underlying infrastructure for blockchain.
Layer 1 : Layer 1 blockchain is an advancement in layer 0. Under this layer, the blockchain network is maintained functionally. However, scaling is a limitation in the layer one blockchain. Any changes and issues arising in the new protocol in layer 0 will also affect layer 1. It is also called an implementation layer. Examples of layer one blockchains are Bitcoin, Ethereum, Cardano, Ripple, etc.
Layer 2 : Layer 0 has many interactions that have been removed by layer 2. For specific blockchains, layer 2 blockchain is the scaling solution. It works with third-party integration and removes the limitations of layer 1. It is the most popular approach for solving scaling issues attached to POW networks. At present, various industries have begun implementing layer two technologies.
Layer 3 : Layer 3 blockchain is also referred to as the “application layer”. The main task of this layer is to host the DAapps and many other protocols that enable other apps. Here, the blockchain protocol is split into two significant sub-layers, that being, application and execution. It is the most potent solution made to separate blockchains with cross-chain capabilities for achieving the target of real interoperability.
Blockchain scalability :
Blockchain scalability is the ability of the network to support the increased load of transactions and nodes in a particular network. In the blockchain, transactions per second are recorded. Day by day, we are witnessing new advancements in blockchain technology; With these advancements, transactions are also increasing per second. That’s why it is called blockchain scalability.
More to come..