Gas Optimization In Solidity: Strategies For Cost-Effective Smart Contracts
Gas is the “fuel” that powers smart contract execution. This article offers practical strategies for Solidity gas optimization.
🇺🇦 Hacken stands with Ukraine!Learn more
In a blockchain, consensus allows protocol layer nodes to independently agree on the ledger’s state. These mechanisms update the chain’s state and preserve its operational integrity, enabling decentralization without chaos.
All blockchains must maintain accurate records to function correctly. Unlike banks, blockchains don’t have any central authority to keep all the records. By contrast, all pears are equal in a decentralized network. Different blocks are broadcast simultaneously, and the network has to decide which chain to follow. A mechanism that determines which chain to follow is called consensus.
A consensus mechanism is what keeps decentralized networks secure. Nodes must agree on the current state before updating the blockchain. This automated process prevents errors and secures the network against threats such as double-spending or Sybil attacks, where malicious actors manipulate the network with fake nodes.
Distributed consensus is entirely automated, and it is executed as programmed. This way, users trust the technology, rather than a third party, for the integrity of a blockchain. As a result, the consensus mechanism’s logic and implementation must be flawless.
Bitcoin, the first mainstream blockchain, adopted the Proof of Work consensus mechanism in 2009. Thereby making Proof of Work one of the first consensus mechanisms. But other more innovative consensus algorithms have been introduced over time. This article will give you high-level insights into the following consensus mechanisms.
|Consensus Mechanism||Advantages||Disadvantages||Protocols Using It|
|Proof of Work||Decentralized Structure|
High Levels Of Security
Acceptable Levels Of Scalability
|High Block Time|
|Proof of Stake||Fast Block Creation Time|
Scalability (But Less Than PoW)
Independence to the Special Hardware
|Suffers From Centralization|
Lower Cost Of Misbehaving
|Delegated Proof of Stake||Scalability|
Highly Susceptible To 51% Attack
|Practical Byzantine Fault Tolerance||Energy Efficiency|
Susceptible To Sybil Attacks
|Proof Of Weight||Great Customization and Scalability|
Quick Transaction Confirmation
|Proof Of Capacity||No Special Hardware|
|Susceptible To Grinding Attack|
Space Privilege Applies
|Proof Of Authority||Transactional Speed|
|Proof of Importance||Sybil Resistant|
|Favors The Rich|
Proof of Work is one of the earliest consensus algorithms, which works based on game theory. Many popular blockchains adopted it, including Bitcoin, Litecoin, and Dogecoin. There are high-level computational tasks that miners have to do in discovering new blocks, called mining.
This is a simple illustration to explain how Proof of Work works:
Imagine there is a puzzle tournament and whoever solves it first wins the game. The grid was 9 x 9 at the start, but the organizers increased it to 27 x 27 as hundreds of people joined. Thus, making it harder to solve. Some of the participants developed custom machines to automate the solution. This will give them a higher chance of winning, right?
That is how Proof of Work actually operates.
Let’s break it down… Any miner who solves the computational problem first through repeated hashing can announce it to the network. The other nodes in the network can accept its validity or contest it when necessary. This is where consensus comes into play. Blockchains adopt various hash functions for their Proof of Work. For instance, Bitcoin uses SHA-256. Besides facilitating the algorithm’s operation, mining also contributes to the security of PoW protocols. It makes attacks difficult because the attacker must expend a large cost, which can be quite unprofitable on their part.
The level of mining difficulty gets higher depending on the amount of computational power the miners have to solve the nonce. The Proof of Work mechanism rewards whoever discovers a valid nonce among the miners. Due to its economic benefit, many miners run the computational race of mining blocks. Even though discovering valid nonces is difficult, confirming if a block was validly added is easy.
Decentralized Structure. The operational power in PoW is evenly distributed across various people. Anyone can become a node operator and mine blocks so far they have the resources and time. The even distribution checkmates the possibility of having a certain group of people dominate the blockchain for selfish reasons. No central authority can control a PoW blockchain.
High Levels Of Security. PoW blockchains are extremely difficult to manipulate. First, attacks such as 51% are practically impossible because no single person or group can have the computational power to take over more than half of the network. Bitcoin, one of the leading blockchains using PoW, has never been hacked. This itself demonstrates the high-level degree of security that PoW provides.
Acceptable Levels Of Scalability. Blockchains must be scalable to speedily serve more users without being costly. Although many PoW blockchains do not have an extremely appealing level of scalability, they are fair enough. The advent of scaling solutions made it easier for PoW blockchains to become fast, cheap, and cater to millions of users.
High Block Creation Time. PoW blockchains require longer periods before a new block can be mined, especially when the block difficulty increases. This causes slow transactions and, ultimately, a bad user experience.
Energy Inefficiency. PoW consensus requires node operators to have some hardware. This hardware is energy-intensive to operate. Research shows that the amount of energy Bitcoin uses in a year is higher than the annual power usage of Norway. This, among other reasons, was why popular blockchains like Ethereum migrated from PoW to PoS.
Special Hardware Dependency. PoW is unlike other consensus mechanisms regarding hardware requirements. The hardware includes Raspberry Pi and other mining machines. These special hardware dependencies limit how easily anyone can become a miner and active in the consensus schemes. Most other consensus mechanisms only require a PC, storage device, and other general hardware.
High Computational Cost. PoW generates high computational costs from two perspectives – setting up and operation. Hardware for setting up mining on PoW blockchains is relatively costly. For instance, a Bitcoin Miner costs over $1,700. That said, PoW requires too much power to operate, and this can also be costly.
Extensive Bandwidth Requirements. There are some specific bandwidth requirements to meet in a PoW blockchain:
These requirements are difficult to meet in some countries, disenfranchising those living there from participating in the consensus.
Proof of Stake is a consensus algorithm where validators lock up some specified amount of native assets to secure the blockchain. It was developed as a better option for PoW. In 2022, Ethereum dropped PoW for PoS because it is more energy-efficient and decentralized. Other prominent blockchains, such as Tezos and Cardano, also incorporated PoS into their protocols.
In DeFi, staking means locking up assets to get rewards over time. The PoS mechanism demands validators to lock up their native assets in a smart contract. Therefore, protocols utilizing the PoS mechanism must ensure their smart contracts are secure.
Each validator can create and propagate new blocks. At the same time, they are responsible for ascertaining the validity of any new blocks their peer broadcasts. They stand a chance to lose their locked assets if they act dishonestly.
PoS Flow. Source: “Deconstructing Blockchains” (Natoli et al., 2019)
Notice that the punishment for dishonest validators in PoS and PoW are similar. But the validators lose staked assets in PoS, while in PoW they lose the money spent on hardware and power.
Fast Block Creation Time. Unlike PoW in Bitcoin, where block creation can last up to 10 minutes, PoS systems create new blocks within seconds. This makes transactions faster.
High Throughput. Since PoS has a faster block creation time, it can process more transactions quickly.
Energy Efficiency. PoS is way more energy efficient than other computational-intensive models such as PoW. In fact, research confirms that PoS uses 99% less energy compared to PoW. The validators do not need to solve any puzzle; the algorithm will pick them to validate based on their staking power.
Scalability (But Less Than Pow). PoS is a scalable consensus algorithm that can handle increasing transactions without compromising speed. However, it is less scalable than PoW.
Independence To The Special Hardware. Becoming a validator in Proof of Stake is easier because it requires no special hardware. Apart from staking, the prospective validator only needs a CPU and storage devices. The lowered bar of entry encourages more participation.
Suffering From Centralization. There can be centralization in a PoS setting since the major criterion is having enough native assets to stake. If a person or group of people can get a lot of native assets and become validators, they can influence the consensus sessions of the blockchain.
Lower Cost Of Misbehaving In Blockchain Networks. Some PoS blockchains are relatively inexpensive to set up. As a result, the validators do not have so much to lose in case they are sanctioned for misconduct. For example, a prospective validator on Cardano must stake a minimum of 25,000 ADA, which is only around $9,600.
Daniel Larimer adapted the PoS mechanism to design the DPoS model in 2014. Popular blockchains such as Cosmos and Tron use a variation of PoS called DPoS. Not all who lock some specified amounts of native assets can become validators. Instead, some selected delegates—better called “witnesses”—perform the decision-making on behalf of the others.
The stakers have the power to elect the witnesses to represent them. In case of misconduct, the stakers can also vote to technically “impeach” them. The DPoS has a democratic outlook and design.
Scalability. DPoS is a more scalable mechanism because there are a few witnesses, thereby fast-tracking the decision-making process. The mechanism can also handle a larger number of transactions so easily.
Energy-Efficiency. Being a variation of Proof of Stake, the DPoS mechanism requires no computational power whatsoever. The witnesses mine blocks based on the staking wealth. It is energy efficient and environmentally friendly.
Low-Cost Transactions. Consensus mechanisms like PoW are often congested, so payees have to incentivize the miners. But DPoS is a fast consensus model that is also cheap to carry out.
Semi-centralization. One of the most critical arguments against the DPoS mechanism is its pro-centralization approach. The few selected witnesses already form an informal centralized council. This outlook is arguably unfit for decentralization and more suited for private blockchains.
Highly Susceptible to 51% Attack
The semi-centralized nature of DPoS makes 51% attacks easier to carry out. The selected witnesses can connive to make malicious decisions or even stop the chain from running.
The Byzantine Generals Problem describes the complexity of reaching an agreement if there are disloyal generals. The pBFT consensus mechanism is a secure model that can withstand dishonest validators. It reaches a consensus when there is ⅔ agreement from the honest nodes. Hyperledger, Fabric, and other prominent blockchains are utilizing this mechanism.
However, the security of pBFT will be breached if the dishonest nodes are more than ⅓ of all the nodes in the network. The nodes in pBFT are divided into primary and secondary nodes. The primary nodes are the leader nodes, while the secondary nodes are the backup nodes. The primary nodes are changed at every consensus round.
Energy Efficiency. pBFT does not require any power consumption or high-level computational power, unlike PoW. This enhances its efficiency and makes it easier to run.
High Throughput. pBFT mechanisms can handle high throughput conveniently as the nodes quickly interact and validate transactions. The decisions of the nodes are final, so there is no need for block finality confirmation. Disputes among the nodes are also resolved quickly in case they contest the validity of any block.
Not Scalable. pBFT was primarily designed for not-too-large blockchains. Thus, it is not scalable for larger blockchains due to the intense back-and-forth communication among the nodes. As the number of transactions increases, it will take more time to agree on and approve them.
Susceptible To Sybil Attack. A typical Sybil Attack occurs when a single person or group is in charge of several dishonest nodes in the network. If the dishonest nodes are more than the honest nodes, they can manipulate and take over the chain.
Six MIT researchers, led by Yossi Gilad, developed a consensus for the Algorand blockchain. Their prime motivation is discovering an algorithm model that solves the Byzantine Generals’ Problem. They discovered a consensus algorithm based on weight fraction and christened it Proof of Weight.
Each user in this mechanism exists in weights, and how much they have in their accounts determines their weight. The algorithm picks committee members randomly among the users based on their weight. This randomness checkmates the possibility of having one or many dishonest users. Honest users must have up to ⅔ of the total money in the network. Otherwise, dishonest nodes can take over.
Although the design of PoWeights might look similar to PoS, each is different. The users only have to have tokens in PoWeights and do not need to lock or stake them.
Great customization and Scalability. PoWeights is a consensus template that any protocol or blockchain can adapt to fit more into their architectural designs. Filecoin, a popular storage protocol, utilizes the PoWeights consensus mechanism but in a different dimension. It weighs its users based on the amount of data they have and calls it Proof of Spacetime. This demonstrates how creative blockchains can customize this consensus mechanism.
Quick Transaction Confirmation. Only the committee members, and not all users, determine transaction validity. This speeds up the speed of confirming transactions on PoWeights blockchains.
Energy Efficiency. Proof of Weight does not demand power consumption. Instead, all it requires is that the users have the native assets in their wallets.
No Incentive. Proof of Work, Proof of Stake, and other algorithms reward the network participants for keeping the network running. But this is not the case with Proof of Weights, the committee members receive no reward for validating transactions.
Semi-centralization. The committee members become centralized in a way that is against blockchain’s decentralization ethos. They can become dishonest and cheat the users.
PoC Flow. Source: “Deconstructing Blockchains” (Natoli et al., 2019)
Another popular name for Proof of Capacity is Proof of Space. Stefan Dziembowski and Sebastian Faust formally introduced it in 2015. Burstcoin was the first project to utilize this algorithm.
Miners need to prove that they have the storage capacity to mine crypto. The most recommended storage device in the instant case is a hard disk. The miner needs to get ready before the mining kicks off. They get ready by plotting nonces. A miner can only create as many nonces as they have space for. The network frequently broadcasts puzzles. Any miner who has the closest hash in their nonce wins the puzzle.
No Special Hardware. Proof of Capacity is easy to set up. A prospective miner only needs to get hard disks and plot nonces on them. No need for sophisticated devices. In fact, hard disks work better than special hardware like ASICs.
More Decentralized. Almost everyone has a chance to become a miner in PoC because hard disks are cheap. This friendly accessibility leads to more decentralization because everyone gets to participate, not only a few people who can afford expensive gadgets.
Susceptible To Grinding Attack. A grinding attack happens when a miner can trick the algorithm to make them a miner. In the case of PoC, a miner can manipulate the chain to always request the hashes in its nonces. Thereby mining more than the rest and getting more rewards.
Space Privilege Applies. Since miners often get a hard disk with unusually large space. As a result, they can plot more nonces and solve more puzzles. This is unfair to those with hard disks of relatively moderate space.
PoA Flow. Source: “Deconstructing Blockchains” (Natoli et al., 2019)
There must be thorough due diligence on the miners for a blockchain to be ultimately secure. Some consensus mechanisms skip this process and fall into the hands of dishonest miners.
Proof of Authority, a consensus mechanism in which validators stake their identity, fixes this loophole in its design. Firstly, the real-life identity of each validator is ascertained within a PoA consensus model. The network managers will check how trustworthy the prospective validator is. This also makes it easy to track any validator in case of foul play. Secondly, each validator must stake a certain amount of assets as a sign of commitment. Basically, PoA validators stake their reputation and their coins.
Transactional Speed. Proof of Authority only has a few vetted validators. The short number of validators makes decision-making on transactional validity faster.
Tighter Security. The protocol managers would have vetted the real-life details of the validators. It is easier to take legal steps against any validator in case they cheat. This makes the mechanism more secure.
Uses Less Energy. Proof of Authority requires energy to operate. However, it does not use up to the amount of energy required for Proof of Work.
Not Decentralized. PoA is not decentralized because it only has a little number of validators. As a result, consensus power is only concentrated into the hands of one single actor or a few people.
Breaks Anonymity. Blockchain protects the anonymity of each user for on-chain privacy. But Proof of Authority exposes the data of the validators.
NEM blockchain introduced the Proof of Importance consensus algorithm to improve the Proof of Stake mechanism. First, the Proof of Stake mechanism makes validators lock up their assets and not transact with them. Secondly, it only rates validators based on their stakings.
Proof of Importance goes beyond that. The algorithm rates a node based on 3 variables:
These 3 questions form how the importance of an account or node will be. The Proof of Importance mechanism encourages network participants to hold assets and transact with them.
Sybil Resistant. A Sybil attack occurs when a dishonest validator controls multiple dishonest nodes to manipulate the blockchain. By default, the scoring system in PoI makes it extremely costly for anyone to run fake nodes.
Prevents Hoarding. Validators in a PoS blockchain have to lock their assets. Thereby hoarding those assets out of circulation. Proof of Importance works better because it encourages a free flow of assets.
Rewards General Participation. PoI is beyond staking assets. It ensures that each miner is actively involved in the network’s activities, especially in terms of transactional frequency and volume.
Favors The Rich. Those who trade higher volumes more frequently are accorded more importance. This can be unfair to other network participants who do not have much funds.
Little Incentives. Validators do not mine blocks with much power. As a result, they are not incentivized as much as the validators in a PoS. This low incentive can be a bad deal for those who run node as a business.
Blockchains try to maintain the tripod balance of decentralization, scalability, and security. This also reflects in the consensus mechanisms they pick. Blockchains adopt consensus mechanisms based on their architecture and technical preferences.
From a security standpoint, the weaknesses in the consensus mechanism of a blockchain can be a loophole for manipulation. This underscores why blockchains should always have quality protocol audits to ensure their protocol is tamper-proof.
There is no absolute best consensus mechanism. All of them have pros and cons. It depends on the nature of the blockchain and what the founding team would like to trade off.
There are various consensus mechanisms, including Proof of Work, Proof of Stake, Delegated Proof of Stake, Proof of Capacity, Proof of Importance, and so on.
Consensus mechanisms refer to the modalities of block generation, becoming a validator, and agreement among validators in a blockchain.