Final Unit 4
Final Unit 4
1. Concept of Ledger
•Ledger is constructed by the ordering service as a totally ordered hashchain of blocks of (valid or invalid)
transactions. The hash chain imposes the total order of blocks in a ledger and each block contains an array of
totally ordered transactions. This imposes total order across all transactions. •Ledger is kept at all peers and
optionally, at a subset of orders.
•A permissioned ledger is a ledger where actors must have permission to access the ledger. •Permissioned ledgers
map to closed trust-some or trust-all ledgers. Permission is granted in two different ways. The first is via a white
list, a list of actors allowed to join the ledger's community. The second is via a black list, a list of actors who are
banned from the ledger's community: a permissioned ledger using a black list would be a closed, trust-some ledger,
a permissioned ledger using a white list could be either an open or closed, trust-some ledger.
•A permissioned ledger introduces some form of access control in the way transactions are accessed and managed.
• A token ledger is a ledger requiring a currency to function, typically to pay the miners or to make denial of
service attacks economically challenging. Tokenless ledgers don't require a currency to operate.
Distributed ledger
•Distributed ledger is the core persistent layer in the blockchain architecture. It provides a decentralized and
distributed database containing the transaction entries. These entries are recorded in the order of its occurrence
and composed into hashed blocks.
•The database or the ledger, therefore, represents a chain of hashed blocks of transactions with each block referring
to the previous block in the chain. The ledger is shared across the blockchain network, which means every node
has a copy of the ledger, and each node verifies the transactions independently.
•When every node agrees and confirms the authenticity of the transaction, the ledger is said to be in consensus.
The blockchain network uses different consensus algorithms to arrive at the consensus.
•The consensus algorithm is a set of rules and conditions that governs the transaction. The blockchain network
implemented for the public has a permissionless ledger, while in a private network or a consortium, a ledger can
be made permissioned.
•The distributed ledger protocol of the fabric is run by peers. The fabric distinguishes between two kinds of peers:
1. A validating peer is a node on the network responsible for running consensus validating transactions and
maintaining the ledger.
2. Non-validating peer is a node that functions as a proxy to connect clients (issuing transactions) to validating
peers. A non-validating peer does not execute transactions but it may verify them.
2. Introduction of Hyperledger
•Hyperledger is an open source project created to support the development of blockchain- based distributed
ledgers. Hyperledger consists of a collaborative effort to create the needed frameworks, standards, tools and
libraries to build blockchains and related applications.
• Hyperledger Fabric is a consortium blockchain. Obtaining identity authentication and organizational permission
is a prerequisite for accessing the Fabric network. After joining the network, members jointly maintain a
distributed ledger. All data operations are public, and will be permanently recorded and cannot be tampered with.
• In Hyperledger Fabric, the communication security of each network node is guaranteed by the Public Key
Infrastructure (PKI), which signs and authenticates user identities and communication messages.
Hyperledger Fabric is a blockchain that achieves data privacy via "channels", which enable private
communications between two or more network members.
• It allows flexible network permission setup, as well as helps you to create private systems with inaccessible
blocks, meaning third parties can't extract any data from them.
•Transactions can be made confidential, only accessible to users with the necessary decryption keys.
•It can be utilized using various programming languages, such as C++, JavaScript, Python, Golang and Java.
•Hyperledger Fabric is a block chain framework. It works together with other Hyperledger projects such as Burrow
and Sawtooth to provide a scalable data platform. Hyperledger Fabric is a platform on which applications may be
developed.
•Hyperledger fabric is built upon a few central components:
a) Distributed ledger for all data recorded about the transactions
b) Multiple peers (or nodes)
c) Smart contracts that maintain transaction logic
1. Advantages:
• Hyperledger Fabric is the basis for decentralized networks, where all participants have identifiers.
• Hyperledger Fabric is built on a modular architecture.
• Fabric decentralized book and smart contract platform allow private channels to be used.
• Fabric features a 'Hardware Security Model (HSM) that helps in safeguarding and managing digital keys used
for authentication.
2. Disadvantages:
• There is network fault tolerance.
• Inadequately skilled programmers.
• Lock of proven use cases.
3. Chaincode
• The chaincode is a program that handles business logic agreed to by members of the network, so it may be
considered as a 'smart contract'. Chaincode runs in a secured Docker container isolated from the endorsing peer
process. Chaincode initializes and manages ledger state through transactions submitted by applications.
• Chaincodes define the data schema in the ledger, initialize it, perform updates when triggered by applications,
and respond to queries. Chaincodes can also post events that allow applications to be notified and perform
downstream operations. For example, after purchase orders, invoices and delivery records have been matched by
a chaincode, it can post an event so that a subscribing application can process related payments and update an
internal ERP system.
• Chaincode is sandboxed in a secure container, which includes a secure operating system, chaincode language,
runtime environment, and SDKs for Go, Java and Node.js.
• 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:
1. Install and define a chaincode
2. Upgrade a chaincode
3. Deployment scenarios
4. Migrate to the new fabric lifecycle
1. Package the chaincode: This step can be completed by one organization or by each organization.
2. Install the chaincode on 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 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 Lifecycle Endorsment policy 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.
4. Ethereum
Introduction of Ethereum
• Ethereum is a decentralized blockchain platform that establishes a peer-to-peer network that securely executes
and verifies application code, called smart contracts.
• Ethereum is a decentralized, open source and distributed computing platform that enables the creation of smart
contracts and decentralized applications, also known as dapps
• Ethereum is an open-source operating system that deals with smart contract functionality.
• Ethereum is open source and used primarily to support the second-largest cryptocurrency in the world known as
Ether.
• Ethereum is also a programming language that helps developers to create distributed applications. Ethereum
split into two different blockchains in 2016 namely Ethereum and Ethereum Classic.
• Ethereum aims to provide a system that gives users more control over their data and it also allows for applications
to be built and run on the blockchain. To run these applications and have this level of control on the Ethereum
platform, it requires Ether.
• Ethereum smart contract: A smart contract is application code that resides at a specific address on the blockchain
known as a contract address. Applications can call the smart contract functions, change their state and initiate
transactions. Smart contracts are written in programming languages such as Solidity and Vyper and are compiled
by the Ethereum Virtual Machine into bytecode and executed on the blockchain.
• Ethereum is the major distributed software application. It supports to build smart contracts and distributed
applications without downtime or third-party interference. Ethereum permits the developer to create and broadcast
next-generation distributed applications.
• The Ethereum platform permits developers to form powerful decentralized applications with in-built economic
functions. Though providing high accessibility, auditability, transparency and neutrality, it also reduces or
eliminates censorship and decreases assured counterparty risks.
• These centralized systems are good extensive models for software applications. This system directly controls
the operation of the individual units and the flow of information from a single center. In this kind of system,
individuals are dependent on the central power to send and receive information.
• The Ethereum blockchain has a native coin that is known as Ether (ETH), which is used to pay for activity on
the Ethereum blockchain. The coin also trades on crypto exchanges and fluctuates in value.
Features of Ethereum
• An account is the minimum storage requirement, just like an address in the Bitcoin protocol. Accounts are one
of the main building blocks of the Ethereum blockchain.
• The state transition is achieved using what's called the Ethereum state transition function, which works as
follows:
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.
3. Provide enough Ether (gas price) to cover the cost of the transaction.
4. In cases of transaction failure due to insufficient account balance or gas, all state changes are rolled back except
for 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 fees are paid to the miners
accordingly. At this point, the function returns the resulting state which is also stored on the blockchain.
• There are two types of accounts on Ethereum: externally owned accounts and contract accounts.
• An Externally Owned Account (EOA) is controlled by a private key. A Contract Account (CA) is controlled by
a piece of code in place of the private.key.
• Each account, regardless of its type consists of the following four elements:
1. Nonce: A number corresponding to the amount of (a) transactions sent from or (b) Contracts created by an
account.
2. Balance: amount owned by an account.
3. storage Root: A hash of the root node of a hash tree that encodes the storage contents of the account.
4. codeHash: A hash of the account's EVM code.
• EOAs are like to accounts that are controlled by a private key in bitcoin. Contract accounts are having private
key along with the accounts that have code associated with them.
• An EOA has ether balance, is capable to send transactions and has no related code, whereas a Contract Account
(CA) has ether balance, associated code and the ability to get caused and accomplish code in response to a
transaction or a message that due to the Turing extensiveness property of the Ethereum blockchain network, the
code within contract accounts can be of one of the level of complexity.
Ethereum Block
Ethereum blocks consist of following components:
1. The block header
2. The transactions list
3. The list of headers of ommers or uncles
• The transaction list is just a list of all transactions involved in the block. In adding, the list of headers of Uncles
is also incorporated in the block. The utmost significant and difficult part is the block header. Block header: The
block headers are the most serious and comprehensive components of an
Ethereum block. The header contains valued information, which is described in detail here.
1. Parent hash: This is the Keccak 256-bit hash of the parent (earlier)block's header.
2. Ommers hash: This is the Keccak 256-bit hash of the list of Ommers (Uncles) blocks included in the block.
3. Beneficiary: This field contains the 160-bit address of the receiver that will accept the mining payment once
the block is fruitfully mined.
4. State root: This field contains the Keccak 256-bit hash of the root node of the state tries.
5. Transactions root: This root is the Keccak 256-bit hash of the root node of the transaction tries. Transaction
tries denotes the list of transactions involved in the block
6. Receipts root: The receipts root is the Keccak 256 bit hash of the root node of the transaction receipt tries. This
tries is to collected of receipts of entirely transactions involved in the block.
7. Logs bloom: The logs bloom worked as a bloom filter that is collected of the logger address and log topics from
the log entry of each transaction receipt of the involved transaction list in the block.
8. Number: The count of total number of all earlier blocks; the origin block is block zero.
9. Gas limit: The field contains the value that represents the limit set on the gas intake per block.
10. Gas used: The field contains the total gas spent by the transactions included in the block.
11. Timestamp: Timestamp is the period Unix time of the time of block initialization.
12. Extra data: Extra data field can be used to supply arbitrary data related to the block.
2. Testnet:
• Testnet on the other hand is a testing network that runs the same protocol as Mainnet does and is used for testing
purposes. It allows you to experiment without having to use valuable coins on the main network (Mainnet).
• The programmers use testnet to troubleshoot and experiment any new features on a blockchain.
• The main dissimilarity between testnets and mainnets is that the previous is a blockchain project that is in
progress, while the latter encompasses a completely developed blockchain.
• A testnet is used by programmers and developers to test and troubleshoot all the aspects and features of a
blockchain network before they are sure the system is secure and ready for the mainnet launch.
• In other words, a testnet only exists as a working prototype for a blockchain project, while a mainnet is a
completely developed blockchain platform for users to send and receive cryptocurrency transactions.
History The word bitcoin was defined in a white Ethereum was conceived in 2013 by
paper published on 31 October 2008. The programmer Vitalik Buterin, and then
currency began use in 2009. went live on 30 July 2015.
Smart Contracts Although bitcoin do have smart contracts, Ethereum allows us to create smart
they are not as flexible or complete as contracts. Smart contracts are
Ethereum smart contracts. Smart contracts computer codes that is stored on a
Basis Bitcoin Ethereum
in Bitcoin does not have all the blockchain and executed when the
functionality that a programming language predetermined terms and conditions
would give them. are met.
Smart Contract Smart contracts on Bitcoin are written in Smart contracts on Ethereum are
Programming programming languages like Script, written in programming languages like
Language Clarity. Solidity, Vyper, etc.
Transactions Generally, bitcoin transactions are only for Ethereum transactions may contain
keeping notes. some executable code.
Hash Algorithm Bitcoin runs on the SHA-256 hash Ethereum runs on the Keccak-
algorithm. 256 hash algorithm.
Block Limit The bitcoin blockchain has a block limit of The Ethereum blockchain does not
1 MB. have a block limit.
Energy
Energy consumption rate of bitcoin Energy consumption rate of bitcoin
Consumption
mining system 3.2 Million household. mining system 1.2 Million household.
rate
Rewards Miner got nearly 6.25 BTC on Miner got nearly 5 BTC along with
successfully adding new block in network. same additional rewards on
Basis Bitcoin Ethereum
Programming
Solidity Golang, JavaScript, or Java
Language
• Voting systems: Voting systems are implemented by using Ethereum. The outcomes of polls are widely
presented, confirming a transparent and fair self-governing procedure by removing passed by vote misuses.
• Banking systems: Ethereum is accomplishment approved extensively in banking application since with
Ethereum's decentralized system, provides strong security for data and unauthorized access to hacker is denied.
• Shipping: Deploying Ethereum in shipping benefits with the pursuing of cargo and prevents goods from being
misdirected or imitated. Ethereum makes available the derivation and tracking framework for any asset required
in a typical supply chain.
• Agreements: With Ethereum smart contracts, arrangements can be preserved and implemented without some
alteration. So in a business that has disjointed applicants, is subject to disagreements and needs digital contracts
to be contemporaneous, Ethereum is a technology for developed smart contracts and for digitally recording the
agreements and the transactions based on them.
Purpose of EVM
The Ethereum Virtual Machine (EVM) is a Turing complete programmable machine, which can execute sc
ripts to produce arbitrary outcomes. It has been built with the purpose of being a “world computer” and ha
s immense power.
It is the computer that stores data on blockchain, like bitcoin, but it also executes code in smart contract
s on the Ethereum network.
The machine is made to be able to run any kind of Crypto-contract that can be built on Ethereum’s bl
ockchain. It does this by using a programming language called Solidity, which is compiled into the EVM
for execution.
The intention behind writing code on the Ethereum network is to create smart contracts and programs that
automatically execute things when certain conditions are met. If a terms or condition is not met, the
system can execute it in an “exit” function as well.
For example, if an account has been hacked, the hacker cannot steal money from the system, because they
don’t have the budget or authority to do so.
Working of EVM
• The EVM uses a stack-based architecture and a word size of 256 bits. The 256-bit word size allows the EVM to
facilitate native hashing and elliptic curve operations that ensure funds can be spent only by their rightful owners.
• The storage associated with the EVM is a word-addressable word array that is non-volatile and is maintained as
part of the system state. Keys and values are 32 bytes in size and storage. The program code is stored in virtual
read-only memory (virtual ROM) that is accessible using the CODECOPY instruction. The CODECOPY
instruction copies the program code into the main memory. Initially, all storage and memory are set to zero in the
EVM.
•The design of the EVM where the virtual ROM stores the program code that is copied into the main memory
using the CODECOPY instruction. The main memory is then read by the EVM by referring to the program counter
and executes instructions step by step. The program counter and EVM stack are updated accordingly with each
instruction execution.
•EVM stack on the left side showing that elements are pushed and popped from the stack. It also shows that a
program counter is maintained and is incremented with instructions being read from the main memory. The main
memory gets the program code from the virtual ROM/storage via the CODECOPY instruction.
Design of EVM
• The EVM supports various programming languages such as Vyper and Solidity, with Solidity being the most
popular programming language for smart contract source code. These programming languages are used to write
smart contracts, which are converted into the bytecode needed to be utilized by the EVM.
• The bytecode stored on-chain, known as the runtime bytecode, is then converted into an opcode that the EVM
computation engine interprets to carry out those actions.
• When an Ethereum transaction executes a smart contract, an EVM is loaded with the information for the
transaction being processed. For example, one variable needed for a smart contract execution is the gas supply,
which is set to the amount of gas paid by the sender.
• The gas supply is reduced as the transaction progresses, and if, at any point, the gas supply reaches zero, the
transaction is abandoned. Although abandoned transactions don't result in changes to the Ethereum state and are
not considered valid transactions, the block's beneficiary is paid for providing resources up to the halting point.
• Smart contracts can initiate transactions and call other contracts on their own. In this case, each call results in
another EVM being loaded with specific information for the new transaction. This new information is initialized
from the EVM one level above.
• If there isn't enough gas to complete the execution, the state is discarded and the transaction execution is reset
to the EVM one level above.
• The Mist browser was intended to be an integral part of the Ethereum network's dApps
(decentralized applications) ecosystem. It was the first graphical user interface that enabled
users to access the blockchain at a time when you could only access it via the command line.
• Mist browser is a user-friendly interface for end users with a feature-rich graphical user interface that is used to
browse Decentralized Applications (DApps) and for account management and contract management.
• Mist browser is not a wallet; in fact, it is a browser of DApps and provides a user-friendly user interface for the
creation and management of contracts, accounts, and browsing decentralized applications. Ethereum wallet is a
DApp that is released with Mist.
• Mist was the first browser that allowed users to browse dApps and it had an Ethereum wallet built in. It was also
the first desktop crypto wallet with a graphical user interface.
• The Mist Ethereum wallet itself would run on a user's computer, which meant it had to be downloaded, installed
and run locally.
• Mist browser was based on electron, an open-source project that aims to ease the creation of cross-platform
applications using JavaScrip.
• The Mist browser was a decentralized app on the Ethereum network from 2015 to 2019.
• Mist was the first browser that allowed users to browse dApps, and it had an Ethereum wallet built in. It was
also the first desktop crypto wallet with a graphical user interface (GUI).
• Mist was deprecated in March 2019 after developers decided other browser developers and wallet makers
were better able to create products for this quickly evolving space.
7.Ether
• Ether is the name of the crypto-currency used to pay for transactions on the Ethereum network. Asides from
paying for general transactions and services, Ether is also used to buy gas, which in turn is used to pay for
computation within the EVM.
•Ether is the metric unit and has a lot of denominations which help accurately pay for transactions and gas. The
smallest denomination a.k.a base unit is called Wei.
•Ether (ETH) is the native cryptocurrency of Ethereum. The purpose of ETH is to allow for a market for
computation. Such a market provides an economic incentive for participants to verify and execute transaction
requests and provide computational resources to the network.
• Any participant who broadcasts a transaction request must also offer some amount of ETH to the network as a
bounty. The network will award this bounty to whoever eventually does the work of verifying the transaction,
executing it, committing it to the blockchain, and broadcasting it to the network.
•The amount of ETH paid corresponds to the resources required to do the computation. These bounties also
prevent malicious participants from intentionally clogging the network by requesting the execution of infinite
computation or other resource-intensive scripts, as these participants must pay for computation resources.
•ETH is also used to provide crypto-economic security to the network in three main ways:
1) It is used as a means to reward validators who propose blocks or call out dishonest behavior by other validators.
2) It is staked by validators, acting as collateral against dishonest behavior if validators attempt to misbehave their
ETH can be destroyed.
3) It is used to weigh 'votes' for newly proposed blocks, feeding into the fork-choice part of the consensus
mechanism.
8.Gas
•Gas keeps the Ethereum blockchain safe. It is what also allows (previously) miners (now) validators to profit and
provides incentive for doing the necessary work of proposing the next block of transactions for the blockchain.
So, what exactly is gas, and how does it work?
•Gas is a fee placed on top of any transaction on the Ethereum network, which is paid directly to the miner or
validators who is making the effort to validate and execute the bytecode of a transaction. Gas also keeps the
network safe through stopping an attacker from overloading the Ethereum network with transactions, Gas is the
resource that enables the execution of code in the EVM environment, measured in wei (a unit of ether). Just like
you need gas to power your car in real life, the EVM needs gas to execute operations.
•Gas is used as a metric for paying for computational resources on the network. Every contract on the network
has a set maximum amount of gas that it can use for its computations. This is known as the "Gas Limit".
• Gas price: This is the cost of gas in terms of tokens like Ether and its other denominations. To stabilize the value
of gas, the gas price is a floating value such that if the cost of tokens or currency fluctuates, the gas price changes
to keep the same real value.
Gas fee: This is effectively the amount of gas needed to be paid to run a particular transaction or program.
•While Ethereum and polygon use the term "gas fees," other blockchains such as Solana and Bitcoin use the term
"transaction fees." "Gas" comes from the fee's similarity to the fuel which keeps a vehicle running.
• Gas fees are also important in blockchain protocols using the proof-of-stake (PoS) consensus mechanism, such
as the next evolution of Ethereum, Ethereum 2.0. On these blockchains, gas fees reward validators who first
commit a certain amount of cryptocurrency to the network in order to be selected to verify new transactions.
• Two factors determine the amount of gas required by a transaction:
1. The complexity of the transaction.
2. The current load on the Ethereum network.
First factor: The normal way to update a blockchain is that a block filled with transactions is proposed and accepted
into the blockchain. For each of these transactions, a miner/validator must validate them and execute their
bytecode, which is composed of instructions.
• The base cost to have some transaction validated is 21000 gwei, where one gwei is one one- billionth, or
0.000000001 ETH. Then, an additional fee is placed on top of the base cost, determined by the amount of
instructions to be executed.
Each opcode has an associated gas cost, and when executed, consumes that amount of gas.
When we get to more complicated bytecode in smart contract transactions, the amount of instructions executed
drastically increases, which is why gas fees are higher for smart contracts than for static transactions. Second
factor: For determining the price of a transaction is the current load, or how heavily congested the Ethereum
network is.
• The formula for calculating gas is:
Gas price Gas units X (Base fee + Tip)
• The base fee's price is determined by Ethereum's network congestion. The tip is a priority fee and is set
automatically by most wallets to speed up our transaction's completion, so it's not very important when calculating
gas.
• The base fee for the current block is calculated based on previous blocks. When a new block is added onto the
blockchain, there is a set amount of gas, called included gas, that it can hold.
•In the block with the lowest base fee of 100 gwei, block number 1, included gas is 15M gwei. If the included gas
is completely filled, the base fee will increase by a maximum of 12.5% per block and the block number will
increase.
9. Solidity
•Solidity is the main programming language for writing smart contracts for the Ethereum blockchain. It is a
contract-oriented language, which means that smart contracts are responsible for storing all of the programming
logic that transacts with the blockchain.
•Solidity is an object-oriented programming language created specifically by the Ethereum network team for
constructing and designing smart contracts on blockchain platforms.
• It is a high-level programming language that looks a lot like JavaScript, Python, and C++. It's designed to run
on the Ethereum Virtual Machine, which is hosted on Ethereum nodes that are connected to the blockchain.
• It is statically typed and supports inheritance, libraries and more. In short, it has all the capability that we need
in order build industrial strength blockchain applications.
b) Actions
• Create a truffle project and set up a development network for it.
• Develop and deploy a smart contract for it.
• From the Truffle console, interact with the smart contract.
• Create tests to evaluate Solidity's primary features.
2. Online mode: In the Online mode, the Remix IDE is typically used to compile and run Solidity smart contracts.
• Let's say user need to make and call a Faucet contract from in an additional contract called Token:
import "Faucet.sol";
contract Token is mortal
{
Faucet faucet;
constructor()
{
_faucet new Faucet();
}
}
contract Token is mortal
{
Faucet faucet;
constructor()
{
faucet new Faucet();
}
}
• This mechanism for contract building guarantees that you distinguish the particular kind of the contract and its
interface.
import "Faucet.sol";
contract Token is mortal
{
Faucet faucet;
constructor()
{
_faucet= new Faucet();
}
}
• You can similarly then call the Faucet functions. In this below example, we call the detroy function of Faucet
from in the destroy function of Token:
import "Faucet.sol";
contract Token is mortal
{
Faucet_faucet;
constructor()
{
_faucet = new Faucet();
}
function destroy() owner Only
{
_faucet.destroy();
}