Blockchain Consensus Mechanism
Tags: web3, consensus, blockchain, ethereum
Published: 2024-02-02 16:50:25

## Consensus mechanism:
- A consensus mechanism is a algorithm or protocol used by nodes in a distributed system to reach agreement on the state of the system. 
- In a blockchain, the consensus mechanism is used to determine which transactions will be included in the next block of the ledger and to prevent conflicting transactions from being included.
- A `consensus protocol` is a process used to achieve agreement between participants of a distributed network.

## <u>Proof Of Work (PoW):</u>
Yes, it means what it sounds like, showing the proof that you have done the work. As we know mining is basically solving a complex mathematical problem that requires high computational power. 
 - At a time when many miners compete to mine a block, the node that wins the race has a proof of work of spending energy and resources and hence it’s rewarded when the block is verified and added to the chain. 
 - If the node tries to perform malicious activity, the block will not be verified by other nodes in the network and the miner doesn’t get the reward, which is a total waste of its resources and time. 
 - `Bitcoin works on PoW`, while `Ethereum is using Proof of Stake`. Proof Of Work requires a lot of power as many miners try to compete to mine a block, Proof Of Stake is a better alternative.  

## **Facts about PoW:**
- Bitcoin has around `2700 transactions` in a block after `10 minutes `which is around `4/5 TPS`. (7–19 minutes to create a block, i.e., an average of 10 minutes).
- There is a `14-day` maximum hold period for transactions in the mempool. Higher transaction fees are used in the mempool to replace lower transaction fees. You'll need to resend the transaction again after that because it will be removed from the mempool.
- Once a transaction is added to the blockchain, it will wait for `6` more blocks to be added to the same blockchain for confirmation and to become irreversible.
- In every `2 weeks`, the bitcoin blockchain checks the average time for the last two weeks. Based on this, the difficulty level was adjusted to make the average mining time per block 10 minutes.
- The bitcoin blockchain looks up the average time spent in mining a block over from previous two weeks. To make the average mining time per block 10 minutes, the difficulty level was adjusted in light of this.
- In `10 minutes, 1 block mined` => In `2 weeks = 2016 mined blocks`. So, the difficulty level for miners is adjusted after every `2016 blocks (after 2 weeks).`
- After `210000 blocks`, or every `4 years`, Coinbase awards will be divided in half. In 2013, 50 bitcoins were given to miners for successfully mining a block then after `4 years it was 25 then 12.5 and now it's 6.26`. This is known as halving. 4-year halving cycle.
- Since miners get fewer rewards, the price of bitcoin will increase. Miners control the circulation of bitcoin price.They'll sell the bitcoin at a higher price to get the benefit.
- The price of bitcoin will rise since miners receive smaller rewards. The price of bitcoins is determined by miners. To earn profit, they will sell the bitcoin for more money. Miners control the circulation of bitcoin price.
- Reward: Coinbase/Mining Reward `(6.25 BTC) + Transaction Fee (1-2 lakh)` Reward points will be distributed to miners; however, they won't be able to use it for another `16 or 17 hours`, or until the next `100 blocks` are created. (also known as Maturity of Coinbase)
- Original Bitcoin network, commonly known as `bitcoin cash`, was forked in order to extend the block size from `1 MB to 4 MB`, allowing for the addition of more transactions. Each Block size: `1 MB`, after forking: `4 MB`
- Bitcoin uses/follows the longest chain in operation.
- `wallet = public key + private key.` Hierarchical deterministic wallet: HD wallet (uses different keys for each transaction)
- `Bitcoin address = SHA256(public key)`
- Transaction hash: To determine the final transaction hash, find the hash of each transaction and apply the merle tree. The block hash will be determined as follows: `block no + nonce + transaction hash + timestamp. `

### Drawbacks of PoW: 
- There is only one blockchain i.e. no sharding concept available.
- Too much energy consumption: `Bitcoin annual mining = Argentina's electricity`
- Network Congestion (NC): When the network consumption is high, the dynamic gas price kicks in and vice versa, resulting in the extended block confirmation time. Also, it takes longer time to add transactions from Dapps with significant network consumption in the blockchain.

## <u>Proof of Stake (PoS):</u>
- Ethereum 2.0: POS: POS based Ethereum blockchain (Also known `Serenity` or `Beacon Chain`). Has PoS consensus & Shard chains.
- In POS, there are no miners. They are referred as `validators` rather than miners. In order to be a validator on the Ethereum network, one must stake `32 ETH`. 
- Groups of people can invest money in liquidity pools, also known as staking pools, until they reach 32 ETH and become validators. 
- 32 ETH will be locked in for a brief period of time, and the blockchain software will serve those as a validator. Liquidity pools can be found in Dapps. A liquidity pool can be a Dapp.
- Geth: GO implementation of the ETH, store private/public key.
- These three types of software must be installed. (Part of GETH): (POS architecture)
     - `Execution client`
     - `Consensus client` (consensus: voting and reaching agreement)
     - `Validator Client`
- Once 32 ETH are deposited (blockchain software will be activated), a validator joins a queue where others are waiting to be validators.

####Adding new blocks in PoS: (How blocks added in POS)
- Beacon chains have `slots` and `epochs`.
- There is a data structure that has `32 partitions`. Each partition is called a `Slots`. The combination of `32 slots` is called an `Epoch`.
- All of the `slots are capable of taking transactions`. They are representations of proposed blocks. Slots are the intermediate state of a block.
- A transaction can be proposed in any slot by the validator who wishes to add a block to the Ethereum blockchain. To add these blocks, individuals or validators are selected at random.
- In POW, the miner with the best hardware mines the transaction. On the other hand, POS uses random selection. When a block is inserted, only one validator will be selected at a time to validate that.
- The amount of ETH staked, was chosen as a validator, based on probability. The more, one stake the ETH, has greater chance of becoming a validator.

####PoS committees: (128 committee members/attester)
- There will be at least `128 committee members` (who are also randomly selected as validators) and `1 proposer`, or `validator`, who will be picked at random to add blocks or transactions to the blockchain, for each slot. Each of them also staked at least 32 ethers.
- `Committee members' responsibility is to verify if a transaction or block added by the proposer or validator is malicious or legitimate`. In this case, the majority needed to confirm a certain slot is `2/3 = 66% `(committee members).
- Therefore, each time a validator is selected at random from that queue, `128 other validators are selected at random for every slot` so that committee members can validate one transaction or add one block. For all `32 slots in a single epoch, the same event occurs for every slot`.
- There will be `12 seconds for each slot`. The duration of the entire `epoch is 6.4 minutes`. No vacant slots are uploaded to the blockchain.
- If the proposer is unable to add a transaction to the slot, Beacon Chain will penalize them. A portion of the Ethereum staked will be burnt. The procedure will use up some of the 32 ethers.
- It will burn some of the stake if it commits fraud. (`1% Stake`).
- The Ethereum blockchain has a list of active validators. If any malicious activity found by a validator, Ethereum will remove it from the blockchain network.
- The `checkpoint` will reverse any newly added slots or blocks to the blockchain in the event that any fraudulent transactions are found.
- The `first slot in each epoch serves as a checkpoint`. It will function as the approved or finished version of the blockchain. The last accepted state of the first slot is based on the voting of committee members, that will roll back to the last checkpoint in case of fraud transactions.
- `Genesis Block = Slot 0 + Epoch 0`. Every epoch is meant to reach finality.  A maximum of` <=32 slots` can be present in an epoch. Epoch's function is to strengthen the blockchain's security by introducing checkpointing.
- Batches of `32 blocks` are uploaded to the blockchain. One slot equals one block, and every block contains a unique collection of transactions.
- Each epoch's validator task is as follows:-> (for 1 slot)
    - `Randomly selected to propose a new block`.
    - `In order to approve the transaction, a committee member was arbitrarily selected to vote`.
    - `To confirm the signature of the transaction, i.e., the public key and private key, committee members will run the transaction through the slots once more`. They'll cast their vote when they've checked the signature. Verify the signature by comparing it with the proposer's signature.

#### `Notes: 1 Epoch = 32 Slots = 32 blocks uploaded to bockchain = slots can store transactions. 128 Committee members/attester for 1 proposer/validator. 128 other validators to propose transaction for each slot. 12 seconds for each slot. epoch is 6.4 minutes long.`

### Reward for Mining a block in PoS:
- `Base reward = validator effective balance * 2^6 / SQRT(Effective Bal. of all active validators)`.
- `Reward for POS: % of total staked Ethereum.` Rewards will be given for each slot.
- `One can be an attester or a proposer at any point in time in one epoch.` 1 task per epoch. Interest on the entire amount of ether staked will be given to you. 
- There is no mining in POS. The portion of ether that you get in return will be added to the overall amount of ether in circulation. 
- You can withdraw the staked ether only after a period of `1.5 years`.

#### Sharding in POS (also known as horizontal sharding): (Parallel blockchain: 15% faster transactions)
- There are `64 shard chains` and `1 beacon chain`. 
- 64 shard chains will each have a portion of the tasks. 
- Every shard chain will make reference to the beacon chain.
- Every single shard chain's data can be read by the beacon chain. 
- Hashing will be used in beacon chains to store the distinctive characteristics of shard chains. 
- The beacon chain is assigning tasks to the shard chains.

#### Drawbacks of Ethereum:
- Gas prices are high due to heavy network congestion.
- Scalability issues i.e. `13-15 TPS.`

#### Solution:
- Layer 2 scaling solution. It uses POS Consensus. A certain gas price changes each time a state is altered. Has some network throughput as well. (TPS).
- Layer 2 blockchain: They are of ERC20 type token. EVM compatible. E.g.: Polygon