0% found this document useful (0 votes)
19 views

Web 3 Technologies Question's

Uploaded by

4832550
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Web 3 Technologies Question's

Uploaded by

4832550
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Unit I

Blockchain

Q.1 What is Electronic cash? What are the fundamental e-cash issues?

Electronic cash, also known as e-cash or digital cash, refers to a form of electronic
payment that allows users to make financial transactions without the need for physical
currency or credit cards. E-cash is typically stored in a digital wallet and can be used
to make purchases online or in person through the use of a mobile device or another
electronic payment method.
There are several fundamental issues that must be addressed in order to effectively
implement e-cash systems:
1. Security: E-cash systems must be secure to protect against fraud and ensure the
confidentiality of transactions.
2. Privacy: E-cash systems must respect the privacy of users by protecting their
personal and financial information.
3. Scalability: E-cash systems must be able to handle large numbers of
transactions efficiently and without delay.
4. Interoperability: E-cash systems must be able to work with a variety of
different payment systems and devices.
5. Regulation: E-cash systems must comply with relevant laws and regulations
related to financial transactions.
6. User acceptance: E-cash systems must be easy to use and understand in order
to gain widespread adoption.

Q.2 Define Blockchain. Specify the features of the blockchain.

Blockchain is a distributed database that maintains a continuously growing list of


records called blocks. Each block contains a timestamp and a link to the previous
block, forming a chain of blocks. This allows the database to be managed
transparently and without the need for a central authority.

OR
Blockchain is a shared, immutable ledger that facilitates the process of recording
transactions and tracking assets in a business network. An asset can be tangible (a
house, car, cash, land) or intangible (intellectual property, patents, copyrights,
branding). Virtually anything of value can be tracked and traded on a blockchain
network, reducing risk and cutting costs for all involved.

How Blockchain works:


● As each transaction occurs, it is recorded as a “block” of data.
Those transactions show the movement of an asset that can be tangible (a
product) or intangible (intellectual). The data block can record the information
of your choice: who, what, when, where, how much and even the condition —
such as the temperature of a food shipment.

● Each block is connected to the ones before and after it.


These blocks form a chain of data as an asset moves from place to place or
ownership changes hands. The blocks confirm the exact time and sequence of
transactions, and the blocks link securely together to prevent any block from
being altered or a block being inserted between two existing blocks.

● Transactions are blocked together in an irreversible chain: a blockchain.


Each additional block strengthens the verification of the previous block and
hence the entire blockchain. This renders the blockchain tamper-evident,
delivering the key strength of immutability. This removes the possibility of
tampering by a malicious actor — and builds a ledger of transactions you and
other network members can trust.

The features of blockchain are:


1. Decentralization:
In blockchain, decentralization refers to the transfer of control and
decision-making from a centralized entity (individual, organization, or group
thereof) to a distributed network. Decentralized networks strive to reduce the
level of trust that participants must place in one another, and deter their ability
to exert authority or control over one another in ways that degrade the
functionality of the network.
2. Distributed ledger technology:
All network participants have access to the distributed ledger and its immutable
record of transactions. With this shared ledger, transactions are recorded only
once, eliminating the duplication of effort that’s typical of traditional business
networks.
3. Immutable records:
No participant can change or tamper with a transaction after it’s been recorded
to the shared ledger. If a transaction record includes an error, a new transaction
must be added to reverse the error, and both transactions are then visible.
4. Smart contracts:
To speed transactions, a set of rules — called a smart contract — is stored on
the blockchain and executed automatically. A smart contract can define
conditions for corporate bond transfers, include terms for travel insurance to be
paid and much more.

Q.3 Explain in detail- Blockchain architecture./ explain blockchain layers.


A blockchain can be logically defined as a network of blocks that are linked together
and carry specific information (database) in a secure and real manner (peer-to-peer).
In other words, blockchain is a collection of interconnected computers rather than a
single, centralized server, making the entire network decentralized.
Blockchain Architecture essentially includes the following:
1. Transaction:
The smallest units that make up a blockchain system are transactions. They
typically include a value, a recipient address, and a sender address. It resembles
a typical credit card statement in many ways. By digitally signing the hash
created by fusing together the previous transaction and the recipient's public
key, the owner transfers value.
Following the transaction's public announcement to the network, each node
separately maintains a copy of the blockchain, and the current known "state" is
determined by processing each transaction in the blockchain's chronological
order. Every node receives a block consisting of the transaction data. The
network distributes new transactions, which each node independently verifies
and "processes" as they go throughout the system. Every transaction has a
timestamp and is gathered in a block.

2. BlockP2P:
Block is made up of transactions and block header information. Blocks are data
structures that serve as containers for groups of transactions and are replicated
across all network nodes. Miners build blocks in the blockchain. Making a
legitimate block that the rest of the network will accept is called mining. The
pending transactions are collected by nodes, who then confirm their
cryptographical correctness before putting them together into blocks to be
stored on the blockchain. The Block header is the metadata that aids in
confirming a block's validity. Transactions are found in a block's remaining
space. Depending on the miner's preference, a block may include any number
of transactions.

3. NetworkConsensus:
This is a Peer-to-peer (P2P) network based on the IP protocol. It is a flat
topology with no centralized nodes. While working together using a consensus
process, all nodes equally provide and can consume services. Peers contribute
to the storage and computational resources needed for network maintenance.
P2P networks are typically more secure than centralized networks because they
lack a single point of vulnerability.The participants in a private blockchain
must be pre-verified, and they are often parties who are familiar with one
another. Every network node in a typical blockchain design keeps a local copy
of the blockchain. The P2P network on which blockchain design is based is
solely responsible for its decentralization.

4. Algorithm:
A consensus method is responsible for synchronizing all of these copies of a
single ledger. The consensus process makes sure that the local copies that each
party has been the most current and consistent with one another. Each node has
a copy that is identical or comparable to one other. One could argue that the
consensus algorithm serves as the fundamental building element of every
blockchain architecture.
Below are a few of the types of Consensus Algorithms. Proof-of-work
(POW)Proof-of-Stake (POS)Simplified Byzantine Fault Tolerance (SBFT)

Q.4 Explain the Generic elements of a blockchain.


A: Addresses
Addresses are unique identifiers that are used in a transaction on the blockchain to
denote senders and recipients. An address is usually a public key or derived from a
public key. While addresses can be reused by the same user, addresses themselves are
unique. In practice, however, a single user may not use the same address again and
generate a new one for each transaction. This newly generated address will be unique.

Transaction
A transaction is the fundamental unit of a blockchain. A transaction represents a
transfer of value from one address to another.

Block
A block is composed of multiple transactions and some other elements such as the
previous block hash (hash pointer), timestamp, and nonce.

Peer-to-peer network
As the name implies, this is a network topology whereby all peers can communicate
with each other and send and receive messages.

Scripting or programming language


This element performs various operations on a transaction. Transaction scripts are
predefined sets of commands for nodes to transfer tokens from one address to another
and perform various other functions. Turing complete programming language is a
desirable feature of blockchains; however, the security of such languages is a key
question and an area of important and ongoing research.

Virtual machine
This is an extension of a transaction script. A virtual machine allows Turing complete
code to be run on a blockchain (as smart contracts) whereas a transaction script can be
limited in its operation. Virtual machines are not available on all blockchains;
however, various blockchains use virtual machines to run programs, for example
Ethereum Virtual Machine (EVM) and Chain Virtual Machine (CVM).

State machine
A blockchain can be viewed as a state transition mechanism whereby a state is
modified from its initial form to the next and eventually to a final form as a result of a
transaction execution and validation process by nodes.

Nodes
A node in a blockchain network performs various functions depending on the role it
takes. A node can propose and validate transactions and perform mining to facilitate
consensus and secure the blockchain. This is done by following a consensus protocol.
(Most commonly this is PoW.) Nodes can also perform other functions such as simple
payment verification (lightweight nodes), validators, and many other functions
depending on the type of the blockchain used and the role assigned to the node.

Smart contracts
These programs run on top of the blockchain and encapsulate the business logic to be
executed when certain conditions are met. The smart contract feature is not available
in all blockchains but is now becoming a very desirable feature due to the flexibility
and power it provides to the blockchain applications.

Q.5 How blockchain works?/ general scheme for creating blocks.

Q.6 What are the Benefits, features, and limitations of blockchain?


Benefits:

Immutability. Blockchain supports immutability, meaning it is impossible to erase or


replace recorded data. Therefore, the blockchain prevents data tampering within the
network.

Traditional data do not exhibit immutability. The conventional database uses CRUD
(create, read, update and delete) at the primary level to ensure proper application
operation, and the CRUD model enables easy erasing and replacing of data. Such data
can be prone to manipulation by rogue administrators or third-party hacks.

Transparency. Blockchain is decentralized, meaning any network member can verify


data recorded into the blockchain. Therefore, the public can trust the network.

On the other hand, a traditional database is centralized and does not support
transparency. Users cannot verify information whenever they want, and the
administration makes a selected set of data public. Still, however, individuals cannot
verify the data.

Censorship. Blockchain technology is free from censorship since it does not have
control of any single party. Therefore, no single authority (including governments) can
interrupt the operation of the network.

Meanwhile, traditional databases have central authorities regulating the operation of


the network, and the authority can exercise censorship. For instance, banks can
suspend users' accounts.
Traceability. Blockchain creates an irreversible audit trail, allowing easy tracing of
changes on the network.

The traditional database is neither transparent nor immutable; hence, no permanent


trial is guaranteed.

Features:

Distributed consensus
Distributed consensus is the major underpinning of a blockchain. This enables a
blockchain to present a single version of truth that is agreed upon by all parties
without the requirement of a central authority.

Transaction verification
Any transactions posted from nodes on the blockchain are verified based on a
predetermined set of rules and only valid transactions are selected for inclusion in a
block.

Platforms for smart contracts


A blockchain is a platform where programs can run that execute business logic on
behalf of the users.

Transferring value between peers


Blockchain enables the transfer of value between its users via tokens. Tokens can be
thought of as a carrier of value.

Generating cryptocurrency
This is an optional feature depending on the type of blockchain used. A blockchain
can generate cryptocurrency as an incentive to its miners who validate the transactions
and spend resources in order to secure the blockchain.

Limitations:

Speed and performance. Blockchain is considerably slower than the traditional


database because blockchain technology carries out more operations. First, it performs
signature verification, which involves signing transactions cryptographically.

Blockchain also relies on a consensus mechanism to validate transactions. Some


consensus mechanisms, such as proof of work, have a low transaction throughput.
Finally, there is redundancy, where the network requires each node to play a crucial
role in verifying and storing each transaction.

High implementation cost. Blockchain is costlier compared to a traditional database.


Additionally, businesses need proper planning and execution to integrate blockchain
into their process.
Data modification. Blockchain technology does not allow easy modification of data
once recorded, and it requires rewriting the codes in all of the blocks, which is
time-consuming and expensive. The downside of this feature is that it is hard to
correct a mistake or make any necessary adjustments.

Q.7 What are the various types of blockchain?

A:

Public Blockchain

● It is a permissionless distributed ledger on which anybody can join and


conduct transactions.
● It is a non-restrictive form of the ledger in which each peer has a copy. This
also means that anyone with an internet connection can access the public
Blockchain.
● This user has access to historical and contemporary records and the ability to
perform mining operations.
● These complex computations must be performed to verify transactions and
add them to the ledger.
● On the blockchain network, no valid record or transaction may be altered.
Because the source code is usually open, anybody can check the
transactions, uncover problems, and suggest fixes.

Private Blockchain

● A blockchain network operates in a private context, such as a restricted


network, or is controlled by a single identity.
● While it has a similar peer-to-peer connection and decentralization to a
public blockchain network, this Blockchain is far smaller.
● They are often run on a small network within a firm or organization rather
than open to anybody who wants to contribute processing power.
● Permissioned blockchains and business blockchains are two more terms for
them.

Hybrid Blockchain

● Organizations who expect the best of both worlds use a hybrid blockchain,
which combines the features of both private and public blockchains.
● It enables enterprises to construct a private, permission-based system
alongside a public, permissionless system, allowing them to choose who has
access to certain Blockchain data and what data is made public.
● In a hybrid blockchain, transactions and records are typically not made
public, but they can be validated if necessary by granting access via a smart
contract.

Consortium Blockchain
● In the same way that a hybrid blockchain has both private and public
blockchain features, a Consortium blockchain, also known as a federated
blockchain, does.
● However, it differs because it involves various organizational members
working together on a decentralized network.
● Predetermined nodes control the consensus methods in a consortium
blockchain.
● It has a validator node responsible for initiating, receiving, and validating
transactions. Transactions can be initiated or received by member nodes.

Q.8 What are the Consensus mechanisms in a blockchain?


1. A consensus mechanism is a fault-tolerant mechanism that is used in computer
and blockchain systems to achieve the necessary agreement on a single data
value or a single state of the network among distributed processes or
multi-agent systems, such as with cryptocurrencies. It is useful in
record-keeping, among other things.
2. In any centralized system, like a database holding key information about
driving licenses in a country, a central administrator has the authority to
maintain and update the database.
3. The task of making any updates—like adding/deleting/updating names of
people who qualified for certain licenses—is performed by a central authority
who remains the sole in-charge of maintaining genuine records.
4. Public blockchains that operate as decentralized, self-regulating systems work
on a global scale without any single authority.
5. They involve contributions from hundreds of thousands of participants who
work on verification and authentication of transactions occurring on the
blockchain, and on the block mining activities.
6. In such a dynamically changing status of the blockchain, these publicly shared
ledgers need an efficient, fair, real-time, functional, reliable, and secure
mechanism to ensure that all the transactions occurring on the network are
genuine and all participants agree on a consensus on the status of the ledger.
7. This all-important task is performed by the consensus mechanism, which is a
set of rules that decides on the legitimacy of contributions made by the various
participants (i.e., nodes or transactors) of the blockchain.
Q.9 What are the Types of consensus mechanisms?
A: There are two main categories of consensus mechanisms

Proof-based, leader-election lottery-based, or the Nakamoto consensus: whereby a


leader is elected at random (using an algorithm) and proposes a final value.
This category is also referred to as the fully decentralized or
permissionless type of consensus mechanism.

This type is well used in the Bitcoin and Ethereum blockchain in the
form of a PoW mechanism.

Byzantine fault tolerance (BFT)-based is a more traditional approach based on


rounds of votes.

This class of consensus is also known as the consortium or permissioned type of


consensus mechanism.

The different types of consensus algorithms are as follows:

Proof of Work (PoW):


- This type of consensus mechanism relies on proof that adequate computational
resources have been spent before proposing a value for acceptance by the
network.
- This scheme is used in Bitcoin, Litecoin, and other cryptocurrency blockchains.

Proof of Stake (PoS):


- This algorithm works on the idea that a node or user has an adequate stake in
the system.
- The user has invested enough in the system so that any malicious attempt by
that user would outweigh the benefits of performing such an attack on the
network.
- Another important concept in PoS is coin age, which is a criterion derived from
the amount of time and number of coins that have not been spent.
- In this model, the chances of proposing and signing the next block increase
with the coin age.

Delegated Proof of Stake (DPoS):


- This is an innovation over standard PoS whereby each node that has a stake in
the system can delegate the validation of a transaction to other nodes by voting.
- It is used in the BitShares blockchain.

Proof of Elapsed Time (PoET):


- PoET uses a Trusted Execution Environment (TEE) to provide randomness and
safety in the leader election process via a guaranteed wait time.
Proof of Deposit (PoD):
- Nodes that wish to participate in the network have to make a security deposit
before they can mine and propose blocks.
- This mechanism is used in the Tendermint blockchain.

Proof of Importance (PoI):


- PoI not only relies on how large a stake a user has in the system, but it also
monitors the usage and movement of tokens by the user in order to establish a
level of trust and importance.
- It is used in the NEM coin blockchain.

Federated consensus or federated Byzantine consensus: Nodes in this protocol


retain a group of publicly-trusted peers and propagate only those transactions that
have been validated by the majority of trusted nodes.

Proof of Activity (PoA):


- This scheme is a combination of PoS and PoW, which ensures that a
stakeholder is selected in a pseudorandom but uniform fashion.
- PoW and PoS are combined together to achieve consensus and a good level of
security.
- This scheme is more energy efficient as PoW is used only in the first stage of
the mechanism; after the first stage, it switches to PoS.

Proof of Capacity (PoC):


- This scheme uses hard disk space as a resource to mine the blocks.
- In PoC, hard disk space is utilized for mining and, as such, is also known as
hard drive mining.
- This concept was first introduced in the BurstCoin cryptocurrency.

Proof of Storage:
- This scheme allows for the outsourcing of storage capacity.
- This scheme is based on the concept that a particular piece of data is probably
stored by a node, which serves as a means to participate in the consensus
mechanism.
- Several variations of this scheme have been proposed, such as Proof of
Replication, Proof of Data Possession, Proof of Space, and Proof of
Space-time.
Proof of Authority (PoA):
- This scheme utilizes the identity of the participants called validators as a stake
on the network.
- Validators are known and have the authority to propose new blocks.
- Validators propose the new blocks and validate them as per blockchain rules.
- Commonly used PoA algorithms are Clique and Aura.
Q.10 Explain CAP theorem.
A:
1. CAP Theorem stands for Consistency, Availability, and Partition Tolerance.
According to the theory, a distributed system cannot always ensure consistency,
availability, and partition tolerance. When things go wrong, we must prioritize
at most two distributed system features and trade-offs between them.
2. CAP Theorem or Brewer’s theorem states that it is feasible to provide either
consistency or availability—but not both—in the event of a network failure on
a distributed database, a theory from theoretical computer science about
distributed data stores. In other words, according to the CAP theorem, a
distributed database system that experiences a partition must choose between
Consistency and Availability.
3. We must simultaneously communicate over the network and store data among
several nodes in a distributed system. A distributed system frequently falls
victim to network failures because of its reliance on network calls in a
significant way. Tolerance for partitions is crucial. In this situation, we must
decide, based on our needs, whether to prioritize consistency or availability.
4. With blockchain technology, immediate consistency is frequently sacrificed for
availability and partition tolerance. By requiring a specific amount of
“confirmations,” blockchain consensus techniques are simply simplified to
eventual consistency.
5. Network failures can affect any distributed system, hence network partitioning
is usually required. There are just two choices remaining in the event of a
partition: consistency or availability. The system will return an error or time out
if a specific piece of information cannot be guaranteed to be current owing to
network segmentation when consistency is chosen above availability.
6. The system will always process the query and attempt to return the most recent
version of the data even if it cannot ensure that it is up to date because of
network partitioning when availability is preferred over consistency.
7. Blockchain is a decentralized database that manages a shared ledger that cannot
be altered. Transactions are what make up the shared ledger. Consensus
techniques are used to record transactions inside the shared ledger. Sharing
distributed transactions naturally raises questions about the CAP theorem.
8. Consistency is sacrificed in Blockchain due to the priority given to Availability
and Partition Tolerance. In this case, Partition tolerance (P), Availability (A),
and Consistency (C) on the blockchain are not attained simultaneously; instead,
they are acquired over time.

Q.11 What are the Methods of decentralization?


A: Two methods:
1. Disintermediation:
a. The concept of disintermediation can be explained with the aid of an
example.
b. Imagine that you want to send money to a friend in another country. You
go to a bank, which, for a fee, will transfer your money to the bank in
that country. In this case, the bank maintains a central database that is
updated, confirming that you have sent the money.
c. With blockchain technology, it is possible to send this money directly to
your friend without the need for a bank.
d. All you need is the address of your friend on the blockchain. This way,
the intermediary (that is, the bank) is no longer required, and
decentralization is achieved by disintermediation.
e. It is debatable, however, how practical decentralization through
disintermediation is in the financial sector due to the massive regulatory
and compliance requirements.
f. Nevertheless, this model can be used not only in finance but in many
other industries as well, such as health, law, and the public sector. In the
health industry, where patients, instead of relying on a trusted third party
(such as the hospital record system) can be in full control of their own
identity and their data that they can share directly with only those
entities that they trust.
g. As a general solution, blockchain can serve as a decentralized health
record management system where health records can be exchanged
securely and directly between different entities (hospitals,
pharmaceutical companies, patients) globally without any central
authority.
2. Contest-driven decentralization
a. In the method involving competition, different service providers compete with
each other in order to be selected for the provision of services by the system.
b. This paradigm does not achieve complete decentralization. However, to a
certain degree, it ensures that an intermediary or service provider is not
monopolizing the service. In the context of blockchain technology, a system
can be envisioned in which smart contracts can choose an external data
provider from a large number of providers based on their reputation, previous
score, reviews, and quality of service.
c. This method will not result in full decentralization, but it allows smart contracts
to make a free choice based on the criteria just mentioned. This way, an
environment of competition is cultivated among service providers where they
compete with each other to become the data provider of choice.
😣Q.12 How to decentralize the system?
A: 0

Q.13 What is Decentralized organizations?


A:
1. Decentralization in business is when daily operations and decision-making
power are delegated by top management to middle-and lower-level managers
— and sometimes even team members.
2. Organizations with a decentralized structure allow upper management to focus
more on growth opportunities and major decisions, rather than day-to-day
duties.
3. Traditional decentralized approaches may still apply rigid frameworks with
checks and controls, while radical types of decentralization extend the scope of
decision-making.
4. The key idea behind a decentralized approach is giving authority and
responsibility to those who know best — since they’re closer to stakeholders
and have relevant information available to them.
5. For example, a personal banker who orders debit cards every day for their
customers will be able to spot debit card issues faster than upper management
could.
6. Rather than sending customers with debit card issues to top management, they
can use the information that’s readily available to them to solve the customers’
problems directly.
7. A company with a decentralized organizational structure is one where
mid-level and lower-level managers make most of the decisions, rather than the
senior management team.
8. Sometimes, management even involves team members in the decision-making
process.
9. This differs from a centralized organization, in which the highest-ranking
leaders within the company make all major decisions, and there's a strict
decision-making hierarchy.
10. Few companies qualify as fully decentralized or centralized. Rather, most have
various degrees of both.
Q.14 What are the Platforms for decentralization?
A:
Written By Chat GPT:
There are several platforms that support decentralization and enable the creation of
decentralized applications (DApps):
Ethereum: One of the most popular platforms for building DApps, Ethereum is a
decentralized, open-source blockchain platform that enables the creation of smart
contracts and DApps. It uses its own programming language, Solidity, to write smart
contracts.
EOS: EOS is a decentralized operating system that supports the deployment of DApps
and smart contracts. It uses a unique consensus algorithm called delegated
proof-of-stake (DPoS) to secure its network.
Tron: Tron is a decentralized blockchain platform that aims to decentralize the
internet. It supports the creation of DApps and smart contracts and uses a DPoS
consensus algorithm.
NEO: NEO is a decentralized platform for the creation of smart contracts and DApps.
It uses a unique consensus algorithm called delegated Byzantine Fault Tolerance
(dBFT) to secure its network.
Cardano: Cardano is a decentralized, open-source blockchain platform that supports
the creation of smart contracts and DApps. It uses a unique proof-of-stake consensus
algorithm called Ouroboros to secure its network.
These are just a few examples of the platforms that support decentralization. There are
many other platforms out there, each with their own unique features and capabilities.

Q.15 Explain Decentralized finance.


A:
1. Decentralized finance (DeFi) is an emerging financial technology based on
secure distributed ledgers similar to those used by cryptocurrencies.
2. DeFi eliminates the fees that banks and other financial companies charge for
using their services. Individuals hold money in a secure digital wallet, can
transfer funds in minutes, and anyone with an internet connection can use DeFi.
3. Decentralized finance eliminates intermediaries by allowing people, merchants,
and businesses to conduct financial transactions through emerging technology.
Through peer-to-peer financial networks, DeFi uses security protocols,
connectivity, software, and hardware advancements.
4. Wherever there is an internet connection, individuals can lend, trade, and
borrow using software that records and verifies financial actions in distributed
financial databases.
5. A distributed database is accessible across various locations as it collects and
aggregates data from all users and uses a consensus mechanism to verify it.
6. Decentralized finance uses the blockchain technology that cryptocurrencies
use. Applications called dApps are used to handle transactions and run the
blockchain.
7. In the blockchain, transactions are recorded in blocks and then verified by other
users. If these verifiers agree on a transaction, the block is closed and
encrypted; another block is created that has information about the previous
block within it.
8. Peer-to-peer (P2P) financial transactions are one of the core premises behind
DeFi. A P2P DeFi transaction is where two parties agree to exchange
cryptocurrency for goods or services without a third party involved.
9. In DeFi, P2P can meet an individual's loan needs, and an algorithm would
matches peers that agree on the lender's terms, and a loan is issued. Payments
from P2P are made via a decentralized application, or dApp, and follow the
same process in the blockchain.
10. Using DeFi allows for:
a. Accessibility: Anyone with an internet connection can access a DeFi
platform and transactions occur without any geographic restriction.
b. Low fees and high-interest rates: DeFi enables any two parties to
directly negotiate interest rates and lend money via DeFi networks.
c. Security and Transparency: Smart contracts published on a blockchain
and records of completed transactions are available for anyone to review
but do not reveal your identity. Blockchains are immutable, meaning
they cannot be changed.
d. Autonomy: DeFi platforms don't rely on any centralized financial
institutions and are not subject to adversity or bankruptcy. The
decentralized nature of DeFi protocols mitigates much of this risk.

Bitcoin

Q.1 How can money be sent using the Bitcoin network from one user to another?
In order to send bitcoin to another person or another wallet, you need the public
bitcoin wallet address of the receiver.
You don’t need the private keys, passphrase or seed phrase for the other wallet, and
those should be kept private by the owner at all times. The public bitcoin address is a
string of 34 letters and numbers, but most bitcoin wallets also represent it as a QR
code.
So, the person (or machine) receiving the bitcoin can also show a QR code that the
sender can scan with their own mobile wallet app.
While every wallet app will be a little bit different, this is basically how the process
goes:
1. Open your bitcoin wallet, click on “Send” and choose the currency if there’s
more than one option.
2. Paste the receiving bitcoin wallet address in the “To” field, or scan their QR
code.
3. Enter the amount you’re sending.
4. If applicable, choose your Transaction Fee setting. Regular fees cost less but
take longer whereas Priority fees cost more but finish faster.
5. After verifying that everything is correct, choose “Send Bitcoin.”
6. After you send the funds, the transaction goes to the blockchain network where
it’s verified and confirmed by Bitcoin miners

Q.2 Explain Cryptographic keys.


In cryptography a ‘key’ is a piece of information used in combination with an
algorithm (a ‘cipher’) to transform plaintext into ciphertext (encryption) and vice
versa (decryption).

Symmetric Cryptography:
In symmetric cryptography, both sender and receiver use the same secret key to
encrypt and decrypt a message.Some of the algorithms includes Blowfish, AES, RC4,
DES, RC5, and RC6. The most widely used symmetric algorithm is AES-128,
AES-192, and AES-256. All AES algorithms use the block size of 128-bit but
different size of key lengths (128, 192, 256).

Asymmetric Cryptography?:
Asymmetric cryptography uses key pairs — public and private key. It works in a way,
message encrypted with either public or private key can only be decrypted using the
other key of the pair.
That is a public key to encrypt, private key to decrypt and private key to encrypt,
public key to decrypt. Public keys are disseminated in public networks whereas
private keys are only known to the owners.
This key pair cryptography differs from symmetric cryptography which uses one
secret key. Some of the algorithms includes RSA, ELC, Diffie-Helman key exchange,
etc. Asymmetric Cryptography has 2 usages, data encryption and digital signature.

Q.3 Explain Addresses in Bitcoin.


A Bitcoin address is a unique identifier that serves as a virtual location where the
cryptocurrency can be sent.
People can send the cryptocurrency to Bitcoin addresses similarly to the way fiat
currencies can often be sent to email addresses.
However, the Bitcoin address is not intended to be permanent, but just a token for use
in a single transaction.
Unlike a digital wallet, a Bitcoin address cannot hold a balance. The address itself
consists of 26-35 alphanumeric characters.
This string is the public half of an asymmetric key pair. The standard format for a
Bitcoin address is P2PKH (pay to public key hash).
Digital wallets or Bitcoin clients generate addresses through cryptographic operations:
The software generates a private key through an asymmetric signature algorithm and
then derives the public key from the private one.
The user signs with the private key and verifies that signature with the public key.
When Bitcoin first started, people could send the currency to an IP address. That was
a convenient method for users but it quickly became apparent that it would also be
convenient for people launching man-in-the-middle attacks.
That method was discontinued and the Bitcoin address was devised as a more secure
alternative.
Most other cryptocurrencies use similar technologies for funds transfer. The Bitcoin
address is one type of blockchain address.

Q.4 Explain the steps of the lifecycle of a Bitcoin transaction.


A bitcoin transaction consists of three main components, these are inputs, outputs, and
the amount that is intended to be transferred between parties.
1. Person A logs in to his Blockchain Wallet and initiates a transaction with Person B.
(Wallets are basically UI which simplifies a user’s interaction with the Blockchain.
2. Every block has a size and capacity, several transactions similar to this will be
grouped into a block till the time the block is full
3. The data in the Block is validated using a consensus algorithm to ensure the
authenticity of the information. The nodes which validate the authenticity get
rewarded with cryptocurrency.
4. Once a block is validated, it is put in the blockchain and all the copies of the ledger
get updated. Now everybody has the updated ledger depicting a single story of the
truth.
5. Person B now receives the transaction from Person A.
OR
Creation: A user creates a new transaction by specifying the details of the transaction,
including the recipient's address, the amount of Bitcoin to be sent, and any necessary
fees. The user must also provide their own address and the private key associated with
that address to sign the transaction and prove ownership.
Broadcast: The user broadcasts the transaction to the Bitcoin network. This can be
done by sending the transaction to a specific node or through a network of nodes.
Validation: Once the transaction is received by the network, it is validated to ensure
that it is properly formatted and that the user has the necessary funds to complete the
transaction. If the transaction is valid, it is added to a pool of unconfirmed
transactions.
Mining: Miners on the network compete to solve a complex mathematical problem in
order to validate transactions and add them to the blockchain. When a miner
successfully solves the problem and adds a block of transactions to the blockchain,
they are rewarded with a certain number of Bitcoin.
Confirmation: Once a transaction has been added to the blockchain, it is considered to
be confirmed. The number of confirmations a transaction has is the number of blocks
that have been added to the blockchain after the block that contains the transaction.
The more confirmations a transaction has, the more secure it is considered to be.
Completion: Once a transaction has been confirmed, it is considered to be complete.
The recipient can now use the received funds.

😣Q.5 Explain The transaction data structure.


Q.6 What are Stale and orphan blocks? Genesis blocks?
Stale Blocks In Bitcoin, when two blocks reach a person, a fork in the blockchain is
created.
So no one can be sure which block is a part of the main chain and which is going to be
discarded. Bitcoin follows the rule of the longest chain.
This means that the chain with the most blocks will be considered the main chain and
the ultimate truth, discarding other forks.
This means, which block gets to be a part of the main chain, depends on the next
block. Whichever chain receives the next block will become the longer one, and hence
will be the main chain discarding the other chain.
The blocks that are part of the discarded chain, i.e. not part of the main chain, are said
to be stale blocks.
Orphan Blocks :Orphan blocks in Bitcoin are often a point of confusion for many
people. Orphan blocks are simply blocks for which a particular node doesn’t have the
parent yet.
This does not mean the block is invalid or it is not included in the main chain, it
simply means that the node cannot verify the block at the moment, and has to ask its
peers for its parents first.
Orphan blocks are not a network-wide condition but node specific meaning if one
node doesn’t have the parents of the block it has received, it is that particular node’s
problem and not a problem of the network that affects everyone.
The genesis block is the first ever block recorded on its respective blockchain
network, also occasionally referred to as Block 0 or Block 1.
When a block is broadcasted to the blockchain, it references the previous block.
However, in the case of the genesis block, there is no previous block to reference.
Because there is no previous block to reference,
genesis blocks are generally hardcoded into the software. In terms of Bitcoin, the
genesis block was on the 3rd of January 2009.
This block had a reward of 50 BTC that is forever unspendable. It is unknown as to
whether the genesis block’s reward was intentionally unspendable as there was no
explanation regarding this from Satoshi Nakamoto.

😣
A:
Q.7 Write a short note on Mining./the mining algorithm.

Q.8 What is a mining pool?


A: 1. A mining pool is a joint group of cryptocurrency miners who combine their
computational resources over a network to strengthen the probability of finding a
block or otherwise successfully mining for cryptocurrency.

2. Individually, participants in a mining pool contribute their processing power toward


the effort of finding a block. If the pool is successful in these efforts, they receive a
reward, typically in the form of the associated cryptocurrency.

3. Rewards are usually divided between the individuals who contributed, according to
the proportion of each individual's processing power or work relative to the whole
group. In some cases, individual miners must show proof of work in order to receive
their rewards.

4. Anyone who wants to make a profit through cryptocurrency mining has the choice
to either go solo with their own dedicated devices or to join a mining pool where
multiple miners and their devices combine to enhance their hashing output. For
example, attaching six mining devices that each offer 335 megahashes per second
(MH/s) can generate a cumulative 2 gigahashes of mining power, thereby leading to
faster processing of the hash function.

5. Not all cryptocurrency mining pools function in the same way. There are, however,
a number of common protocols that govern many of the most popular mining pools.
6. Proportional mining pools are among the most common. In this type of pool, miners
contributing to the pool's processing power receive shares up until the point at which
the pool succeeds in finding a block. After that, miners receive rewards proportional
to the number of shares they hold.

7. Pay-per-share pools operate somewhat similarly in that each miner receives shares
for their contribution. However, these pools provide instant payouts regardless of
when the block is found. A miner contributing to this type of pool can exchange
shares for a proportional payout at any time.

8. Peer-to-peer mining pools, meanwhile, aim to prevent the pool structure from
becoming centralized. As such, they integrate a separate blockchain related to the pool
itself and designed to prevent the operators of the pool from cheating as well as the
pool itself from failing due to a single central issue.

😣Q.9 Protocol messages used with the bitcoin network?


Q.10 What is Wallet? Explain the types.
A crypto wallet is a digital or software-based way to access your cryptocurrencies.
Unlike a regular wallet, a crypto wallet doesn’t actually hold your assets. Instead, it
stores credentials called private keys that give you access to your assets on the
blockchain.
Depending on the type of crypto wallet you have, you can: Send, receive, and pay
with crypto Store crypto Create a digital “vault” online that only you can access
Interact with web3 applications that let you lend and borrow against your crypto Buy,
sell, and store NFTs Earn on your crypto in a crypto rewards account
crypto wallets store your public and private keys as well as a linked receiving address
so you can send and receive crypto securely How a crypto wallet works Crypto
wallets consist of three parts: a public key, a private key, and a public receiving
address.
Whenever someone sends crypto from their wallet, they must use their private key to
“sign,” or confirm, the transaction. This digital signature is like a fingerprint, unique
to each individual and their private key, proving that the transaction is coming from
the legitimate owner of the wallet and hasn’t been tampered with.
Q.11 Bitcoin payment procedure.
Same as gpay
open gpay
select receiver
make sure your bank has enough funds
send money
enter pin
done

Q.12 What are the types of Bitcoin Improvement Proposals?


A Bitcoin Improvement Proposal (BIP) is a formal proposal to change Bitcoin. As a
piece of software, Bitcoin is always undergoing upgrades—bugs need to be fixed,
algorithms can be made more efficient, code can be simplified, compatibility with
other software must be maintained, and new features can be added.
The 3 Types of BIPs
1. Standards Track BIPs Any proposal that sought changes to the Bitcoin protocol is
called a Standard Track BIP, including block data, or altering the process of validating
transactions within the ecosystem. It can also cover the attempt to change the
interoperable functions between two BIPs. This attempt needs consensus before it
becomes operational. BIP 91 can best represent this type.
2. Informational BIPs This type of BIP focuses on general guidelines, design issues,
and other information that does not seek too much attention from the Bitcoin
community in general.
3. Process BIPs This type involves proposals that are seeking to improve changes in
the core processes running the Bitcoin ecosystem. It is similar to Standard Track BIPs
as they need a consensus vote for a major change to be implemented.
Unit II

Smart Contracts

Q.1 What is a smart contract? Explain its properties.


Smart contracts are simply programs stored on a blockchain that run when
predetermined conditions are met. They typically are used to automate the execution
of an agreement so that all participants can be immediately certain of the outcome,
without any intermediary’s involvement or time loss. They can also automate a
workflow, triggering the next action when conditions are met.

A smart contract is a self-executing contract with the terms of the agreement between
buyer and seller being directly written into lines of code. The code and the agreements
contained therein exist across a distributed, decentralized blockchain network. The
code controls the execution, and transactions are trackable and irreversible.

Smart contracts permit trusted transactions and agreements to be carried out among
disparate, anonymous parties without the need for a central authority, legal system, or
external enforcement mechanism.
● Speed, efficiency and accuracy
Once a condition is met, the contract is executed immediately. Because smart
contracts are digital and automated, there’s no paperwork to process and no
time spent reconciling errors that often result from manually filling in
documents.
● Trust and transparency
Because there’s no third party involved, and because encrypted records of
transactions are shared across participants, there’s no need to question whether
information has been altered for personal benefit.
● Security
Blockchain transaction records are encrypted, which makes them very hard to
hack. Moreover, because each record is connected to the previous and
subsequent records on a distributed ledger, hackers would have to alter the
entire chain to change a single record.
● Savings
Smart contracts remove the need for intermediaries to handle transactions and,
by extension, their associated time delays and fees.

Incase Somone is planning to break the above points in detail like me


● Secure: Cryptography is used to secure contracts and stop people from altering records.
While the technology is highly secure in most instances, there have been several cases
where SC have been hacked and the funds deposited withdrawn [2].
● Transparent: When running on public networks, anyone can see what the smart contract is
and what it’s being used for.
● Free of third-parties: As we presented initially, smart contracts don’t need a middleman to
be involved in the verification process.
● Near real-time execution: Although dependent on the underlying networks’ throughput
and congestion, smart contracts usually take place almost simultaneously for all parties,
across participating computers, once the necessary criteria are satisfied.
● Autonomous and decentralized: SC’s work automatically, so you’re not having to wait for
someone to push a button. Additionally, once deployed, they can’t be changed or
controlled by any centralized party (like banks, brokers, or even by the network).
● Accurate: Because smart contracts are written in code, they don’t rely on the grey areas of
a language and what words mean. This can pose an inconvenience, especially when grey
areas that require flexible solutions exist.

Q.2 Explain standard mechanics of how oracles work.


1. Oracles offer access to a path for the decentralized Web3 ecosystem where
decentralization and digitization are the core underlying features. They are a
dedicated entity that links a blockchain platform to existing external data
sources to facilitate the execution of smart contracts based on real-world
information.
2. They are recognized as Decentralized Oracle networks or DON’s, oracles help
the Web3.0 cluster seamlessly access data junctions, legacy channels, and
advanced computations without any hassle. They aid developers in building
hybrid smart contracts in which there exists a combination of on-chain code
and off-chain infrastructure for supporting innovative Dapp projects.
3. Where on-chain data exists within the blockchain network, off-chain data
resonates outside of the ecosystem. Firms and entities using blockchain
technology, join hands with renowned oracle networks link Chainlink to
expand their capacities.
4. Oracles play a significant role in widening the scope for the operability of
smart contracts. Conversely, a lack of blockchain oracle would limit the use of
smart contracts.
5. Oracles are not just the links between the blockchains and the external world;
rather they are an infrastructural layer that increases the efficiency of the core
network.
6. The oracles query, verify and authenticate external data resources before wiring
them to the requesting parties.
7. All oracle networks perform three important functions:
A. Collection of data from a reliable external source.
B. Sending the information on-chain using a signed message.
C. Making the data source accessible for end users by storing it safely in
the form of smart contracts.
8. Once the data is stored in a smart contract, other automated agreements can
easily access it through message calls that refer to the “retrieve” feature. The
data can also be used directly by Ethereum nodes or network participants by
accessing the storage section of the Oracle system.

Q.3 Explain Software and network-assisted proofs.

Note the following answer is written by an AI , However I can vouch that it's
correct.

Software-assisted proofs, also known as zero-knowledge proofs, are a type of


cryptographic technique that allows one party (the prover) to prove to another party
(the verifier) that they possess certain information, without revealing the actual
information. This can be useful in a variety of contexts, including in smart contracts,
where it can enable parties to verify the correctness of a computation or other
statement without having to reveal the underlying data.

In the context of smart contracts, software-assisted proofs can be used to enable


verifiable computations, where a prover can prove to a verifier that a computation has
been performed correctly without revealing the input data or intermediate results of
the computation. This can be useful in a variety of contexts, such as in the verification
of financial transactions or other sensitive data.

Network-assisted proofs, on the other hand, are a type of cryptographic technique that
enables a prover to prove to a verifier that a statement is true by relying on the
consensus of a network of nodes. In the context of smart contracts, network-assisted
proofs can be used to enable decentralized verifications of statements, such as the
verification of the authenticity of a document or the existence of a particular asset.

Overall, both software-assisted proofs and network-assisted proofs are useful tools for
enabling verifiable computations and statements in smart contracts, and can be used to
increase the security and trustworthiness of these systems.

Q.4 What are the Types of blockchain oracles?


There are various types of Oracles such as:
1. Inbound oracles:
Inbound oracles receive off-chain information and bring them to the blockchain
so it can be used in the smart contract. For example, oracles that get the price
information of cryptocurrencies or assets from exchanges are inbound oracles.
2. Outbound oracles:
Outbound oracles are less common, they transmit information from the
blockchain to an outside source. An oracle that transmits the circulating supply
of a cryptocurrency to a website or a smart lock that unlocks when the payment
has been made in the blockchain are examples of outbound oracles.
3. Software oracles:
Software oracles get their information from digital sources such as APIs,
databases, and websites.
4. Hardware oracles:
Hardware oracle’s information comes from real-world sources such as sensors
and IoT devices. For example, Chainlink has developed oracles that can
interact with RFID sensors and collect data.
5. Human oracles:
Individuals with specialized knowledge or talents in a specific sector can
sometimes act as oracles. They may gather information from a variety of
sources and check if they are legitimate. Because human oracles may use
cryptography to authenticate their identity, the chances of a fraudster
impersonating them and giving tampered data are slim.
6. Centralized:
Centralized oracles are controlled by a single entity and rely on a single data
source. Centralized oracles are risky as they are a single source of failure if
they get hacked, manipulated, or shut down. This leads to counterparty risk
which defeats the purpose of smart contracts as they are supposed to be
trustless.
7. Decentralized:
A decentralized oracle does not rely on a single oracle node and data source. It
combines independent oracle operators and different data sources and brings
them into the blockchain to reach a single conclusion. Decentralized oracles
solve the problem of single source of failure in centralized oracles. If one of the
oracles fails to function as intended for any reason, the smart contract will be
able to function as planned.

Ethereum

Q.1 Why is the Ethereum blockchain considered as a state transition function?

The EVM behaves as a mathematical function would: Given an input, it produces a


deterministic output. It therefore is quite helpful to more formally describe Ethereum as
having a state transition function:

1
Y(S, T)= S'
2

Given an old valid state (S) and a new set of valid transactions (T), the Ethereum state
transition function Y(S, T) produces a new valid output state S'

State

In the context of Ethereum, the state is an enormous data structure called a modified Merkle
Patricia Trie, which keeps all accounts linked by hashes and reducible to a single root hash
stored on the blockchain.

Transactions

Transactions are cryptographically signed instructions from accounts. There are two types of
transactions: those which result in message calls and those which result in contract creation.

Contract creation results in the creation of a new contract account containing compiled smart
contract bytecode. Whenever another account makes a message call to that contract, it
executes its bytecode.

- The Ethereum blockchain is considered a state transition function because it allows


users to transition the state of the system from one state to another by executing smart
contracts.
- In Ethereum, the state of the system is represented by the current state of all the
accounts on the network. An account can be either an external account controlled by a
human user or a contract account controlled by code.
- When a user sends a transaction to the Ethereum network, it is processed by the
Ethereum Virtual Machine (EVM), which executes the code associated with the
transaction and updates the state of the system accordingly. This process is known as
a state transition.
- The state transition function in Ethereum is deterministic, meaning that given a
particular input, the output will always be the same. This ensures that all parties
involved in a transaction can agree on the outcome and helps to prevent disputes.
- Overall, the state transition function is an important part of the Ethereum blockchain
because it allows for the execution of smart contracts and the updating of the system
state in a transparent and secure manner.
Q.2 What are the types of Ethereum networks?
Ethereum is a protocol that runs on thousands of computers simultaneously. It uses
blockchain technology to create distributed ledgers, which replace websites like
Facebook and YouTube by decentralizing the network among users.
To have control over the shared blockchain, Ethereum employs different types of
networks called “clusters” that are composed of individual “nodes” that are linked
together in a peer-to-peer network.
A node typically has an Ethereum client software running on it, and each node has a
full copy of all other nodes’ databases
Therefore, each node can independently verify and query the blockchain, which
prevents malicious or rogue nodes from manipulating the shared information.

There are four types of Ethereum networks:


1. Public mainnet:
The public Ethereum network has two variations: Homestead and Metropolis.
The first one was launched in March 2015 via a hard fork which resulted in a
different set of network parameters that enabled smart contract transactions.
In 2016, the Foundation planned another hard fork called Metropolis to
improve efficiency and flexibility when dealing with transactions and smart
contracts on the blockchain.
With the new hard fork come both the public mainnet (Metropolis) and the
testnet (Ropsten).

2. Private mainnet:
In a private Ethereum network, membership is controlled and limited to certain
users who are carefully selected by administrators. It is used to protect against
malicious attacks and limit access only to trusted parties — which makes it an
ideal solution for companies looking to develop applications based on
cryptocurrency.
Private networks can be built in-house or hosted by a third-party service
provider such as Microsoft Azure or Amazon Web Services.

3. Testnet:
The testnet is used by those who want to experiment with their code before
launching it on the mainnet. Users who want to try out the testnet can create a
new node and join the network — or they can connect their private networks to
the public testnet.
A functional public testnet is a necessary component of an Ethereum-based app
as most developers use it to test their apps, smart contracts, and other solutions
based on blockchain technology.

4. Whisper Network (sharding):


The Whisper Network was originally developed as a platform for private
messaging between users in an Ethereum-based app or decentralized
application (dapp).
To understand how the Whisper Network works, it is necessary to have a basic
understanding of “sharding”.
The network is made up of shards that are linked together by the use of
complex cryptography. Each of these shards can contain multiple nodes and are
collectively updated by their leader nodes at specific intervals.
The Whisper Network uses a combination of high-speed encryption developed
by the Ethereum Foundation, sharding technology, and distributed storage
solutions.
As an application developer, one can control each node in the network through
the use of smart contracts: The person receiving the message will receive
“signed” proof that their counterpart has read and accepted the message.

Sharding drastically reduces the amount of work that a full node must do to
maintain the state of a decentralized application (dapp).
Rather than using a large number of full nodes to ensure security, only the
nodes that need to be updated are updated.
There is also no need for the network leader (or “faucet”) node anymore.

Alternative Answer

There are two broad categories of Ethereum:

Public Ethereum
Public networks are accessible to anyone in the world with an internet connection.
Anyone can read or create transactions on a public blockchain and validate the
transactions being executed. The consensus among peers decides on the inclusion of
transactions and the state of the network.

The public ethereum consists of the following networks:


- Ethereum Mainnet : Mainnet is the primary public Ethereum production
blockchain, where actual-value transactions occur on the distributed ledger.
When people and exchanges discuss ETH prices, they're talking about Mainnet
ETH.
- Ethereum Testnet : In addition to Mainnet, there are public testnets. These are
networks used by protocol developers or smart contract developers to test both
protocol upgrades as well as potential smart contracts in a production-like
environment before deployment to Mainnet. Think of this as an analog to
production versus staging servers.

You should test any contract code you write on a testnet before deploying to
Mainnet. Among dapps that integrate with existing smart contracts, most
projects have copies deployed to testnets.
You can also choose between which testnet you would like to play around with
like Sepolia , Goreli , etc.
- Layer 2 Testnets: Layer 2 (L2) is a collective term to describe a specific set of
Ethereum scaling solutions. A layer 2 is a separate blockchain that extends
Ethereum and inherits the security guarantees of Ethereum. Layer 2 testnets are
usually tightly coupled to public Ethereum testnets.
Private Ethereum
An Ethereum network is a private network if its nodes are not connected to a public
network (i.e. Mainnet or a testnet). In this context, private only means reserved or
isolated, rather than protected or secure.

There are two ways you can have your own private ethereum network:
- Development networks : To develop an Ethereum application, you'll want to run
it on a private network to see how it works before deploying it. Similar to how
you create a local server on your computer for web development, you can
create a local blockchain instance to test your dapp. This allows for much faster
iteration than a public testnet.
- Consortium networks: The consensus process is controlled by a predefined set
of nodes that are trusted. For example, a private network of known academic
institutions that each govern a single node, and blocks are validated by a
threshold of signatories within the network.

If a public Ethereum network is like the public internet, a consortium network


is like a private intranet.

Q.3 What are the Components of the Ethereum ecosystem?


https://www.geeksforgeeks.org/components-of-ethereum-network/
Ethereum is a decentralized, open-source blockchain platform that runs smart
contracts: applications that run exactly as programmed without any possibility of
downtime, censorship, fraud, or third-party interference. Ethereum is powered by the
Ethereum Virtual Machine (EVM), which executes smart contracts in a decentralized
manner.
There are several key components of the Ethereum network:
1. Ethereum Virtual Machine (EVM): This is a decentralized virtual machine that
executes smart contracts on the Ethereum network. The EVM is powered by
nodes on the network and executes the code of a smart contract in a
deterministic and sandboxed environment.
2. Ethereum Gas: Gas is the internal pricing for executing smart contracts on the
Ethereum network. Each operation within a smart contract requires a certain
amount of gas to be executed, and the cost of gas is paid in Ether (ETH), the
native cryptocurrency of the Ethereum network.
3. Ethereum Blockchain: The Ethereum blockchain is a decentralized, distributed
ledger that records all transactions and smart contract executions on the
network. The Ethereum blockchain is secured by a network of nodes, which
validate and record transactions on the blockchain.
4. Ethereum Accounts: There are two types of accounts on the Ethereum network:
externally owned accounts (EOAs) and contract accounts. EOAs are controlled
by private keys and are used to send transactions and interact with smart
contracts. Contract accounts are created by smart contracts and are used to
store data and execute code.
5. Ethereum Smart Contracts: Smart contracts are self-executing contracts with
the terms of the agreement between buyer and seller being directly written into
lines of code. The code and the agreements contained therein exist on the
blockchain network.
6. Ethereum Consensus Protocol: The Ethereum network uses a proof-of-work
consensus protocol, which requires miners to solve complex mathematical
problems in order to validate transactions and add them to the blockchain. The
first miner to solve the problem is rewarded with Ether.
7. Ethereum Mining: Ethereum mining is the process of adding transactions to the
Ethereum blockchain by solving complex mathematical problems. Miners use
specialized hardware to process transactions and secure the network.
8. Ethereum dApps: dApps, or decentralized applications, are applications that
run on the Ethereum network and are powered by smart contracts. dApps can
be built on top of the Ethereum platform and are decentralized, meaning they
are not controlled by any single entity.
Q.4 What are the elements present in the Ethereum blockchain?
Chat GPT
The Ethereum blockchain is a decentralized, distributed ledger that stores the state of
all smart contracts and transactions on the Ethereum network. It is composed of
several elements, including:

- Blocks: Each block in the Ethereum blockchain contains a list of transactions


that have been processed by the network, as well as a reference to the previous
block (also known as the "parent" block). This creates a chain of blocks, hence
the name "blockchain."

- Nodes: Nodes are the computers that run the Ethereum software and maintain a
copy of the Ethereum blockchain. They validate and relay transactions and
blocks, and help to keep the Ethereum network secure.

- Miners: Miners are nodes that perform the work of validating and adding new
blocks to the Ethereum blockchain. They do this by solving complex
mathematical problems, a process known as "mining." When a miner
successfully adds a new block to the blockchain, they are rewarded with a
small amount of Ether (the native cryptocurrency of Ethereum).

- Smart contracts: Smart contracts are self-executing contracts with the terms of
the agreement between buyer and seller being directly written into lines of
code. They are stored and replicated on the Ethereum blockchain and can be
used to facilitate, verify, and enforce the negotiation or performance of a
contract.

- Accounts: There are two types of accounts on the Ethereum blockchain:


external accounts (controlled by private keys) and contract accounts (controlled
by code). External accounts represent individuals or organizations on the
Ethereum network, and they can send transactions and interact with smart
contracts. Contract accounts, on the other hand, represent smart contracts
themselves and cannot initiate transactions, but can execute code and store
data.

- Ether: Ether (ETH) is the native cryptocurrency of the Ethereum blockchain. It


is used to pay for the computational resources needed to execute smart
contracts and to incentivize miners to validate and add new blocks to the
blockchain.
Q.5 Explain Ethereum state transition function.
1. Confirm the transaction validity by checking the syntax, signature validity, and
nonce.
2. The transaction fee is calculated, and the sending address is resolved using the
signature.
● The sender's account balance is checked and subtracted accordingly and
the nonce is incremented.
● An error is returned if the account balance is insufficient.
3. Provide enough ETH (the gas price) to cover the cost of the transaction.
● This is charged per byte and is incrementally proportional to the size of
the transaction.
● In this step, the actual transfer of value occurs.
● The flow is from the sender's account to the receiver's account.
● The account is created automatically if the destination account specified
in the transaction does not exist yet.
● If the destination account is a contract, then the contract code is
executed.
4. In cases of transaction failure due to insufficient account balance or gas, all
state changes are rolled back except for the fee payment, which is paid to the
miners.
5. Finally, the remainder (if any) of the fee is sent back to the sender as change
and the fee is paid to the miners accordingly.
6. At this point, the function returns the resulting state, which is also stored on the
blockchain.

😣Q.6 Explain State storage in the Ethereum blockchain.


Q.7 What is a Transaction receipt?
Diagram:
● Transaction receipts are used as a mechanism to store the state after a
transaction has been executed.
● In other words, these structures are used to record the outcome of the
transaction execution.
● It is produced after the execution of each transaction.
● All receipts are stored in an index-keyed trie.
● The hash (a 256-bit Keccak hash) of the root of this trie is placed in the block
header as the receipt's root.
● It is composed of four elements as follows
1. The post-transaction state: holds the state after the transaction has been
executed.
2. Gas used: This item represents the total amount of gas used in the block
that contains the transaction receipt.
3. Set of logs: This field shows the set of log entries created as a result of
the transaction execution.
4. The bloom filter: A bloom filter is created from the information
contained in the set of logs.
● A log entry is reduced to a hash of 256 bytes, which is then embedded in the
header of the block as the logs bloom.
● A log entry is composed of the logger's address, log topics, and log data.

Q.8 Explain Ethereum Virtual Machine operation.


1. The Ethereum Virtual Machine (EVM) is a simple stack-based machine that
runs byte code instructions to transform the system state from one state to
another.
2. The word size of the EVM is set to 256-bits.
3. The stack size is limited to 1024 elements.
4. The EVM is a Turing-complete machine, but is limited by the amount of gas
that is required to run any instructions.
5. EVM also supports exception handling. Various exceptions can occur such as
not having enough gas or providing invalid instructions, in which case the
machine would immediately halt and return the error to the execution agent.
6. The EVM is an isolated and sandboxed runtime environment ( a sandbox is an
isolated testing environment that enables users to run programs or open files
without affecting the application, system or platform on which they can run ).
7. The code that runs on the EVM does not have any access to any external
resources such as a network or filesystem.
8. This results in increased security, deterministic execution on Ethereum
blockchain.
9. There are three main types of storage available for the contracts and the EVM:
I. Memory:
● The first type is called memory or volatile memory.
● When a contract finishes its code execution, the memory is
cleared.
● Write operations to the memory can be of 8 or 256-bits, whereas
read operations are limited to 256-bit words .
● The memory available is unlimited, but it is constrained by gas
fee requirements.
II. Storage:
● A storage is a key-value store and is permanently persisted on the
blockchain.
● The key and values are each 256-bits wide.
● It is allocated to all accounts on the blockchain.
● As a security measure, storage is only accessible by its own
respective CA’s. It can be thought of as hard disk storage.
III. Stack:
● EVM is a stack-based machine and thus performs all
computations in a data storage method known as the stack.
● All in-memory values are also stored in the stack.
● It has a maximum depth of 1024 elements and supports the word
size of 256-bits.

⚡Q.9 What are the nine Native contracts of Ethereum?


https://ethereum.stackexchange.com/questions/15479/list-of-pre-compiled-contracts
1. Recovery of ECDSA signature: This is a process for determining the Ethereum
address associated with a given ECDSA signature.
2. Hash function SHA256: This is a cryptographic hash function that produces a
fixed-size hash value from an input.
3. Hash function RIPEMD160: This is a cryptographic hash function that produces a
fixed-size hash value from an input.
4. Identity: This refers to the unique characteristics that distinguish an individual or
entity.
5. Modular exponentiation (EIP 198): This is a mathematical operation that involves
raising a number to a power and taking the result modulo another number.
6. Addition on elliptic curve alt_bn128 (EIP 196): This is a mathematical operation that
involves adding two points on an elliptic curve using the alt_bn128 curve.
7. Scalar multiplication on elliptic curve alt_bn128 (EIP 196): This is a mathematical
operation that involves multiplying a point on an elliptic curve by a scalar value using
the alt_bn128 curve.
8. Checking a pairing equation on curve alt_bn128 (EIP 197): This is a mathematical
operation that involves verifying the validity of a pairing equation on the alt_bn128
curve.
9. BLAKE2b hash function (EIP 152): This is a cryptographic hash function that
produces a fixed-size hash value from an input.

Q.10 What are the elements of the Ethereum Block header?


There are various elements in a Ethereum block header:
1. Parent hash: This is the Keccak 256-bit hash of the parent (previous) block's
header.
2. Ommers hash: This is the Keccak 256-bit hash of the list of ommers (or uncles)
blocks included in the block.
3. The beneficiary: The beneficiary field contains the 160-bit address of the
recipient that will receive the mining reward once the block is successfully
mined.
4. State root: The state root field contains the Keccak 256-bit hash of the root
node of the state trie. It is calculated once all transactions have been processed
and finalized.
5. Transactions root: The transaction root is the Keccak 256-bit hash of the root
node of the transaction trie. The transaction trie represents the list of
transactions included in the block
6. Receipts root: The receipts root is the Keccak 256-bit hash of the root node of
the transaction receipt trie. This trie is composed of receipts of all transactions
included in the block. Transaction receipts are generated after each transaction
is processed and contain useful post-transaction information.
7. Logs bloom: The logs bloom is a bloom filter that is composed of the logger
address and log topics from the log entry of each transaction receipt of the
included transaction list in the block.
8. Difficulty: The difficulty level of the current block.
9. Number: The total number of all previous blocks; the genesis block is block
zero.
10. Gas limit: This field contains the value that represents the limit set on the gas
consumption per block.
11. Gas used: This field contains the total gas consumed by the transactions
included in the block.
12. Timestamp: The timestamp is the time of block initialization.
13. Extra data: The extra data field can be used to store arbitrary data related to the
block.
14. Mixhash: The mixhash field contains a 256-bit hash that, once combined with
the nonce, is used to prove that adequate computational effort (Proof of Work,
or PoW) has been spent in order to create this block.
15. Nonce: Nonce is a 64-bit hash (a number) that is used to prove, in combination
with the mixhash field, that adequate computational effort (PoW) has been
spent in order to create this block.

Same thing as above but simpler


● Parent hash: This is the hash of the previous block in the blockchain.

● Uncle hash: This is the hash of one of the "uncles" of the block, which are
blocks that were mined but not included in the main blockchain.

● Coinbase: This is the Ethereum address of the miner who mined the block.

● Root: This is the root of the state tree, which is a data structure that represents
the state of the Ethereum network at a given point in time.

● Difficulty: This is the difficulty level of the block, which determines how hard
it was to mine the block.

● Number: This is the number of the block in the blockchain.

● Gas limit: This is the maximum amount of gas that can be consumed by the
transactions in the block.
● Gas used: This is the actual amount of gas consumed by the transactions in the
block.

● Timestamp: This is the time at which the block was mined.

● Extra data: This is a field that can be used to include additional data in the
block header.

Q.11 Explain Ethereum block validation mechanism.


An Ethereum block is considered valid if it passes the following checks:
1. If it is consistent with uncles and transactions. This means that all ommers
satisfy the property that they are indeed uncles and also if the PoW for uncles is
valid.
2. If the previous block (parent) exists and is valid.
3. If the timestamp of the block is valid. This means that the current block's
timestamp must be higher than the parent block's timestamp.
4. If any of these checks fails, the block will be rejected. A list of errors for which
the block can be rejected is presented here:
● The timestamp is older than the parent.
● There are too many uncles.
● There is a duplicate uncle.
● The uncle is an ancestor.
● The uncle's parent is not an ancestor.
● There is non-positive difficulty.
● There is an invalid mix digest.
● There is an invalid PoW.
OR
The Ethereum block validation mechanism is a process for ensuring the integrity and
security of the Ethereum blockchain. It involves verifying that a new block being
added to the blockchain is valid and conforms to the rules of the Ethereum network.

The block validation process involves several steps, including:


● Checking the parent hash: The parent hash field in the block header is checked
to ensure that it matches the hash of the previous block in the blockchain.
● Validating the proof of work: The proof of work field in the block header is
checked to ensure that it meets the required difficulty level and that the block
was mined correctly.
● Checking the transaction root: The transaction root field in the block header is
checked to ensure that it matches the root of the Merkle tree of the transactions
in the block.
● Validating the transactions: Each transaction in the block is checked to ensure
that it is properly signed and that it follows the rules of the Ethereum network.
● Updating the state: If the block is found to be valid, the state of the Ethereum
blockchain is updated to reflect the changes caused by the transactions in the
block.

The block validation mechanism is an important part of the Ethereum blockchain, as it


ensures the integrity and security of the network. It helps to prevent fraudulent or
invalid blocks from being added to the blockchain and ensures that all nodes on the
network are in consensus about the state of the network.

Q.12 What are the client software and wallets that are available with Ethereum?
A wallet is a generic program that can store private keys and, based on the addresses
stored within it, it can compute the existing balance of ether associated with the
addresses by querying the blockchain.
The following is a non-exhaustive list of the client software and wallets that are
available with Ethereum:
1. Geth: This is the official Go implementation of the Ethereum client.
2. Eth: This is the C++ implementation of the Ethereum client.
3. Parity: This implementation is built using Rust and developed by Parity
4. technologies.
5. Trinity: Trinity is the implementation of the Ethereum protocol. It is written in
Python.
6. Light clients:
● Simple Payment Verification (SPV) clients download only a small
subset of the blockchain.
● This allows low resource devices, such as mobile phones, embedded
devices, or tablets, to be able to verify the transactions.
● A complete Ethereum blockchain and node are not required in this case,
and SPV clients can still validate the execution of transactions.
● SPV clients are also called light clients.

Q.13 How to query the blockchain using Geth?


There are different methods available to query with the blockchain.
There are three methods of interacting with the blockchain using
Geth:
1. Geth console:
● Geth can be started in the console using the following command:
“geth console”.
● This will also start the interactive JavaScript environment in which
JavaScript commands can be run to interact with the Ethereum
blockchain.
2. Geth attach:
● When a geth client is already running, the interactive JavaScript console
can be invoked by attaching to that instance.
● This is possible by running the geth attach command. “geth attach”.
● The Geth JavaScript console can be used to perform various functions.
● For example, an account can be created by attaching Geth.
● Once Geth is successfully attached with the running instance of the
Ethereum client, it will display the command prompt, >, which provides
an interactive command-line interface to interact with the Ethereum
client using JavaScript notations.
● You can create a new account using the command:
“personal.newAccount()”.
● We can then query the number of accounts on the blockchain using the
command: “eth.accounts”
● When an account in Ethereum is created, it stores the generated public
and private key pair on disk in a keystore.
● It is important to understand what this keystore contains and where it is
created.

Q.14 Explain MetaMask installation process.


https://www.geeksforgeeks.org/how-to-install-and-use-metamask-on-google-chrome/

Q.15 Explain Ethereum protocol Whisper, Swarm.


1. Whisper:
The whole concept of the Ethereum Whisper communication protocol revolves
around three objectives:
● providing users with a flexible system
● launching a secure communication channel on Ethereum
● most importantly, guaranteeing the users’ anonymity online.
If you are familiar enough with how blockchain works, you will know how
easy it is to track transactions in this system. You do not need to be one of the
counterparties involved in the operation to get information on the movement.

Ethereum Whisper goes in a whole different direction. Whisper conceals the


content of messages and the identities of senders and receivers from observers.
The system relies on a double layer of data encryption:
● Symmetric encryption allows transmitting one-to-many communications
using a single encryption and decryption key. The recipients of a
message can decrypt the messages sent to them.
● Asymmetric encryption employs public keys for encryption and private
keys for decryption. When communicating with another person, the
system uses this type of encryption.

Of course, because of the tight connection with Ethereum, all participants


already have public/private key pairs. This mechanism enables the use of the
completely encrypted architecture we described above.

2. Swarm:
Ethereum Swarm is basically a giant DHT. DHTs are used in many storage
solutions (like BitTorrent or IPFS) as a database where peers can find where the
data is stored. Swarm uses the DHT in a different way because it stores the data
itself in the DHT. Swarm calls this solution DISC which means Distributed
Immutable Store for Chunks. When you store anything in Swarm, it splits it
into 4K chunks. These chunks are addressable by the chunk hash and stored on
nodes that are the nearest to the chunk address. Every chunk is stored
redundantly on the 4 nearest nodes.

The network structure of Swarm is stable and highly optimized for the DHT.
Because of this optimized network structure, the content retrieval in Swarm is
really efficient. Swarm calls this Kademlia connectivity.
Unit III

Web3

Q.1 How Truffle can be used to test and deploy smart contracts?
Truffle is a popular development framework for Ethereum that allows you to write,
test, and deploy smart contracts. Here is a basic outline of how to use Truffle to test
and deploy your contracts:

- Install Truffle: Make sure you have Truffle installed on your machine. You can
install it using npm by running the following command: npm install -g truffle.

- Create a Truffle project: Create a new folder for your Truffle project and
navigate to it in your terminal. Then, run the command truffle init to create a
new Truffle project in the current directory. This will create a default Truffle
project structure with the following directories:

- contracts: This directory contains your Solidity smart contracts.


- migrations: This directory contains JavaScript scripts that are used to
deploy your contracts to the Ethereum network.
- test: This directory contains JavaScript test scripts for your contracts.
- Write your contract: Use Solidity to write your smart contract and save it in the
contracts directory.

- Compile your contract: Run the command truffle compile to compile your
contract. This will generate a JSON file for your contract in the build/contracts
directory.

- Write tests: Write test scripts for your contract in the test directory using
JavaScript and the Truffle testing library.

- Run your tests: Run the command truffle test to run your tests and ensure that
your contract is working as expected.

- Migrate your contract: Create a migration script in the migrations directory to


deploy your contract to the Ethereum network. Then, run the command truffle
migrate to deploy your contract.
https://trufflesuite.com/docs/truffle/how-to/create-a-project/
https://trufflesuite.com/docs/truffle/how-to/compile-contracts/
https://trufflesuite.com/docs/truffle/how-to/debug-test/write-tests-in-javascript/

Q.2 Explain Deployment on decentralized storage using IPFS.


Decentralized P2P storage is ideal for storing and distributing large static assets such
as images, videos, and the resources of the application’s frontend web interface
(HTML, CSS, JavaScript, etc.). We’ll look at a few of the options next.

The Inter-Planetary File System (IPFS) is a decentralized content-addressable storage


system that distributes stored objects among peers in a P2P network. “Content
addressable” means that each piece of content (file) is hashed and the hash is used to
identify that file. You can then retrieve any file from any IPFS node by requesting it
by its hash.

IPFS aims to replace HTTP as the protocol of choice for delivery of web applications.
Instead of storing a web application on a single server, the files are stored on IPFS and
can be retrieved from any IPFS node.

To deploy your application on IPFS, you will need to follow these steps:

- Install the IPFS client on your machine. This will allow you to interact with the
IPFS network and perform various actions such as adding and fetching files.

- Add your application's files to the IPFS network. You can do this using the ipfs
add command, which will add the files to your local IPFS node and return a
content hash for each file.

- Publish the content hashes for your application's files on a decentralized


registry such as ENS (Ethereum Name Service). This will allow users to access
your application using a human-readable name, rather than a long content hash.

- Update your application to use the content hashes or ENS names to retrieve the
necessary files from the IPFS network. This can typically be done using an
IPFS library or plugin that provides a simple API for interacting with the IPFS
network.
Serenity

Q.3 What is a Scalability Trilemma?


The scalability trilemma, also known as the "blockchain trilemma," refers to the
trade-offs that blockchain systems face when trying to improve scalability, security,
and decentralization. These three factors are often considered conflicting goals, as it is
difficult to improve one without sacrificing the others.

Serenity is a proposed upgrade to the Ethereum blockchain that aims to address the
scalability trilemma by improving the scalability and security of the Ethereum
network while maintaining decentralization. It does this through the use of various
technologies such as sharding and proof of stake. However, it is important to note that
the scalability trilemma is a fundamental challenge that all blockchain systems face,
and it remains to be seen how effectively Serenity will be able to address it.

Proof of Stake & The Casper V2 Protocol


The Ethereum blockchain is planning to transition from a proof of work (PoW)
consensus algorithm to a proof of stake (PoS) consensus algorithm as part of the
Serenity release. PoW systems, which use mining to validate transactions and generate
new blocks, have been criticized for their high hardware and electricity costs and the
risk of centralization. PoS systems allow anyone holding coins in the system to
participate in the process of appending and agreeing on new blocks, with the influence
of each participant proportional to the number of coins they hold. The initial plan for
this transition was the Casper FFG protocol, a hybrid PoW and PoS blockchain that
required a minimum deposit of 1500 Ether to become a validator. However, this plan
has been abandoned in favor of Casper V2, a pure PoS system called the beacon chain
that will require a minimum deposit of 32 Ether to become a validator and serve as the
base layer for sharding.

Sharding
Sharding is a technique that aims to increase the Ethereum blockchain's total
throughput rate by dividing the validation responsibility among many nodes. This is
done by storing different parts of the state in different nodes and directing transactions
to different nodes depending on which shards they affect, allowing for parallel
processing. The goal of sharding is to allow Ethereum to scale to practical levels for
applications while maintaining decentralization and security. It is similar to sharding
techniques found in traditional databases.

Ethereum Flavored WebAssembly (eWasm)


eWasm is a planned update to the Ethereum blockchain that aims to improve
flexibility, performance, and language support for smart contract development. It will
do this by replacing the current Ethereum Virtual Machine (EVM) with a new
execution engine based on WebAssembly, a binary format optimized for virtual
machines. This new runtime environment, which will be portable and able to run code
almost as fast as native machine code, will s upport smart contract development in a
variety of languages that can be compiled into WebAssembly, including Go, Rust, C,
and C++. The goal of eWasm is to make Ethereum code execution faster and more
efficient.

https://medium.com/hackernoon/tackling-ethereums-blockchain-trilemma-via-serenity
-ethereum-2-0-1fb423a6b184

Q.4 What are the goals behind the development of Serenity?


1. Ethereum took the blockchain technology to the next level by fostering
hundreds of new blockchain networks and their native tokens.
2. Ethereum initiated the concept of smart contracts and decentralized
applications (DApps) to the broader community. Today it hosts many
blockchain projects including those booming under the Decentralized Finance
(DeFi) umbrella.
3. Now, the platform co-founded by Vitalik Buterin is facing a significant
transformation to stay on top of the league. That's when Ethereum is starting to
transition to Ethereum 2.0 gradually, and the new platform will be significantly
better and more scalable.
4. Ethereum 2.0 is an essential upgrade implemented to address the limitations of
the Proof-of-Work (PoW) consensus. The Proof-of-Stake (PoS) algorithm
supposedly uplifts the transaction speed and the accessibility of individual
validators to participate and maintain the network's truth.
5. Ethereum 2.0, also known as Serenity, is allegedly an improved version of
Ethereum. The sharding will replace the PoW with a PoS algorithm, thus
eliminating the scalability and accessibility issues.
6. To achieve this, Serenity will implement a unique architecture called sharding,
which refers to a network of parallel channels working together.
7. Each shard will have its own set of account balances and smart contracts. The
method to achieve maximum decentralization will be implemented in the final
phase of the upgrade.
8. There will be 64 new chains created on the network during the sharding to
spread the volume, meaning to break the data stored on Ethereum nodes into
smaller groups.
9. Eventually, uplifting the transactions per second to process each small group of
data. The highlight of this sharding is primarily its decentralized nature that
allows more participants to secure the network.
10. When there are more nodes on a network, it usually translates to a safer
Ethereum blockchain network.

Q.5 What are the four phases in the development of Ethereum 2.0?
1. Phase 0:
● The main work included in Phase 0 is around the management of
validators and the staking mechanism.
● In addition, this phase also includes block proposer selection, consensus
mechanism rules, and a reward/penalty mechanism.
● This stage involves the creation of a core system chain called the beacon
chain, which can be considered the backbone of the entire Ethereum 2.0
chain system.
● After Phase 0 is complete, there will be two chains in existence: the
original Ethereum 1.0 chain and a new chain called the beacon
chain.These chains will operate in parallel.
● The Phase 0 specification and development can be further divided into
multiple categories, the first of which is the beacon chain

2. Phase 1:
● Phase 1 includes the development of shard chains and blocks.
● Phase 1.5 also known as "the merge" is where ethereum mainnet will
transit into Ethereum 2 most likely by becoming a shard chain of
Ethereum 2.0.
● Shard chains are the main scalability feature that will initially consist of
64 chains and will grow over time as required.
● The main design goals in this phase revolve around creation, validation,
and consensus of the data of shard chains.
● The state of each shard chain will be written periodically to the beacon
chain.
● This is called a crosslink, which is a set of signatures from a set of
validators (the committee) that has attested to a block in a shard chain.
● This crosslink is included in the beacon chain representing the
attestation of blocks of shard chains.
● The idea behind this mechanism is that when a block in the beacon
chain is finalized, the corresponding block in the shard chain is also
considered final.
3. Phase 2:
● Phase 2 will have the ability to run smart contracts and transactions on
shard chains.
● In addition, constructs such as accounts will also be available with this
phase.
● Each shard chain in Phase 2 will have its own ewasm EVM, which will
allow for faster running of smart contracts.
● There is also a concept of the execution environment, which allows
shards in Phase 2 to build custom environments for specific use cases.
● This gives tremendous flexibility to developers, as it allows them to
build fully customized execution environments.
● It is quite early to say how exactly these execution environments will be
designed because of the rapidly evolving research in this space.

4. Phase 3:
● Phase 3 is to be a continuous improvement and maintenance stage,
where a complete Ethereum 2.0 chain will be running and evolving into
a more mature and feature-rich blockchain.

Hyperledger

Q.1 What are the Projects under Hyperledger?


There are four categories of projects under Hyperledger.
The categories are:
1. Distributed ledgers:
Currently, there are six distributed ledger projects under the Hyperledger
umbrella:
a. Fabric:
Hyperledger Fabric is a blockchain project that was proposed by IBM and
Digital Asset Holdings (DAH).
It is an enterprise-grade permissioned distributed ledger framework, which
provides a framework for the development of blockchain solutions and
applications.

b. Sawtooth:
Hyperledger Sawtooth is a blockchain project proposed by Intel in April
2016. It was donated to the Linux foundation in 2016.
Sawtooth introduced some novel innovations focusing on the decoupling of
ledgers from transactions, flexible usage across multiple business areas
using transaction families, and pluggable consensus.

c. Iroha:
Iroha was contributed by Soramitsu, Hitachi, NTT Data, and Colu in
September 2016.
Iroha aims to build a library of reusable components that users can choose
to run on their own Hyperledger-based distributed ledgers.

d. Indy:
Indy is a distributed ledger developed for building decentralized identities.
It provides tools, utility libraries, and modules, which can be used to build
blockchain-based digital identities.

e. Besu:
Besu is a Java-based Ethereum client.
It is the first project under Hyperledger that can operate on a public
Ethereum network.

f. Burrow:
Hyperledger Burrow was contributed by Monax.
Burrow introduces a modular blockchain platform and an Ethereum Virtual
Machine (EVM)-based smart contract execution environment.

2. Libraries:
Currently, there are four library projects under the Hyperledger umbrella:
a. Aries:
Aries is not a blockchain; in fact, it is an infrastructure for
blockchain-rooted, peer-to-peer (P2P) interactions.
The aim of this project is to provide code for P2P interactions, secrets
management, verifiable information exchange, interoperability, and secure
messaging for decentralized systems.
The eventual goal of this project is to provide a dynamic set of capabilities to
store and exchange data related to blockchain-based identity.

b. Transact:
Transact provides a shared library that handles smart contract execution.
This library makes the development of distributed ledger software easier by
allowing the handling of scheduling, transaction dispatch, and state
management via a shared software library.
It provides an approach to implement new smart contract development
languages named smart contract engines.
Two main examples of such engines are Seth (for EVM smart contracts) and
Sabre (for web assembly Wasm-based smart contracts).

c. Quilt:
This utility implements the Interledger protocol, which facilitates
interoperability across different distributed and non-distributed ledger
networks.

d. Ursa:
Ursa is a shared cryptography library that can be used by any project,
Hyperledger or otherwise, to provide cryptography functionality.
There are two sub-libraries available in Ursa: LibUrsa and LibZmix.
LibUrsa is designed for cryptographic primitives such as digital signatures,
standard encryptions schemes, and key exchange schemes.
LibZmix supports signature Proofs of Knowledge (PoK), bullet proofs, range
proofs, and set memberships.

3. Tools:
a. Avalon:
Avalon provides a trusted computer framework that enables privacy and
allows off-chain processing of compute-intensive operations in a trusted and
secure manner.
It provides a guarantee that a computation was performed correctly and
privately.

b. Cello:
The aim behind Cello is to allow the easy deployment of blockchains.
This will provide an ability to allow as a service deployments of a
blockchain service.

c. Caliper:
It can be used to measure the performance of any blockchain.
There are different performance indicators supported in the framework.
These include success rate, transaction read rate, throughput, latency, and
hardware resource consumption, such as CPU, memory, and I/O.
Ethereum, Fabric, Sawtooth, Burrow, and Iroha are currently the supported
blockchains in Caliper.

d. Explorer:
This project aims to build a blockchain explorer for Hyperledger Fabric that
can be used to view and query the transactions, blocks, and associated data
from the blockchain.
It also provides network information and the ability to interact with chain
code.

4. Domain-specific:
a. Grid:
Grid is a Hyperledger project that provides a standard reference
implementation of supply chain-related data types, data models, and relevant
business logic encompassing smart contracts.

b. Labs:
Hyperledger labs provide a quick and easy way to start a project under
Hyperledger without going through the official formal process of incubation
and activation.
This allows the development of research projects, hackathons, and demo
projects.

Q.2 Explain Hyperledger reference architecture.


● In the preceding diagram, starting from the left, we see that we have five
top-level components that provide various services.
● The first is identity, which provides authorization, identification, and
authentication services under membership services.
● Then, we have the policy component, which provides policy services.
● After this, blockchain and transactions, which consist of the Consensus
Manager, Distributed Ledger, the network P2P Protocol, and Ledger Storage
services.
● The consensus manager ensures that the ledger is updateable only through
consensus among the participants of the blockchain network.
● Finally, we have the smart contracts layer, which provides chaincode services
in Hyperledger and makes use of Secure Container technology to host smart
contracts.
● The various elements within the hyperledger architecture are:
a. Consensus: These services are responsible for facilitating the agreement
process between the participants on the blockchain network.
Consensus is required to make sure that the order and state of
transactions are validated and agreed upon in the blockchain network.

b. Smart contracts: These services are responsible for implementing


business logic as per the requirements of the users.
Transactions are processed based on the logic defined in the smart
contracts that reside on the blockchain.

c. Communication: This component is responsible for message


transmission and exchange between the nodes on the blockchain
network.

d. Security and crypto: These services are responsible for providing the
capability to allow various cryptographic algorithms or modules to
provide privacy, confidentiality, and non-repudiation services.

e. Data store: This component provides an ability to use different data


stores for storing the state of the ledger.

f. Policy services: This set of services provides the ability to manage the
different policies required for the blockchain network.

g. APIs and SDKs: This component allows clients and applications to


interact with the blockchain.
h. An SDK is used to provide mechanisms to deploy and execute
chaincode, query blocks, and monitor events on the blockchain.

Q.3 What are the various elements of Hyperledger?


● The various elements within the hyperledger architecture are:
a. Consensus: These services are responsible for facilitating the agreement
process between the participants on the blockchain network.
Consensus is required to make sure that the order and state of transactions
are validated and agreed upon in the blockchain network.

b. Smart contracts: These services are responsible for implementing business


logic as per the requirements of the users.
Transactions are processed based on the logic defined in the smart
contracts that reside on the blockchain.

c. Communication: This component is responsible for message transmission


and exchange between the nodes on the blockchain network.

d. Security and crypto: These services are responsible for providing the
capability to allow various cryptographic algorithms or modules to provide
privacy, confidentiality, and non-repudiation services.

e. Data store: This component provides an ability to use different data stores
for storing the state of the ledger.

f. Policy services: This set of services provides the ability to manage the
different policies required for the blockchain network.

g. APIs and SDKs: This component allows clients and applications to interact
with the blockchain.

h. An SDK is used to provide mechanisms to deploy and execute chaincode,


query blocks, and monitor events on the blockchain.

Q.4 Explain Hyperledger Fabric.


1. Hyperledger Fabric, or Fabric for short, is the contribution made initially by
IBM and Digital Assets to the Hyperledger project.
2. Hyperledger Fabric platform is an open source blockchain framework hosted
by The Linux Foundation. It has an active and growing community of
developers.
3. This contribution aims to enable a modular, open, and flexible approach toward
building blockchain networks.
4. Various functions in the fabric are pluggable, and it also allows the use of any
language to develop smart contracts.
5. This functionality is possible because it is based on container technology
(Docker), which can host any language.
6. Transactions in Fabric are private, confidential, and anonymous for general
users, but they can still be traced back and linked to the users by authorized
auditors.
7. As a permissioned network, all participants are required to be registered with
the membership services to access the blockchain network.
8. This benefit is particularly useful in industries including healthcare, supply
chain, banking, and insurance where data cannot be exposed to unknown
entities. For example, an insurance company on a Hyperledger Fabric
blockchain network can share customer’s claim data with permissioned parties
to maintain customer privacy.
9. This ledger also provided auditability functionality to meet the regulatory and
compliance needs required by the user.
10. Hyperledger Fabric is built to support enterprise-grade use cases, and can
support quick transaction throughput from its consensus mechanism. Because
Fabric is a permissioned blockchain framework, it does not need to solve for
Byzantine Fault Tolerance which can cause slower performance when
validating transactions on the network.

Q.5 Explain consensus mechanism in Hyperledger Fabric.


1. A consensus service is responsible for providing the interface to the consensus
mechanism.
2. Consensus in Hyperledger Fabric is implemented as a peer called orderer,
which is responsible for ordering the transactions in sequence into a block.
3. An orderer does not hold smart contracts or ledgers.
4. Consensus is pluggable and currently, there are two basic types of ordering
services available in Hyperledger Fabric:
a. SOLO: This is a basic ordering service intended to be used for development
and testing purposes.
b. Kafka: This is an implementation of Apache Kafka, which provides an
ordering service.
Kafka only provides crash fault-tolerance but does not provide Byzantine
fault-tolerance.

5. Raft: Raft is a crash fault-tolerant and leader-follower-based protocol for


achieving distributed consensus.
6. PBFT: PBFT is a state machine replication-based BFT protocol that can be
used in Hyperledger Fabric to achieve consensus.

Q.6 Explain The transaction lifecycle in Hyperledger Fabric.


Hyperledger fabric is an enterprise-level permission blockchain network. It is made up
of various unique organizations or members that interact with each other to serve a
specific purpose.
For example, these organizations can be a bank, financial institution, or a supply chain
network. Each organization is identified and they have a fabric certificate authority.
These organizations are called members.
Each member of the fabric can set up one or more authorized peers to participate in
the network using the fabric certificate authority.
All of these peers must be authorized properly.
There is a client-side application connected to the network written with the software
development kit (SDK) of any particular programming language.

For each and every transaction in the fabric, the following steps are followed-
1. Creation of the proposal:
Imagine a deal between a smartphone manufacturer company and a smartphone
dealership.
The transaction begins when a member organization proposes or invokes a
transaction request with the help of the client application or portal.
Then the client application sends the proposal to peers in each organization for
endorsement.
2. Endorsement of the transaction:
After the proposal reaches the endorser peers (peers in each organization for
endorsement of a proposal) the peer checks the fabric certificate authority of
the requesting member and other details that are needed to authenticate the
transaction.
Then it executes the chain code (a piece of code that is written in one of the
supported languages such as Go or Java) and returns a response.
This response indicates the approval or rejection of the following transaction.
The response is carried out to the client.
3. Submission to ordering service: After receiving the endorsement output, the
approved transactions are sent to the ordering service by the client-side
application. The peer responsible for the ordering service includes the
transaction into a specific block and sends it to the peer nodes of different
members of the network.
4. Updating the ledger: After receiving this block the peer nodes of such
organizations update their local ledger with this block. Hence the new
transactions are now committed.

Q.7 Explain New chaincode lifecycle management in Hyperledger .


1. Chaincode is a program, written in Go, Node.js, or Java that implements a
prescribed interface. Chaincode runs in a secured Docker container isolated
from the endorsing peer process. Chaincode initializes and manages ledger
state through transactions submitted by applications.
2. A chaincode typically handles business logic agreed to by members of the
network, so it may be considered as a “smart contract”. Ledger updates created
by a chaincode are scoped exclusively to that chaincode and can’t be accessed
directly by another chaincode. However, within the same network, given the
appropriate permission a chaincode may invoke another chaincode to access its
state.
3. The Fabric chaincode lifecycle is a process that allows multiple organizations
to agree on how a chaincode will be operated before it can be used on a
channel. A network operator would use the Fabric lifecycle to perform the
following tasks:
a. Install and define a chaincode:
Fabric chaincode lifecycle requires that organizations agree to the
parameters that define a chaincode, such as name, version, and the
chaincode endorsement policy. Channel members come to agreement
using the following four steps. Not every organization on a channel
needs to complete each step.

1. Package the chaincode: This step can be completed by one


organization or by each organization.
2. Install the chaincode on your peers: Every organization that will
use the chaincode to endorse a transaction or query the ledger
needs to complete this step.
3. Approve a chaincode definition for your organization: Every
organization that will use the chaincode needs to complete this
step. The chaincode definition needs to be approved by a
sufficient number of organizations to satisfy the channel’s Life
cycle Endorsement policy (a majority, by default) before the
chaincode can be started on the channel.
4. Commit the chaincode definition to the channel: The commit
transaction needs to be submitted by one organization once the
required number of organizations on the channel have approved.
The submitter first collects endorsements from enough peers of
the organizations that have approved, and then submits the
transaction to commit the chaincode definition.

b. Upgrade a chaincode:
You can upgrade a chaincode using the same Fabric lifecycle process as
you used to install and start the chaincode. You can upgrade the
chaincode binaries, or only update the chaincode policies.
Follow these steps to upgrade a chaincode:
1. Repackage the chaincode
2. Install the new chaincode package on your peers
3. Approve a new chaincode definition
4. Commit the definition to the channel

c. Deployment Scenarios:
1. Joining a channel:
A new organization can join a channel with a chaincode already
defined, and start using the chaincode after installing the
chaincode package and approving the chaincode definition that
has already been committed to the channel.
2. Updating an endorsement policy:
You can use the chaincode definition to update an endorsement
policy without having to repackage or re-install the chaincode.
Channel members can approve a chaincode definition with a new
endorsement policy and commit it to the channel.

3. Approving a definition without installing the chaincode:


You can approve a chaincode definition without installing the
chaincode package. This allows you to endorse a chaincode
definition before it is committed to the channel, even if you do
not want to use the chaincode to endorse transactions or query the
ledger. You need to approve the same parameters as other
members of the channel, but not need to include the packageID as
part of the chaincode definition.

4. One organization disagrees on the chaincode definition:


An organization that does not approve a chaincode definition that
has been committed to the channel cannot use the chaincode.
Organizations that have either not approved a chaincode
definition, or approved a different chaincode definition will not
be able to execute the chaincode on their peers.

5. The channel does not agree on a chaincode definition:


If the organizations on a channel do not agree on a chaincode
definition, the definition cannot be committed to the channel.
None of the channel members will be able to use the chaincode.

6. Organizations install different chaincode packages:


Each organization can use a different packageID when they
approve a chaincode definition. This allows channel members to
install different chaincode binaries that use the same endorsement
policy and read and write to data in the same chaincode
namespace.

7. Creating multiple chaincodes using one package:


You can use one chaincode package to create multiple chaincode
instances on a channel by approving and committing multiple
chaincode definitions.
d. Migrate to the new Fabric lifecycle:

OR

The chaincode lifecycle management in Hyperledger Fabric is the process of


developing, deploying, and managing smart contracts (also known as chaincode) on
the Fabric platform. The new chaincode lifecycle management in Hyperledger Fabric
introduces several improvements and enhancements over the previous version,
including:

Improved resource management: The new chaincode lifecycle management includes


new features for managing resources, such as memory and CPU usage, which can help
to improve the scalability and performance of the Fabric network.

Enhanced security: The new chaincode lifecycle management includes improved


security features, such as better protection against replay attacks and the ability to
disable chaincode execution at the network level.

Simplified deployment and management: The new chaincode lifecycle management


includes improved tools and processes for deploying and managing chaincode, which
can help to reduce the complexity and overhead of developing and maintaining smart
contracts on the Fabric platform.

Improved interoperability: The new chaincode lifecycle management includes support


for multiple programming languages, which can help to improve interoperability
between different components of the Fabric network and make it easier to develop
chaincode in the language of choice.

Overall, the new chaincode lifecycle management in Hyperledger Fabric aims to


provide a more efficient and secure platform for developing and deploying smart
contracts on the Fabric network.

Q.8 Write a short note on Hyperledger Sawtooth.


1. Hyperledger Sawtooth is an open source project under the Hyperledger
umbrella, and works as an enterprise level blockchain system used for creating
and operating distributed ledger applications and networks particularly for use
by enterprises.
2. Sawtooth enables selective permissions – that is, one can easily deploy certain
select clusters of Sawtooth nodes with different permissions on the same
blockchain. The ledger stores the necessary details about the permissions,
nodes and identities.
3. The operating performance of the Sawtooth network is boosted by the
mechanism of parallel transaction execution, which has an upper hand over the
serial execution mechanism that often is a bottleneck when dealing with high
volumes of transactions on many popular cryptocurrency networks.
4. Sawtooth supports Proof of Elapsed Time (POET) consensus mechanism that
offers benefits of low resource utilization and low energy consumption, and is
commonly used on the permissioned blockchain networks to decide the mining
rights or the block winners on the network. (For more, see Proof of Elapsed
Time.)
5. Some real-world examples using Sawtooth-based applications include
Sawtooth Supply Chain, which helps an enterprise keep track of contextual and
logistics-related information of an asset represented on the blockchain,
Sawtooth Marketplace, which helps participants trade in specified quantities of
digital assets on the blockchain, and Sawtooth Private UTXO, which facilitates
digital asset creation and trading, including off-ledger and privately-held
transactions.

Tokenization

Q.1 What are the Advantages/ Disadvantages of tokenization?


Advantages of Blockchain Tokenization
Distributed System
Blockchain data is often stored in thousands of devices on distributed network nodes
hence, the system and the data are highly resistant to technical failures and malware.
Each node replicates the data and stores the copy of the database. In contrast,
conventional databases rely on a few servers and are vulnerable to failures and
cyber-attacks.

Trustless System
In the conventional payment system, sometimes transactions do not only involve two
parties but also intermediaries such as banks or payment providers. When we
implement blockchain tokenization, the distributed network nodes verify the
transactions through a process known as mining and so blockchain for a reason is
often referred to as “trustless system”. This eliminates the risk of trusting an
organization and reduces the overall cost of transactions by cutting out third parties.
Stability
Confirmed blocks of blockchain are resistant to the modification of data, which means
there are no chances of deletion and changes in data after it has been registered in the
blockchain. This makes it feasible to store the financial data in the blockchain as it
provides greater stability and security.

Disadvantages
Data Modification
One of the downsides of implementing Blockchain is data modification; once data has
been added to Blockchain, it is very difficult to modify it and this stability is
disadvantageous. But changing blockchain data or code is demanding and it becomes
difficult when needed, where one chain has to be abandoned and a new one is taken
up.

Storage
Blockchain logs can grow very large over time. The Bitcoin blockchain requires
around 200 GB of storage and the growth in the blockchain size appears to be
increasing, resulting in the network risks losing nodes if the log becomes too large for
the storage and downloads.

Private Keys
Blockchain uses asymmetric cryptography to give ownership to its users over their
cryptocurrency unit. Each Blockchain address has a respective private key. While the
Blockchain address is shareable, the private key should be kept confidential. To access
the funds, each user needs a private key. In cases, where an individual loses the private
key, the money is lost and there is no way out!

Prone to Attacks
The Proof of Work algorithm efficiently protects the Bitcoin blockchain. But there
have been fewer potential attacks that are performed against the blockchain and 51
percent among them are most discussed. This attacks can be successful when only one
entity handles more than 50 percent of network hashing power, which allows them to
disrupt the whole network.

Q.2 What are the various Types of tokens used on a blockchain?


https://www.softwaretestinghelp.com/types-of-cryptocurrency/
- Cryptocurrency: These are digital assets that use cryptography for secure
financial transactions. Examples include Bitcoin, Ethereum, and Litecoin.
- Utility tokens: These are tokens that give holders access to a specific product or
service.
Utility tokens are thought of as coupons or vouchers but essentially are digital
units representing a value on the blockchain. In other words, the token provides
certain access to a product or service run or operated by the token issuer. A
person can gain access by buying the token and can redeem it for a defined
access value to the product or service.
For example, a token might be used to access a decentralized application
(dApp) on a blockchain.

- Security tokens: These are tokens that represent ownership of an asset, such as
stocks, bonds, or real estate. They are subject to federal securities regulations.
These are securitized cryptocurrencies that derive value from an external asset
that can be traded under a financial regulation as security.

- Asset-backed tokens: These are tokens that represent ownership of a physical


asset, such as gold or oil or real-world real estate, art, carbon credits, or
commodities as underlying value.

- Non-fungible tokens (NFTs): These are unique tokens that represent ownership
of a one-of-a-kind asset, such as a piece of art or a collectible. These is unqiue
to the holder and the creator of the collectible. One can launch NFTs using
ERC721 and ERC1155 standards on Ethereum.

- Stablecoins: These are tokens that are pegged to a stable asset, such as a fiat
currency or commodity, in order to minimize price volatility. As the name
suggests, these are tokens of a stable value in nature in that their value is
somewhat predictable in the sense that it remains the same almost all the time.
Stable tokens or stablecoins as they are mainly called, are backed by a stable or
fairly value-stable asset like fiat. So we have dollar and Euro-stabilized or
backed stable coins, gold and other precious metals, oil, and
commodity-backed tokens.

- Governance tokens: These are tokens that give holders voting rights in
decision-making processes within a blockchain network or organization.

- Reward tokens: These are tokens that are given to participants in a blockchain
network as a reward for contributing resources, such as computing power or
storage, to the network.
Q.3 Explain Process of tokenization.
This is as per Mam’s PPT
• Almost any asset can be tokenized and presented on a blockchain,
such as commodities, bonds, stocks, real estate, precious metals,
loans, and even intellectual property.
• Physical goods that are traditionally illiquid in nature, such as
collectibles, intellectual property, and art, can also be tokenized and
turned into liquid tradeable assets.
• The first step is to onboard an investor who is interested in
tokenizing their asset.
• The asset that is presented for tokenization is scrutinized and
audited, and ownership is confirmed.
• The process of tokenized security starts, which leads to the security
token offering(STO).
• The physical asset is placed with a custodian (in the real world) for
safekeeping.
• The derivative token, representing the asset, is created by the
organization offering the token and issued to investors through a
blockchain.
• Traders start to buy and sell these tokens using trading exchanges in a
secondary market and these trades are settled (the buyer makes a
payment and receives the goods) on a

Q.4 Explain Token standards.

Here are some of the most popular token standards on Ethereum:

● ERC-20 - A standard interface for fungible (interchangeable) tokens, like


voting tokens, staking tokens or virtual currencies.
● ERC-721 - A standard interface for non-fungible tokens, like a deed for
artwork or a song.
● ERC-777 - ERC-777 allows people to build extra functionality on top of tokens
such as a mixer contract for improved transaction privacy or an emergency
recovery function to bail you out if you lose your private keys.
● ERC-1155 - ERC-1155 allows for more efficient trades and bundling of
transactions – thus saving costs. This token standard allows for creating both
utility tokens (such as $BNB or $BAT) and Non-Fungible Tokens like
CryptoPunks.
● ERC-4626 - A tokenized vault standard designed to optimize and unify the
technical parameters of yield-bearing vaults

https://ethereum.org/en/developers/docs/standards/tokens/

Q.5 Explain Trade lifecycle.


Same has Process I assume

Q.6 Differentiate between fungible and non - fungible tokens.


1. Interchangeability: Fungible tokens are interchangeable and identical in value,
while non-fungible tokens are unique and cannot be replaced by another
identical token.
2. Value: Fungible tokens have a standard value that is the same for all units of
the same token, while non-fungible tokens have a unique value that may be
different from other tokens.
3. Ownership: Fungible tokens do not represent ownership or proof of
authenticity for a specific asset, while non-fungible tokens do.
4. Trading: Fungible tokens can be traded on an equal basis, while non-fungible
tokens cannot be traded on an equal basis.
5. Examples: Examples of fungible tokens include cryptocurrencies like Bitcoin
and Ethereum, as well as commodities like gold and oil. Examples of
non-fungible tokens include collectibles, artwork, and in-game items.
6. Use cases: Fungible tokens are often used for financial transactions and as a
store of value, while non-fungible tokens are used to represent ownership or
authenticity of unique assets.
7. Transferability: Fungible tokens can be transferred easily and without requiring
any additional information, while non-fungible tokens may require additional
information or verification to be transferred.
8. Rarity: Fungible tokens are not rare and can be easily replaced, while
non-fungible tokens may be rare and have a unique value because of their
rarity.
9. Immutability: Fungible tokens do not have a fixed or unchanging state, while
non-fungible tokens may have a fixed or unchanging state.
10. Protocols: Fungible tokens are often built on blockchain protocols that support
the transfer of value, while non-fungible tokens are often built on protocols that
support the unique identification and ownership of assets.
Unit IV

Solidity Programming

Q.1 What are the A Solidity file construct?


A Solidity file is a source code file written in the Solidity programming language.
Solidity is a high-level, object-oriented programming language that is used to develop
smart contracts for the Ethereum blockchain.
A Solidity file typically consists of the following constructs:
1. Pragma directive: This specifies the version of the Solidity compiler that the
code is written for.
2. Import statements: These allow the Solidity file to access code from other
Solidity files or external libraries.
3. Contract definition: This defines the structure and behavior of a smart contract.
A Solidity file can contain multiple contract definitions.
4. State variables: These are variables that are stored on the blockchain and can be
accessed by the smart contract.
5. Functions: These are blocks of code that perform a specific task and can be
called by external clients or other functions within the contract.
6. Events: These allow the smart contract to trigger notifications when certain
conditions are met.
7. Modifiers: These are blocks of code that can be used to modify the behavior of
functions.
8. Structs: These are custom data types that allow the contract to store complex
data structures.
9. Enums: These are custom data types that allow the contract to define a set of
named constants.
10. Libraries: These are reusable blocks of code that can be called by multiple
contracts.
11. Interfaces: These define the functions that a contract must implement in order
to be compatible with other contracts or external clients.

Q.2 Explain the Structure of a contract in solidity programming.


Types
In Solidity, the contract type is a struct that organizes a set of related functions around
a single purpose.

Address types are Ethereum addresses that equate to 20 bytes, and are represented in
hexadecimal form beginning with the prefix 0x.
Most other types will be familiar to you as a developer - including booleans, integers,
fixed-point numbers, byte arrays, and literals.

Data Storage
In Solidity, reference data values can be stored as storage, memory or calldata
depending on the role of the data stored. In particular:

storage : keeps the data permanently on the blockchain, and is extremely expensive.
memory: values are stored only for the lifetime of the smart contract's execution, and
are inexpensive to use (costing only small amounts of gas).
calldata: is a special data location that contains the function arguments, and is only
available for external function call parameters.

Function Modifiers
Functions exist to get/set information based on calls initiated by external transactions.
In particular, a smart contract can never run unless initiated by an external transaction
- they don't execute silently in the background.

Access modifiers include:

public: Can be accessed by all functions or callers


external: Can be accessed only by external callers, not internal functions
internal: Can be accessed only by this contract, or contracts deriving from it
private: Can be accessed only from this contract itself
Other modifiers include:

view: This guarantees that the function will not modify the state of the contract's data
(or data in storage).
pure: This guarantees that the function with neither read nor modify the state of the
contract's data.
payable: Functions and addresses declared payable can receive ether into their
contracts.

Special Functions and Variables


There are a number of global variables and functions that will be helpful to remember
you have access to! Some special variables are:

block.number (uint256): The number of the most recent block.


block.timestamp (uint256): The UNIX timestamp of the most recent block.
block.gaslimit (uint256): The gas limit of the current block.
msg.sender (address payable): The sender of the transaction triggering the contract.
msg.value (uint256): The number of wei transferred with the message.
Special functions include:
receive(): Contracts may only have one of these functions declared. It serves as the
default destination when a contract is sent Ether. It cannot have arguments, return
anything, and must be external and payable.
fallback(): Contracts may only have one of these functions declared. It serves as the
fallback if a call to the contract does not match any function, or if no data was
supplied and the receive() function was not declared. It cannot have arguments, return
anything, and must be external.
Events
Solidity events are roughly equivalent to logging in other programming paradigms.
They're emitted when a contract is executed, stored permanently on the blockchain,
but aren't accessible to be modified / read by smart contracts.

You can declare and emit an event like this:

event TestEvent (
uint256 date,
string value
);

emit TestEvent(block.timestamp,’My first event!”);

Events can be accessed in a variety of different ways:

Events are stored in the receipts of transactions and can be accessed there.
You can subscribe to an event with myContract.events.TestEvent([options][,
callback])
You can request past events using a request like myContract.getPastEvents(event[,
options][, callback]).

Q.3 What is a State variable?


Values of these variables are permanently stored in the contract storage. Each function
has its own scope, and state variables should always be defined outside of that scope.
// Solidity program to
// demonstrate state
// variables
pragma solidity ^0.5.0;

// Creating a contract
contract Solidity_var_Test {

// Declaring a state variable


uint8 public state_var;

// Defining a constructor
constructor() public {
state_var = 16;
}
}

Q.4 What is Modifier?

Modifiers assist in the execution of a function’s behavior. The behavior of a function


can be changed using a function modifier, they can also be called before or after a
function is executed.

Solidity function modifiers help in the following:

● To access restrictions
● Input accuracy checks
● Hacks protection

We can restrict access of the function by having owner only modifiers


contract Owner {
modifier onlyOwner {
require(msg.sender == owner);
_;
}

We can have input accuracy checks using the following:


modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}

Q.5 Explain Data types in Solidity.


In Solidity, a programming language for the Ethereum blockchain, there are several
data types that can be used to store values in variables or to define the types of
function parameters and return values. These data types include:
- bool: This is a boolean type that can store either true or false.
- int: This is an integer type that can store a whole number (positive or negative).
There are several variations of this type, including int8, int16, int32, int64, and
int128, which represent integers of different sizes.
- uint: This is an unsigned integer type that can store a whole number (positive
only). Like int, there are several variations of this type including uint8, uint16,
uint32, uint64, and uint128.
- address: This is a type that represents an Ethereum address. It can be used to
store the address of a contract or an external actor.
- bytes: This is a type that represents a sequence of bytes (integers in the range
0-255). There are several variations of this type, including bytes1, bytes2,
bytes3, and so on, which represent byte arrays of different sizes.
- string: This is a type that represents a string of Unicode characters.

In addition to these basic types, Solidity also supports arrays, structs, and enums,
which can be used to store and manipulate more complex data structures.

Q.6 Explain Solidity expressions.


In Solidity, an expression is a piece of code that returns a value. Expressions can be
used in various places in your code, such as in assignments, function calls, and
conditional statements.

There are many types of expressions in Solidity, including:

- Literals: These are fixed values that can be assigned to variables. Examples
include numbers (e.g., 42), strings (e.g., "Hello, World!"), and booleans (e.g.,
true or false).

- Variables: These are named locations in memory that can hold a value.
Variables must be declared before they can be used in your code, and they can
be of various types (e.g., int, uint, bool).

- Operators: These are symbols that perform operations on one or more operands
(values or variables). Examples include arithmetic operators (e.g., +, -, *, /),
comparison operators (e.g., ==, !=, >, <), and logical operators (e.g., &&, ||, !).

- Function calls: These are expressions that invoke a function and return the
value returned by that function. Function calls can be made to both internal
(i.e., within the current contract) and external (i.e., another contract) functions.

- Conditional expressions: These are expressions that return a value based on a


boolean condition. The most common conditional expression is the ternary
operator (?:), which has the form "condition ? value1 : value2". If the condition
is true, the ternary operator returns value1; otherwise, it returns value2.

Q.7 decision control statements in Solidity.


Decision-making in programming is used when we have to adopt one out of a given
set of paths for program flow. For this purpose, conditional statements are used which
allows the program to execute the piece of code when the condition is fulfilled.
Solidity uses control statements to control the flow of execution of the program to
advance and branch-based changes to the state. The following conditional statements
are provided by Solidity.

If statement

This is the most basic conditional statement. It is used to make a decision whether the
statement or block of code will be executed or not. If the condition is true the
statements will be executed, else no statement will execute.
Syntax:
if (condition) {
statement or block of code to be executed if the condition is True
}

if…else statement

This statement is the next form of conditional statement which allows the program to
execute in a more controlled way. Here if the condition is true then the, if block is
executed while if the condition is false then the else block, is executed.
if (condition) {
statement or block of code to be executed if condition is True
} else {
statement or block of code to be executed if condition is False
}

if…else if…else statement

This is a modified form of if…else conditional statement which is used to make a


decision among several options. The statements start execution from if statement and
as the condition of any if block is true the block of code associated with it is executed
and the rest if are skipped, and if none of the conditions is true then the else block
executes.
Syntax:
if (condition) {
statement or block of code to be executed if the condition is True
} else if (condition 2) {
statement or block of code to be executed if the condition of else...if is True
} else {
statement or block of code to be executed if none of the condition is True
}

Q.8 loops in Solidity.


Solidity supports for, while, and do while loops.
Don't write loops that are unbounded as this can hit the gas limit, causing your
transaction to fail.
For the reason above, while and do while loops are rarely used.

Q.9 How to write a simple contract in solidity?

This contract has a balance that is stored on the blockchain and two functions:
addFunds and withdraw. The addFunds function allows users to add funds to the
balance, while the withdraw function allows them to withdraw funds from the balance.
The withdraw function also includes a require statement that checks that the balance is
greater than or equal to the amount being withdrawn. If it is not, the transaction will
fail and an error message will be displayed.
You can deploy this contract to the Ethereum blockchain using a tool like Remix,
which is a browser-based Solidity compiler and runtime environment. You can then
interact with the contract using Remix or a tool like MetaMask, which is a browser
extension that allows you to send transactions and interact with contracts on the
Ethereum blockchain.

Q.10 Explain Inheritance in solidity


Inheritance is one of the most important features of the object-oriented programming
language. It is a way of extending the functionality of a program, used to separate the
code, reduces the dependency, and increases the re-usability of the existing code.
Solidity supports inheritance between smart contracts, where multiple contracts can be
inherited into a single contract. The contract from which other contracts inherit
features is known as a base contract, while the contract which inherits the features is
called a derived contract. Simply, they are referred to as parent-child contracts. The
scope of inheritance in Solidity is limited to public and internal modifiers only. Some
of the key highlights of Solidity are:
● A derived contract can access all non-private members including state
variables and internal methods. But using this is not allowed.
● Function overriding is allowed provided function signature remains the
same. In case of the difference of output parameters, the compilation will
fail.
● We can call a super contract’s function using a super keyword or using a
super contract name.
● In the case of multiple inheritances, function calls using super gives
preference to most derived contracts.

Solidity provides different types of inheritance.

1. Single Inheritance

In Single or single level inheritance the functions and variables of one base contract
are inherited to only one derived contract.

2. Multi-level Inheritance
It is very similar to single inheritance, but the difference is that it has levels of the
relationship between the parent and the child. The child contract derived from a parent
also acts as a parent for the contract which is derived from it.

3. Hierarchical Inheritance

In Hierarchical inheritance, a parent contract has more than one child contracts. It is
mostly used when a common functionality is to be used in different places.

4. Multiple Inheritance

In Multiple Inheritance, a single contract can be inherited from many contracts. A


parent contract can have more than one child while a child contract can have more
than one parent.
For examples of all the above inheritance if you feel like writing refer:
https://www.geeksforgeeks.org/solidity-inheritance/

Q.11 Explain Interfaces in solidity


A Solidity contract interface is a list of function definitions without
implementation. In other words, an interface is a description of all functions that an
object must have for it to operate.
The interface enforces a defined set of properties and functions on a contract.
Solidity allows you to interact with other contracts without having their code by using
their interface. For example, if you want to interact with another contract from your
own contract, you provide your calls with an interface wrapper. By declaring an
interface, you can interact with other contracts, and call functions in another
contract.
Interfaces are usually found at the top of a Solidity contract, and they are identified
using the “interface” keyword. Because interfaces reduce code duplication and
overhead, they are most useful when decentralized applications require extensibility
and want to avoid complexity.
Solidity Interface Characteristics
1. The Solidity interface can inherit from other interfaces
2. Contracts can inherit interfaces as they would inherit other contracts
3. You can override an interface function
4. Data types defined inside interfaces can be accessed from other contracts
All functions that inherit from the interface must set the override modifier on every
function that overrides an interface function. Otherwise, the Solidity compiler will
throw an error.
Solidity Interface Requirements
There are some restrictions when creating interfaces in Solidity, and developers should
remember this list of the main interface requirements:
1. The interface cannot have any functions implemented
2. Functions of an interface can be only of type external
3. The interface cannot declare a constructor
4. The interface cannot declare state variables
Example:

https://www.alchemy.com/overviews/solidity-interface

Q.12 Explain Error handling in solidity.


Solidity uses state-reverting exceptions to handle errors, and such an exception will
undo all changes made to the state in the current call and simultaneously flag an error
to the caller. ‍

Solidity, an object-oriented programming language to implement smart contracts on


blockchains such as Ethereum, has numerous functions to address underlying issues
that can occur at compile time or runtime. Even though syntax error checks happen at
compile time, runtime errors are difficult to catch and mainly happen during the
contract execution process. Some runtime error examples include a divide-by-zero
type error, array-out-of-index error, and so on.

In effect, error handling in Solidity ensures atomicity as a property. When a smart


contract call terminates with an error, all the state changes (i.e., alterations made to
variables, balances, etc.) are reverted, all the way up the chain of contract calls.

Ways to Handle Solidity Error:


Require
The require function is used to verify inputs and conditions before execution.
For instance, if the condition is false, then the require function immediately stops
execution. In other words, require acts as a gate check modifier, preventing logic
from accessing further execution of function and thereby producing an error. Require
is ideal for logic flow gating and validating user inputs on functions.
Require statements declare prerequisites for running the function, which should be
satisfied prior to code execution. The require function accepts a single argument and
after evaluation, require returns a boolean value of true or false. In the event that the
execution is terminated due to a false condition, the unused gas is returned to the
caller and the state is reversed to the original state. Customer string messages can also
be added.

Here is an example of a require statement in Solidity:

Revert
‍Revert does not evaluate any condition and does not depend on any state or statement.
The revert statement is similar to the require statement in that the revert function can
handle the same error types as the require function, but it is more appropriate for
complex logic gates.

If a revert statement is called, the unused gas is returned and the state reverts to its
original state. The ability to add a custom message is the same as the require function.

Here is an example of a revert statement in Solidity:

Assert
Assert is a function that is used to check for code that should never be false, and plays
an important role in preventing impossible scenarios. If the assert function returns a
boolean value of true, then a terminal bug will be displayed and the programs will not
execute.
In contrast to the require and revert functions, assert does not return any unused gas
and instead, the assert function will consume the gas supply before proceeding to
reverse the program to its original state. Interestingly, prior to the Byzantium fork,
both the require and assert functions behaved in an identical manner, however,
compiled to distinct opcodes.

Assert Type Exceptions


A value is modulo or divided by zero
A zero-initialized variable of a function is called
A negative or large value is converted to an enum
Accessing an array within an index that is negative or larger than expected

Q.13 What is the difference between an abstract contract and an Interface?


In Solidity, an interface is a collection of function signatures that defines a contract's
external API. It does not contain any implementation code, only the declarations of
the functions that make up the contract's API. Interfaces are used to define a standard
or contract that other contracts can implement.

On the other hand, an abstract contract is a contract that contains both function
declarations and implementation code, but the implementation code is incomplete. An
abstract contract is used as a base contract from which other contracts can inherit and
override the implementation code.

Here is an example of an interface and an abstract contract in Solidity


In the example above, IMyInterface is an interface that defines two functions: foo and
bar. MyAbstractContract is an abstract contract that defines two functions: baz and
qux. The virtual keyword indicates that these functions can be overridden in a derived
contract.

Q.14 Explain events in solidity.


Solidity events are crucial for smart contract developers because they allow smart
contracts to index variables in order to rebuild the storage stage, help to automatically
update the user interface, and allow for testing of specific variables.
In Solidity, events are dispatched signals that smart contracts can fire. When you
call events, they cause the arguments to be stored in the transaction’s log, which is a
special data structure in the blockchain. Events notify external users, such as a
listening frontend website or client application, that something has happened on the
blockchain.
The Ethereum Virtual Machine (EVM) has a logging function that is used to
write data, including Solidity events, to a structure outside smart contracts.

Logs and events are often referred to synonymously. Events allow you to ‘print’
information to the logging structure in a way that is more gas-efficient since the
information is not stored in a storage variable, which takes up more gas. Events, or
logs, live in the Transaction Receipts trie, which is inaccessible to smart contracts.

Solidity events are interfaces with EVM logging functionality. You can add an
attribute indexed to up to three parameters. Then they appear in the structure of topics,
not the data portion of the log. When parameters do not have the indexed attributes,
they are ABI-encoded into the data portion of the log.
There are two types of Solidity events: those which are indexed and those which are
not.

When parameters do not have the indexed attribute, they are ABI-encoded into the
data portion of the log. These parameters form the byte array of the event. Data is
encoded according to its type and can be decoded according to a schema.

Indexed parameters are also known as “topics”, are the searchable parameters in
events. The indexed parameters will allow you to search for these events using the
indexed parameters as filters. You can add an attribute indexed up to 4 parameters or 3
parameters based on whether the events are anonymous or not, respectively.

Q.15 Explain the use of assert and revert in solidity with the help of an example.

Refer Error Handling Q.12

You might also like