UNIT – 4
Blockchain 2.0
It is based on the concept of exchanging value in a decentralized and peer-to-
peer fashion. A blockchain is a distributed ledger system that stores all
transactions and data in a public database.
Ethereum
Ethereum is a Blockchain network that introduced a built-in Turing-complete
programming language that can be used for creating various decentralized
applications(also called Dapps). The Ethereum network is fueled by its own
cryptocurrency called ‘ether’.
The Ethereum network is currently famous for allowing the implementation
of smart contracts. Smart contracts can be thought of as ‘cryptographic
bank lockers’ which contain certain values.
These cryptographic lockers can only be unlocked when certain conditions
are met.
Unlike bitcoin, Ethereum is a network that can be applied to various other
sectors.
Ethereum is often called Blockchain 2.0 since it proved the potential of
blockchain technology beyond the financial sector.
The consensus mechanism used in Ethereum is Proof of Stakes(PoS),
which is more energy efficient when compared to that used in the Bitcoin
network, that is, Proof of Work(PoW). PoS depends on the amount of stake
a node holds.
History of Ethereum
2013: Ethereum was first described in Vitalik Buterin’s white paper in
2013 with the goal of developing decentralized applications.
2014: In 2014, EVM was specified in a paper by Gavin Wood, and the
formal development of the software also began.
2015: In 2015, Ethereum created its genesis block marking the official
launch of the platform.
2018: In 2018, Ethereum took second place in Bitcoin in terms of market
capitalization.
2021: In 2021, a major network upgrade named London included Ethereum
improvement proposal 1559 and introduced a mechanism for reducing
transaction fee volatility.
2022: In 2022, Ethereum has shifted from PoW( Proof-of-Work ) to PoS(
Proof-of-State ) consensus mechanism, which is also known as Ethereum
Merge. It has reduced Ethereum’s energy consumption by ~ 99.95%.
Features of Ethereum
1. Smart contracts: Ethereum allows the creation and deployment of smart
contracts. Smart contracts are created mainly using a programming
language called solidity. Solidity is an Object Oriented Programming
language that is comparatively easy to learn.
2. Ethereum Virtual Machine (EVM): It is designed to operate as a runtime
environment for compiling and deploying Ethereum-based smart contracts.
3. Ether: Ether is the cryptocurrency of the Ethereum network. It is the only
acceptable form of payment for transaction fees on the Ethereum network.
4. Decentralized applications (Daaps): Dapp has its backend code running
on a decentralized peer-to-peer network. It can have a frontend and user
interface written in any language to make calls and query data from its
backend. They operate on Ethereum and perform the same function
irrespective of the environment in which they get executed.
5. Decentralized autonomous organizations (DAOs): It is a decentralized
organization that works in a democratic and decentralized fashion. DAO
relies on smart contracts for decision-making or decentralized voting
systems within the organization.
Type of Ethereum Accounts
Ethereum has two types of accounts: An externally owned account (EOA),
and a Contract account. These are explained as following below:
Externally owned account (EOA): Externally owned accounts are
controlled by private keys. Each EOA has a public-private key pair. The
users can send messages by creating and signing transactions.
Contract Account: Contract accounts are controlled by contract codes.
These codes are stored with the account. Each contract account has an ether
balance associated with it. The contract code of these accounts gets
activated every time a transaction from an EOA or a message from another
contract is received by it. When the contract code activates, it allows to
read/write the message to the local storage, send messages and create
contracts.
How Does Ethereum Work?
Ethereum implements an execution environment called Ethereum Virtual
Machine (EVM).
When a transaction triggers a smart contract all the nodes of the network
will execute every instruction.
All the nodes will run The EVM as part of the block verification, where the
nodes will go through the transactions listed in the block and runs the code
as triggered by the transaction in the EVM.
All the nodes on the network must perform the same calculations for
keeping their ledgers in sync.
Every transaction must include:
Gas limit.
Transaction Fee that the sender is willing to pay for the
transaction.
If the total amount of gas needed to process the transaction is less than or
equal to the gas limit then the transaction will be processed and if the total
amount of the gas needed is more than the gas limit then the transaction
will not be processed the fees are still lost.
Thus it is safe to send transactions with the gas limit above the estimate to
increase the chances of getting it processed.
Real-World Applications of Ethereum
Voting: Voting systems are adopting Ethereum. The results of polls are
available publicly, ensuring a transparent fair system thus eliminating
voting malpractices.
Agreements: With Ethereum smart contracts, agreements and contracts can
be maintained and executed without any alteration. Ethereum can be used
for creating smart contracts and for digitally recording transactions based
on them.
Banking systems: Due to the decentralized nature of the Ethereum
blockchain it becomes challenging for hackers to gain unauthorized access
to the network. It also makes payments on the Ethereum network secure, so
banks are using Ethereum as a channel for making payments.
Shipping: Ethereum provides a tracking framework that helps with the
tracking of cargo and prevents goods from being misplaced.
Crowdfunding: Applying Ethereum smart contracts to blockchain-based
crowdfunding platforms helps to increase trust and information symmetry.
It creates many possibilities for startups by raising funds to create their own
digital cryptocurrency.
Domain names: Ethereum name service allows crypto users to buy and
manage their own domain names on Ethereum, thus simplifying
decentralized transactions without putting users to remember long,
machine-readable addresses.
Benefits of Ethereum
Availability: As the Ethereum network is decentralized so there is no
downtime. Even if one node goes down other computing nodes are
available.
Privacy: Users don’t need to enter their personal credentials while using
the network for exchanges, thus allowing them to remain anonymous.
Security: Ethereum is designed to be unhackable, as the hackers have to
get control of the majority of the network nodes to exploit the network.
Less ambiguity: The smart contracts that are used as a basis for trade and
agreement on Ethereum ensure stronger contracts that differ from the
normal traditional contracts which require follow-through and
interpretation.
Rapid deployment: On Ethereum decentralized networks, enterprises can
easily deploy and manage private blockchain networks instead of coding
blockchain implementation from scratch.
Network size: Ethereum network can work with hundreds of nodes and
millions of users.
Data coordination: Ethereum decentralized architecture better allocates
information so that the network participants don’t have to rely on a central
entity to manage the system and mediate transactions.
Drawbacks of Ethereum
Complicated programming language: Learning solidity from
programming smart contracts on Ethereum can be challenging and one of
the main concerns is the scarcity of beginner-friendly classes.
Volatile cryptocurrency: Ethereum investing can be risky as the price of
Ether is very volatile, resulting in significant gains as well as a significant
loss.
Low transaction rate: Bitcoin has an average transaction rate of 7TPS and
Ethereum has an average speed of 15 TPS which is almost double that of
bitcoin but it is still not enough.
Ethereum Virtual Machine
Ethereum Virtual Machine (EVM) is designed as the runtime environment
for smart contracts in Ethereum. It is sandboxed and isolated from the other
parts of the system. This means that any operation on EVM should not affect
your data or programs in any way, no matter how many times you call a
particular function on it.
An EVM is the runtime environment that executes Ethereum smart
contracts.
Ethereum contains its own Turing-complete scripting language, called
Solidity, and with this comes a need to execute this code.
A program called the Ethereum Virtual Machine (EVM) can do this task.
It runs on top of the Ethereum network, meaning that all nodes reach a
consensus about what code should be executed at every given time.
Purpose of EVM
The Ethereum Virtual Machine (EVM) is a Turing complete
programmable machine, which can execute scripts to produce arbitrary
outcomes. It has been built with the purpose of being a “world computer” and
has immense power.
It is the computer that stores data on blockchain, like bitcoin, but it also
executes code in smart contracts on the Ethereum network.
The machine is made to be able to run any kind of Crypto-contract that can
be built on Ethereum’s blockchain. It does this by using a programming
language called Solidity, which is compiled into the EVM for execution.
The intention behind writing code on the Ethereum network is to create
smart contracts and programs that automatically execute things when
certain conditions are met. If a terms or condition is not met, the system can
execute it in an “exit” function as well.
For example, if an account has been hacked, the hacker cannot steal money
from the system, because they don’t have the budget or authority to do so.
How Does EVM Works?
Ethereum Virtual Machine (EVM) is a program which executes scripts used to
implement certain operations usually in Ethereum blockchain.
The Ethereum Virtual Machine makes the process of creating new tokens on
Ethereum Blockchain easy. Here, script means a set of instructions or an
algorithm which tells the computer what it needs to do in order for something
to work properly. The EVM requires that one has access over any network
node so as to be able to execute the desired commands and create new tokens
on the blockchain without any difficulties.
In Ethereum, there is something called a smart contract. These contracts
have some computer code which facilitates the exchange of money and
information.
These contracts are predefined by the creator of the smart contract, in order
to ensure that a certain outcome will happen based on either what happens
or doesn’t happen.
Ethereum Virtual Machine provides Turing complete environment for
execution of scripts and smart contracts. This means that anything that can
be implemented with a computer can be run on EVM.
In the Ethereum ecosystem, EVM plays a vital role by providing a platform for
decentralized applications (DApps) to be built on top of it.
Ethereum Virtual Machine ensures that all transactions and smart contracts
made on the Ethereum blockchain are executed in correct and expected
manner as desired by the smart contract code. It serves as a platform for
applications to be executed on.
In simple words, it can be said that Ethereum Virtual Machine facilitates
DApp creation and execution on the blockchain.
Ethereum Virtual Machine (EVM) has two parts:
EVM (the part that runs solidity source code): The EVM is written in
C++ and uses LLVM as its compiler. It is a full-featured virtual machine
with all the features that you would want in a general purpose Smart
Contract Virtual Machine, such as support for multiple programming
languages, security features, runtime environments and more. It also allows
you to write custom EVM bytecode .
Uncles: These are small pieces of smart contracts or data stored on the
blockchain. This is a useful feature because it allows for you to store
metadata about your program. EVM Assembly: This is the bytecode of
EVM, which you can use as your programming language.
These are small pieces of smart contracts or data stored on the blockchain.
This is a useful feature because it allows one to store metadata about the
program.
Actions: These are basic operations that one can perform on assets stored
in memory (and not on the blockchain), such as multiplication, addition,
and so on.
Balance: This is the amount of Ether that one have at any time. So, if there
is a balance of 100 Ether and spend 10 Ether, the balance would be 90
Ether. Note that this is not actually a variable, it’s just a part of memory
where EVM stores the data. This means that whenone tries to modify or
read from it, it will return execution with an error.
Block: This is an immutable storage for all actions and transactions related
to Ethereum in its lifetime up until this block in particular. These blocks
can be only 65,000 so this is not going to change.
Blockhash: This is a hash of the block in question. So, if you are looking at
stored on the blockchain under another name, this would be a hash of the
data stored there.
Block Number: This is a number indicating which block this particular
blockhash belongs to. It always starts from zero and increases every time
there’s a new block added to the chain. Note that blocks have timestamps
associated with them so you can tell how much time passed between two
blocks.
Code: This is code executed in EVM that determines what action is going
to be taken when an input happens (such as transferring money).
CodeHash: This is a hash of the code itself. If one looks at a contract on
Etherscan, the CodeHash is what one will see. When functions are executed
on EVM, this number changes because the code itself changes based on the
input.
CodeSize: This is the actual size of the code in bytes.
GasLimit: This is a part of EVM that allows for users to specify how much
gas they are willing to spend in order to execute something. If this number
is zero, then nothing will happen (this rarely happens).
How Does Gas RelateTo Performance Of EVM?
Gas is a measure of computational power. It determines how much time
each transaction and contract takes to execute.
Because there is so much code already in the system, it uses a limited
amount of Gas to run all of this code. It sets the default gas limit to 250,000
gas units.
In general, the more complicated your transaction, the more gas it takes to
execute.
Benefits of EVM
Execute untrusted code without risking data: One can execute untrusted
code without putting the data at risk. EVM guarantees that its computations
will not interfere with anything else happening in the system or with the
personal files.
Can run complex smart contracts: One can run complex smart contracts
in EVM without worrying about how they interact with each other. One can
write them once and then run them on multiple platforms, which allows for
the creation of a single contract that runs on multiple computing
environments.
Deterministic processing: Smart contracts written on EVM have access to
all of Ethereum’s states at any given time, allowing for processing to
happen in a deterministic way and giving more guarantees about their
correctness. For example, one cannot make an infinite loop in EVM by
calling the same function twice. It would stop executing and return a finite
value.
Distributed consensus: One of the potential applications of Ethereum is to
allow for distributed consensus where everyone is running the same
program but from their own computers.
Robust against failure: This is a complex process because the network
needs to be able to come to a consensus at any given time. This way, the
system becomes more robust against failures of individual nodes and you
can update several nodes simultaneously without worrying that they might
end up disagreeing with each other because of how code was written.
Easy to write stateful contracts: From a developer perspective, EVM is
designed for writing smart contracts as well as for creating DApps
(decentralized applications), which are programs running on distributed
networks in a way that ensures all of them are seeing the same version. It
also makes it incredibly easy to write stateful contracts, which need access
to some kind of persistent storage.
Downsides of EVM
High cost of storing data: First is gas, which is what you need to use in
order to pay the fee to run a smart contract, and the other is the high cost of
storing data on the blockchain, which could take up more than 3TB
High gas cost: In Ethereum, all transactions require a fee to execute. These
fees are called “gas”, and are paid in ETH tokens. Gas is priced at the
moment of execution, and depends on the complexity of executing a
transaction. The more difficult the computation for a transaction, the higher
its gas cost will be.
High gas price during network congestion: During times when there is
high network congestion due to many transactions being pushed onto the
blockchain, gas prices rise because there are fewer transactions that can go
through (the same amount of computational power has to service more
transactions).
Technical expertise required: Writing smart contracts and using EVM
requires technical expertise. It’s a Turing-complete system, which allows
programmers to write scripts in any programming language they wish. This
can be excellent or disastrous, depending on the intention behind the code
being written. Programming languages are not inherently good or bad in
their nature; it all depends on who is using them and for what purpose. The
downside of this technology is that it could create a lot of complicated
problems because with more power comes more responsibility for the
writer of code.
Ethereum wallets
Ethereum wallets are applications that let you interact with your Ethereum
account. Think of it like an internet banking app – without the bank. Your
wallet lets you read your balance, send transactions and connect to applications.
Your wallet is only a tool for managing your Ethereum account. That means
you can swap wallet providers at any time. Many wallets also let you manage
several Ethereum accounts from one application.
Wallets, accounts, and addresses
It's worth understanding the differences between some key terms.
An Ethereum account is an entity that can send transactions and has a
balance.
An Ethereum account has an Ethereum address, like an inbox has an
email address. You can use this to send funds to an account.
A wallet is a product that lets you manage your Ethereum account. It
allows you to view your account balance, send transactions, and more.
Most wallet products will let you generate an Ethereum account. So you don't
need one before you download a wallet.
Types of wallets
There are a few ways to interface and interact with your account:
1. Physical hardware wallets are devices that let you keep your crypto
offline – very secure
2. Mobile applications that make your funds accessible from anywhere
3. Browser wallets are web applications that let you interact with your
account directly in the browser
4. Browser extension wallets are extensions you download that let you
interact with your account and applications through the browser
5. Desktop applications if you prefer to manage your funds via macOS,
Windows or Linux
Solidity Programming
Solidity is an object-oriented programming language created specifically by the
Ethereum Network team for constructing and designing smart contracts on
Blockchain platforms.
It's used to create smart contracts that implement business logic and generate
a chain of transaction records in the blockchain system.
It acts as a tool for creating machine-level code and compiling it on the
Ethereum Virtual Machine (EVM).
It has a lot of similarities with C and C++ and is pretty simple to learn and
understand. For example, a “main” in C is equivalent to a “contract” in
Solidity.
Like other programming languages, Solidity programming also has variables,
functions, classes, arithmetic operations, string manipulation, and many other
concepts.
Evolution of Solidity Programming
Solidity is a relatively new language that is rapidly growing.
Solidity is currently the core language on Ethereum and other private
blockchains operating on competing platforms, such as Monax and
its Hyperledger Burrow blockchain which uses Tendermint for consensus.
SWIFT has created a proof of concept that runs on Burrow and uses Solidity.
What are EVM and Smart Contracts?
EVM or Ethereum Virtual Machine
The Ethereum Virtual Machine (EVM) provides a runtime environment for
Ethereum smart contracts.
It is primarily concerned with ensuring the security and execution of
untrusted programs through the use of an international network of public
nodes.
EVM is specialized in preventing Denial-of-Service attacks and certifies that
the programs do not have access to each other's state, as well as establishing
communication, with no possible interference.
Smart Contracts
Smart contracts refer to high-level program codes compiled into EVM before
being posted to the Ethereum blockchain for execution.
It enables you to conduct trustworthy transactions without the involvement of
a third party; these transactions are traceable and irreversible.
Programming languages commonly used to create and write smart contracts
are Serpent, Solidity, Mutan, and LLL.
Data Types of Solidity Programming
It supports all the common data types seen in other OOP languages, such as,
Boolean - The Boolean data type returns ‘1' when the condition is true and ‘0'
when it is false, depending on the status of the condition.
Integer - You can sign or unsign integer values in Solidity. It also supports
runtime exceptions and the ‘uint8' and ‘uint256' keywords.
String - Single or double quotes can denote a string.
Modifier - Before executing the code for a smart contract, a modifier often
verifies that any condition is rational.
Array - The syntax of Solidity programming is like that of other OOP
languages, and it supports both single and multidimensional arrays.
Apart from that, Solidity programming allows you to "Map" data structures with
enums, operators, and hash values to return values stored in specific storage
places.
What is Solidity Programming: Data Types, Smart Contracts, and EVM?
Dapps otherwise referred to as Decentralized Applications are applications built
on the open-source, peer-to-peer network of Ethereum Blockchain which uses
smart contracts and front-end user interfaces to create decentralized platforms.
Developing a Dapp, like any other app, requires programming and executing
code on the system. Solidity programming stands apart from the other
programming languages and is the programming language of choice in
Ethereum.
Solidity is a brand-new programming language developed by Ethereum, the
second-largest cryptocurrency market by capitalization.
So if you are interested in exploring more about Solidity Programming and its
concepts, then you are at the right place. In this tutorial on Solidity
Programming, you will cover various important components of Solidity
Programming.
How to Get Started With Solidity Programming?
Version Pragma
Pragmas are directives to the compiler about how to handle the code. Every
line of solidity source code should begin with a "version pragma," which
specifies which version of the solidity compiler to use.
This prevents the code from being incompatible with future compiler
versions that may introduce changes.
The Contract Keyword
The contract keyword declares a contract that encapsulates the code.
State/Declare Variables
State variables are written on the Ethereum Blockchain and are permanently
maintained in contract storage.
The line uint public var1 declares a state variable of type uint named var1
(unsigned integer of 256 bits), it is very similar to adding a slot in a database.
A Function Declaration
This is a function named “set” of access modifier type public which takes a
variable a and variable b of data type uint as a parameter.
This was an example of a simple smart contract that updates the value of var1
and var2. Anyone with access to the Ethereum blockchain can use the set
function to change the value of var1 and var2.
By adding the values of the variables var1 and var2, it can calculate the
variable sum.
It will retrieve and print the value of the state variable sum using the “get”
function.
How to Execute the Code?
You can execute a Solidity Program in two ways -
1. Offline Mode
2. Online Mode
Offline Mode
To operate a Solidity smart contract in Offline mode, it must meet three
conditions and follow four essential actions:
Conditions
1. Download and install node.js.
2. Install Truffle globally.
3. Install ganache-cli.
Actions
1. Create a truffle project and set up a development network for it.
2. Develop and deploy a smart contract for it.
3. From the Truffle console, interact with the smart contract.
4. Create tests to evaluate Solidity's primary features.
Online Mode
In the Online Mode, the Remix IDE is typically used to compile and run
Solidity smart contracts.
Remix IDE
Advantages of Solidity Programming
Apart from the primary functionality of Solidity Programming, there are many
other features provided by Solidity programming that cause it to have an edge
over other Ethereum based languages.
Apart from fundamental data types, Solidity programming also allows
complex data types and member variables.
It provides an Application Binary Interface (ABI) to enable type safety. If the
compiler discovers a data type mismatch for any variable, the ABI generates
an error.
It refers to the ‘Natural Language Specification,' which is used to turn user-
centric specifications into language that machines can understand.
Various types of attacks on Smart Contracts
These smart contracts are executed on blockchain platform such as Ethereum.
Smart contracts are implemented on Ethereum using Solidity. By compiling to
bytecode, the program can be executed by the Ethereum Virtual Machine
(EVM). EVM bytecode is the bytecode that is executed by the Ethereum virtual
machine (EVM). It's a low-level bytecode, meaning that it doesn't have an
abstract syntax tree and instead operates on individual bytes. The instruction set
of the EVM is kept minimal in order to avoid incorrect or inconsistent
implementations which could cause consensus problems. All instructions
operate on the basic data type, 256-bit words or on slices of memory (or other
byte arrays). The usual arithmetic, bit, logical and comparison operations are
present. Conditional and unconditional jumps are possible. Furthermore,
contracts can access relevant properties of the current block like its number and
timestamp.
EVM maintains the global state of the network, which includes addresses,
account balances and token holdings.
The main topic here is various types of attack using SC.
There are several types of attacks that can occur in smart contracts as
below:
1.Re-entry attack: A re-entry attack is a type of attack that can occur in smart
contract systems, specifically in Ethereum-based blockchain systems. It occurs
when a malicious actor is able to call a smart contract function multiple times
before the first call has completed. This can cause unintended side-effects and
allow the attacker to manipulate the state of the smart contract.
Re-entry attacks take advantage of the fact that smart contracts in Ethereum can
be called by other smart contracts, and that these calls can be triggered
asynchronously. If a smart contract function is not properly protected from re-
entry, an attacker could call the function multiple times before the first call has
completed, causing the function to be executed multiple times and potentially
modifying the state of the contract in unexpected ways.
E.g, A smart contract that manages a balance of funds could be vulnerable to a
re-entry attack if it does not properly check the state of the contract before
executing a transfer of funds. If an attacker is able to call the transfer function
multiple times before the first call has completed, the contract could transfer
more funds than intended, resulting in a loss of funds for the contract or other
users of the contract.
How to prevent re-entry attack, smart contract developers must ensure that
their contracts are properly protected from re-entry, typically by using
techniques such as mutexes, checks that prevent the contract from executing the
same function multiple times, or by using more advanced techniques such as
state channels. It is important to thoroughly test and review smart contracts to
ensure that they are secure and free from vulnerabilities, including re-entry
attacks.
2. Race conditions attack: Race conditions refer to a type of concurrency-
related problem that can occur in smart contracts. A race condition occurs when
two or more transactions try to access and modify the same state
simultaneously, leading to unpredictable or unintended results. For example,
consider a smart contract that keeps track of a balance for each user. If two
transactions attempt to transfer funds from one us.
E.g, consider a smart contract that keeps track of a balance for each user. If two
transactions attempt to transfer funds from one user to another at the same time,
and both transactions read the current balance of the first user before modifying
it, there is a possibility that both transactions will use the same starting balance.
As a result, one of the transactions may overwrite the balance change made by
the other transaction, leading to incorrect balances.
Race conditions can have serious consequences for smart contracts, as they can
lead to security vulnerabilities, unexpected behavior, and data corruption.
How To prevent race conditions, it is important to use locking mechanisms
such as mutexes or to perform transactions atomically, which ensures that only
one transaction can modify a given state at a time. Additionally, it is important
to test smart contracts thoroughly for race conditions and to implement regular
security audits to ensure that the contract remains secure over time.
3. Integer overflow/underflow attack: Integer overflow/underflow refers to a
type of error that can occur in smart contracts when performing arithmetic
operations on integers.
In computer systems, integers are stored in a fixed number of bits, which
determines the maximum and minimum values that an integer can represent.
When an operation is performed on an integer that results in a value that
exceeds the maximum representable value, an overflow occurs. Similarly, when
an operation is performed on an integer that results in a value that is below the
minimum representable value, an underflow occurs.
In smart contracts, integer overflows and underflows can have serious
consequences.
E.g, an overflow in a contract that manages a balance can result in an incorrect
balance being stored, leading to security vulnerabilities and loss of funds. An
underflow in a contract that manages a token supply can result in the creation of
negative tokens, leading to unexpected behavior and data corruption.
How to prevent integer overflows and underflows, it is recommended to use
safe integers libraries or to perform explicit range checks before performing
arithmetic operations. Additionally, it is important to thoroughly test smart
contracts for these types of errors and to implement regular security audits to
ensure that the contract remains secure over time.
4. Delegate call/proxy call attacks: Delegate call (also known as a proxy call)
is a feature in the Ethereum Virtual Machine (EVM) that allows a contract to
call another contract, with the calling contract effectively delegating its own
execution context to the called contract.
A delegate call attack occurs when an attacker takes advantage of the delegate
call feature to modify the behavior of a smart contract. The attacker can modify
the behavior of the called contract by providing malicious input data or by
changing the code of the called contract.
Below are few examples.:
Example 1: Modifying a called contract: An attacker can modify the behavior
of a called contract by changing its code. For example, consider a contract that
manages an escrow account for funds. If the contract uses delegate calls to call
another contract for performing transactions, an attacker can modify the code of
the called contract to steal funds from the escrow account.
Consequence: Loss of funds and data corruption.
What is an escrow account: Is a type of account used in transactions as a
neutral third party that holds and manages funds or assets on behalf of two other
parties. The purpose of an escrow account is to ensure that funds or assets are
not released until certain conditions are met.
In the context of a financial transaction, an escrow account can be used to
hold funds until the terms of the transaction are met. For example, in a real
estate transaction, the buyer's funds may be held in an escrow account until the
sale is completed and the title is transferred to the buyer.
In the context of a smart contract, an escrow account refers to a contract that
holds and manages funds or assets on behalf of two parties, ensuring that the
funds or assets are released only when certain conditions are met. For example,
in a decentralized exchange, an escrow contract can be used to hold the funds of
both the buyer and the seller until the terms of the trade are met, at which point
the funds are released to the appropriate parties.
Escrow accounts play an important role in transactions by providing a secure
and neutral way to manage funds and assets, helping to reduce the risk of fraud
and ensuring that transactions are completed fairly and transparently.
Example2: Injecting malicious input data: An attacker can inject malicious
input data into a delegate call to modify the behavior of the called contract. For
example, consider a contract that manages a voting system. If the contract uses
delegate calls to call another contract for counting votes, an attacker can inject
malicious input data into the delegate call to manipulate the vote count.
Consequence: Tampering with the results of the voting system and loss of trust
in the system.
Example 3: Reentrancy attacks: An attacker can take advantage of delegate
calls to perform reentrancy attacks. For example, consider a contract that
manages a balance for each user. If the contract uses delegate calls to call
another contract for performing transactions, an attacker can modify the
behavior of the called contract to perform a reentrancy attack and steal funds
from the balance of the original contract.
How to prevent delegate call attacks, it is important to verify the source and
destination of a delegate call before executing it. Additionally, authentication
mechanisms can be used to ensure that only authorized contracts can call other
contracts. Additionally, it is recommended to perform regular security audits
and to thoroughly test smart contracts for potential delegate call vulnerabilities.
5. Denial of Service (DoS) attacks: Type of cyber-attack where a attacker
deliberately overloads or crashes a system or network, making it unavailable to
users. The goal of a DoS attack is to prevent legitimate users from accessing the
targeted system or network, either by overwhelming it with excessive traffic or
by exploiting vulnerabilities in the system's design.
In the context of smart contracts, a DoS attack on a contract can be performed
by repeatedly sending transactions that use excessive computational resources,
leading to a congested network, or by exploiting vulnerabilities in the contract's
code that allow the attacker to crash the contract.
Consequences of DoS attacks on smart contracts can include:
Network Congestion: Last but not the least network congestions can
result from a large number of transactions being sent to a smart
contract, including DoS attacks, leading to blocks not being finalized
in a timely manner. When this occurs, the consensus mechanism used
by the network may have difficulty reaching agreement on which
transactions to include in the next block, causing delays and
potentially even failed transactions. In a proof-of-work consensus
mechanism, for example, network congestion can lead to longer
confirmation times for transactions and higher transaction fees, as
miners prioritize transactions with higher fees.
How to prevent DoS attacks: smart contract developers can take several
precautions, such as:
Limiting the computational resources required by transactions:
This can be done by limiting the number of operations that can be
performed by a transaction, or by setting a maximum gas limit for
transactions.
Monitoring the network for excessive traffic: Network monitoring
tools can be used to identify and prevent DoS attacks.
Conducting regular security audits: Regular security audits can
identify vulnerabilities in the contract's code that could be exploited
by attackers to perform a DoS attack.
It is important to take the threat of DoS attacks seriously, as they can have
serious consequences for smart contracts and the users that depend on them.
Regular security audits, network monitoring, and implementation of best
practices can help mitigate the risk of DoS attacks and ensure the availability
and security of smart contracts.
6. Front-running: Type of attack that takes advantage of the decentralized and
transparent nature of blockchain systems. It occurs when a malicious actor
intercepts a transaction in the process of being confirmed by the network and
quickly executes their own transaction with the same asset, taking advantage of
the change in market conditions caused by the original transaction.
In the context of smart contracts, front-running can occur when a malicious
actor intercepts a transaction that is about to be executed by a smart contract and
quickly executes their own transaction with the same assets, taking advantage of
the conditions created by the original transaction. For example, if a user is about
to execute a trade on a decentralized exchange, a malicious actor could intercept
the transaction, execute their own trade with the same assets, and take
advantage of the change in market conditions caused by the original trade.
To prevent front-running, smart contract developers can take several
precautions, such as:
Implementing an order execution algorithm that prioritizes
transactions based on a fair and transparent criterion, such as
transaction fees or the time the transaction was submitted.
Using an alternative consensus mechanism, such as proof-of-stake,
that is less susceptible to front-running.
Conducting regular security audits to identify and address
vulnerabilities in the contract's code.
7. Contract ownership hijacking: Type of attack on a smart contract in which
an attacker takes over the ownership of the contract, effectively giving them
control over its operations. This can occur if the contract's code contains
vulnerabilities that allow an attacker to change the address stored as the
contract's owner, giving them the ability to execute any function within the
contract.
Once the attacker has taken over ownership of the contract, they may be able to
execute malicious code, steal funds stored within the contract, or manipulate the
contract's functionality in other ways. In some cases, they may also be able to
modify the contract's code to remove any evidence of the attack and make it
more difficult to detect.
How to prevent contract ownership hijacking, smart contract developers can
take several precautions, such as:
Implementing strong access controls, such as multi-signature
requirements, to prevent unauthorized changes to the contract's code
or ownership.
Conducting regular security audits to identify and address
vulnerabilities in the contract's code.
Implementing measures to detect and respond to attempts to hijack
contract ownership, such as logging functions and alerts
8. Information leakages attack: Refer to the unauthorized release of sensitive
information from a smart contract. These attacks can occur when the contract's
code contains vulnerabilities that allow an attacker to access and exfiltrate
sensitive information, such as private keys, passwords, or confidential business
data.
Some common ways in which information leakages can occur include:
Log leaks: Attackers can use the contract's logging functionality to
exfiltrate sensitive information.
Code execution: Attackers can execute malicious code on the
contract that allows them to access and exfiltrate sensitive
information.
Timing attacks: Attackers can use timing information to deduce
sensitive information, such as private keys.
How to prevent information leakages attacks, smart contract developers can
take several precautions, such as:
Implementing strong access controls to prevent unauthorized
access to sensitive information.
Conducting regular security audits to identify and address
vulnerabilities in the contract's code.
Implementing measures to detect and respond to attempts to exfiltrate
sensitive information, such as logging functions and alerts.
Designing contracts to minimize the amount of sensitive information
stored on the blockchain.
9. Transaction-ordering dependence (TOD) attacks: Refer to a type of attack
on a blockchain that takes advantage of the dependence of some smart contracts
on the order in which transactions are processed. In a TOD attack, an attacker
manipulates the order in which transactions are processed to achieve a
malicious outcome.
Example, consider a smart contract that allows users to place bets on a future
event. If the contract processes transactions in a particular order, an attacker
may be able to place a bet after the outcome of the event is known and
manipulate the contract to pay out more than they should have.
How to prevent TOD attacks, smart contract developers can take several
precautions, such as:
Implementing randomization mechanisms to ensure that
transactions are processed in a random order.
Using consensus mechanisms, such as Proof of Work or Proof of
Stake, to ensure that transactions are processed in a fair and
predictable order.
Designing contracts to be insensitive to the order in which
transactions are processed.
All of the above attacks can have serious common consequences, including:
Financial loss: Attackers may be able to steal funds by manipulating
the contract to pay out more than they should have.
Decreased trust in the system: Users may lose trust in the security
of smart contracts and be less likely to use them in the future.
Reputation damage: The smart contract platform and its developers
may experience reputation damage as a result of the attack.
Turing Completeness
Turing-completeness is a word defined by Alan Turing which it describes the
idea that some computing machines are capable of performing any task a
computer can perform.
The concept of Turing-completeness is one at the heart of software and
application development, where it allows code to be written without having
to check beforehand if it will work or not.
In other words, one can write your program without worrying about what
else is allowed for it to do.
This is essential in determining usability as well as many other aspects of
the software. It is also important to know what “Turing-complete” means
and how it relates to Ethereum.
In Turing’s paper, the concept of Turing-complete machines is used to
disprove the possibility of true artificial intelligence.
For instance, whether a machine can eventually imitate the behaviors of a
human. In practical terms, this means that “Turing-complete” allows
programmers to write code that can be used by any computer to achieve
any result.
It is necessary for introducing new techniques and ideas into software
programming such as functional programming or even for understanding
ideas about universal computation with regard to general computing.
Turing Completeness of Smart Contract Language
“A programming language that is Turing complete is theoretically
capable of expressing all tasks accomplishable by computers; nearly
all programming languages are Turing complete if the limitations of
finite memory are ignored.”
Unfortunately, I am not a thought leader in the field of smart contract design, so
I turned to the internet for guidance. Preliminary research returned wholly
unhelpful answers from StackOverflow like this or in-depth papers on Turing
machines like this. Neither of which examine the property in question through
the context of programming smart contracts.
Fortunately, I had the privilege of asking a highly qualified and leading resource
on the subject, Emily Pillmore who is a senior programmer with Kadena. I asked
her, “What is the difference between Turing completeness and Turing
incompleteness in the context of blockchain?” Her response:
“Turing incompleteness doesn’t really have much to do directly with
blockchains. It is a property of abstract rewrite systems in computer science that
ensures that all expressions in the system can be expressed in a normal form (i.e.
can be reduced)… Turing incompleteness manifests as expressions in a language
which are irreducible.”
And that’s only a fraction of the full answer! The remainder of the response is
equally impenetrable to someone like me. I asked a “How-does-this-thing-work”
question and got a comprehensive and technical answer. Fair enough. So I
thought I’d come at the problem from a different angle. Maybe if I ask a “What-
can-this-thing-do” question, then I’ll get a more concrete picture of its behaviors.
I asked, “Are there examples of things you can do with Turing completeness
that would be useful on the blockchain?” Emily’s answer:
“No. I cannot come up with a single use-case for the blockchain that requires
Turing completeness. The EVM does not use any of the properties of Turing
completeness because it restricts all recursion via the gas model anyway, which
enforces that recursion either terminate prior to gas running out, or terminate
the program when gas runs out. So in effect, the EVM’s gas model sort of
simulates Turing incompleteness, but not really. This is why I say they adopt all
the flaws of Turing completeness (side effecting, illegible and unreasonable
code, arbitrary looping), but use none of its benefits (no infinite recursion
allowed).”
Aha, this I can follow! When you have the power to do more things, it also
means that more things can go wrong. Turing completeness is inherently more
powerful, but if you can’t utilize the benefits of that power, then you’re
needlessly exposing yourself to more attack vectors due to the increased surface
area that comes with so many additional features.
To further clarify the distinguishing characteristic:
Turing complete languages always have a form of conditional repetition or
conditional jump (while, for, goto)
By their design, blockchains will always stop these endless loops with
mechanisms like gas.
Therefore, Turing completeness carries with it an unnecessary and
burdensome attack surface. It is high risk, with low reward, as illustrated
below.
Approximation of the “dead weight” attack surface inherited when using Turing
complete languages for smart contract programming.
At the time of publishing, there are 16 known attack vectors on Solidity, the
most popular domain-specific programming language for smart contracts, which
happens to be Turing complete. If Solidity were Turing incomplete, then the
most costly of these attacks would not even be possible. Most notably, the DAO
attack in 2016 — a reentrancy attack, enabled by Turing completeness —
drained 3.6M ETH (~$50M USD) from the fund, resulting in the Ethereum
community hard-forking the entire network to restore their preferred version of
history.
Ethereum as Turing Completeness
Ethereum is a cryptocurrency built with Turing completeness in mind.
Since it relies on programmable smart contracts, Ethereum is not reliant on
third-party services to function.
This means that, theoretically, one could buy a house or make other major
purchases on the Ethereum blockchain through the use of a smart contract.
However, there are concerns regarding whether or not this is feasible due to
the high costs associated with Turing complete systems and their ability to
run continuously without human intervention.
Does a System Have To Be Turing Complete To Be Useful in Blockchain?
A system has to be Turing complete in order to be useful in blockchain, but
it can have all the other desirable properties of a blockchain, such as
decentralization and trustless transactions.
A system is Turing complete if it can simulate an arbitrary computer
program. Turing complete systems have to be able to run any possible
computation, which includes the most complex types of computation such
as those found in blockchain. This type of system also often has better
performance than other systems because it can use a set of rules which are
more efficient when solving problems with many steps.
In addition to being Turing complete, a system must also be decentralized
and allow trustless transactions according to consensus in order for it to be
useful in the blockchain. These properties are necessary for the security and
consistency that a blockchain needs in order for its data records or “blocks”
to have value and meaning.
Blockchain verification and validation
We propose a taxonomy of BC-App V&V, broadly classified into SC
Testing, Platform Testing, and Application Testing, illustrated in Fig. 3. We
further discuss different testing types and methods belonging to these three
main classes in Sections 4 State of the art: Smart contract testing, 5 State of the
art: Performance testing, 6 State of the art: Security testing, 7 API and interface
testing.
State of the art: Smart contract testing
The presence of bugs and vulnerabilities (e.g., buffer overflows, command
injection, and cross-site scripting) in SCs after their deployment on a BC
network causes the following two major problems: (i) wastage of resources
(e.g., gas and computing hardware) and delay in transaction processing, due to
the presence of bugs in SCs, and (ii) security threats caused by malicious
entities by exploiting the vulnerabilities present in SCs. Both these problems
may lead to financial and non-financial
State of the art: Performance testing
In the literature, there exist different approaches for performance testing of BC-
Apps. The most common of these are benchmarking, monitoring, experimental
analysis, and simulation techniques. These approaches aim to help developers
evaluate different performance characteristics and identify bottlenecks, to
improve the performance of BC-Apps. Next, we discuss these approaches in
detail, along with their advantages and limitations. In Table 6, we summarize
and compare different types of BC
State of the art: Security testing
In this section, we discuss the Security and Privacy (S&P) related aspects of
BC-Apps that should be considered during an end-to-end BC-App security
testing. We discuss various S&P aspects considering components at different
layers of the BC stack. Please note that specific approaches to SC security
testing are covered in Section 4.
BC technology supports the concept of security by leveraging public-key
cryptography and primitives such as hash function and digital signature.
However, this may
API and interface testing
The users of BC-Apps typically have available APIs to connect to the
underlying BC components. A BC-App ecosystem comprises different
components, all of which must be connected. Therefore, it is crucial that
different APIs associated with these components are tested for their
compatibility with each other. API testing plays a major role to ensure that the
backend is functional. The APIs in BC-Apps need to be tested for errors
including unauthorized access, encrypted data in transit
Blockchain 3.0
It focuses on creating solutions for services and industries outside the world of
economics. This final evolutionary stage of the technology is dedicated to
transcending the purely financial application of DLT and introducing new
approaches to data management.
What is Ethereum?
Ethereum is a public, distributed, decentralized, and community-built
technology that is designed to carry out smart contracts (a script that, when
called with certain parameters, performs some actions or computations if
certain events are triggered.
In the Ethereum blockchain, there is a single, canonical state of the computer
called the Ethereum Virtual Machine. As it is a public and decentralized
platform, every node on the network agrees with the state of this virtual
machine and keeps a copy of the state on this computer. Whenever a new
block is added to the Blockchain, it will be added to the global copy of the
network that exists within all the nodes of the network.
What is Hyperledger?
Hyperledger is an open-source platform for building distributed ledger
solutions, with a modular architecture that delivers high degrees of
confidentiality, flexibility, resiliency, and scalability. This enables solutions
developed with this platform to be adapted for any industry. This is a private
and confidential blockchain framework managed by the Linux Foundation.
Differences Between Ethereum And Hyperledger
Below are the key differences between Ethereum and Hyperledger:
1. Purpose:
Ethereum is the platform for creating B2C businesses and decentralized
applications. It is created for the purpose of running smart contracts on the
Ethereum Virtual Machine(EVM) and creating decentralized apps for mass
consumption with the help of this.
Hyperledger is designed to create B2B businesses and cross-industry
applications. It helps businesses or industries to collaborate with the
developers, who are working with Distributed Ledger Technology(DLT).
Customized blockchain apps with limited access can be created with this.
2. Confidentiality:
Ethereum is a public network. All the transactions are entirely transparent
and anyone with access to the internet can view these transactions.
Hyperledger is limited access or allowed blockchain network. This is
highly secure and confidential. The organizations or individuals having the
Certificate of Authorization can only view all the transactions on the
network.
3. Governance:
The Ethereum network is governed by the Ethereum developers only.
Vitalik Buterin is the main developer and founder of Ethereum. This is
mostly an example of in-house development rather than collaboration.
Hyperledger fabric is governed by the Linux Foundation. IBM is also one
of the major contributors to this framework. It is a product of the massive
collaboration of these two companies which turned out to be a huge
success.
4. Participation:
Ethereum is a permission-free and public network. Anyone with access to
the internet can download the software and start mining Ethereum.
Hyperledger maintains strict control over the participation in this network.
Only authorized members and peers selected by authorized members can
use the Hyperledger platform and its tools. This hides valuable and
confidential information from external parties and prevents them to
manipulate it.
5. Smart Contracts:
Ethereum came up with smart contracts first. A Smart Contract is a
computer program or a condition written in code that gets automatically
triggered when certain conditions are met. It controls the transfer of digital
assets between the parties under the contract. It is immutable, once the
condition is created it cannot be changed by any third party.
Like the smart contracts, Hyperledger fabric also allows the member
organizations to run some code on peers that create the transactions on a
specific condition. These are known as chaincode.
6. Programming Language:
For writing smart contracts, Ethereum uses solidity and for developing the
application some high-level languages like JavaScript, Python, Golang can
be used.
In Hyperledger Go is widely used to write the chaincode along with that
some extent of Java and JavaScript are also used.
7. Proof-Of-Stake (POS) or Consensus Mechanism:
Previously Ethereum was using Proof-of-Work(POW) based consensus
mechanism. Currently, Ethereum is using Proof-of-Stake(POS) based
consensus protocol. The consensus mechanism allows the participant
nodes of the decentralized network to come to a consensus or agree on
things like account balances and the order of transactions which prevents
the users from making fake transactions and double-spending their coins.
As Hyperledger is a private and permissioned network, it does not need any
POW or consensus mechanism to validate a transaction. If two participating
parties agree on a specific transaction then no third party can view or
intervene in the specific transaction. This helps to improve the scalability
and transaction rates as well as the performance of the entire network.
8. Speed of Transactions:
As Ethereum is a public domain it has a POW mechanism, which reduces
the transaction speed of Ethereum. That is something close to 20
transactions per second.
For being a permissioned blockchain network, Hyperledger fabric does not
need such a heavy POW mechanism like Ethereum. That increases the
transaction speed. That is around 2000 transactions per second. Which is
far larger than Ethereum.
9. Cryptocurrency:
Ethereum has its own native cryptocurrency called ETHEREUM(ETH).
Any participating node can mine ETH by paying gas.
Hyperledger does not have its native cryptocurrency and it does not involve
in mining.
Feature Ethereum Hyperledger
Public blockchain Private blockchain
Confidentiality
Client-side B2C Enterprise-level B2B
applications applications
Purpose
Ethereum Developers Linux Foundation
Governance
Organizations having
Anyone
Certificate of Authorization
Participation
Programming Solidity Golang, JavaScript, or Java
Language
POW- Proof of Work Pluggable consensus
Consensus
Mechanism mechanism
Mechanism
Less More
Speed of
Feature Ethereum Hyperledger
Transactions
Ether or Ethereum None
Cryptocurrency
When to use what?
The used cases of Ethereum and Hyperledger are mentioned below:
Ethereum:
Public or B2C applications: When the developer or developing
organizations intend to create decentralized applications for customer use,
they can use Ethereum smart contracts. With Ethereum, anyone can join the
network and create a node. Every such node possesses a copy of the entire
blockchain.
Community-led open-source applications: These applications do not
need any confidentiality, and are developed and hosted by blockchain
developer communities around the world. They can be developed using
Ethereum.
Hyperledger:
Private or B2B Applications: Businesses don’t want to keep their
confidential data on a public blockchain like Ethereum. As a permission
blockchain network, Hyperledger can solve this problem. It offers the
facility to create a blockchain application maintaining the privacy of the
information of the organization.
Create customized blockchain algorithms: When an organization or a
business wants to define its own and unique blockchain algorithms
Hyperledger can be very useful. In Hyperledger projects, the whole
underlying infrastructure of the blockchain can be modified. This flexibility
stands out to be a great tool while making customized blockchain
applications for business purposes.
Permissioned Blockchain
A permissioned blockchain is a distributed ledger that is not publicly
accessible. It can only be accessed by users with permissions. The users can
only perform specific actions granted to them by the ledger administrators and
are required to identify themselves through certificates or other digital means.
You might consider the addition of permissioned users as an extra blockchain
security system. Administrators maintain an access control layer to allow
certain actions to be performed only by certain identifiable participants.
Records are kept within the blockchain of who is involved in the transactions.
This makes permissioned blockchains different from public blockchains.
Permissioned blockchains provide an additional level of security over
typical blockchain systems like Bitcoin, as they require an access control
layer.
These blockchains are favored by entities who require security, identity,
and role definition within the blockchain.
Permissioned blockchains are becoming more common as businesses
realize their benefits.