Block Chain
Block Chain
Unit - 3:
Other considerations:
● Some argue smart contracts should be automatable (allowing human input), but the
author insists true smart contracts must be fully automated, with oracles providing
external inputs where needed.
● Smart contracts typically follow a state machine model, evolving based on specific
conditions.
● Legal and regulatory challenges persist: Courts struggle to interpret code as contracts,
raising issues about human readability, semantics, and dispute resolution.
● Smart contracts must be deterministic — producing the same result on every node to
ensure blockchain consensus.
Essential Properties
BB Gang
Ricardian Contracts
● Origin: Proposed by Ian Grigg in the late 1990s (from Financial Cryptography in 7
Layers paper); first used in the Ricardo bond trading system.
● Purpose: Bridge the gap between human-readable legal contracts and machine-readable,
enforceable code — making contracts understandable by both courts and software.
BB Gang
How it works
Structure
BB Gang
Smart Contract Templates:
● Concept: Smart contract templates provide standardized frameworks for creating legal
agreements, especially in the financial industry.
● Origin: Proposed by Clack et al in their paper Smart Contract Templates: Foundations,
design landscape and research directions.
● Goal: Support legal agreements for financial instruments using standard, reusable
templates.
● DSLs are specialized programming languages designed for a specific domain (e.g.,
insurance, energy derivatives, trading strategies).
● DSLs are optimized for their domain and offer limited, focused features, unlike
general-purpose languages (GPLs).
● The financial industry already uses many DSLs (see dslfin.org).
BB Gang
Oracles
Oracles are essential components in the smart contract ecosystem, enabling contracts to access
external data they cannot retrieve on their own (e.g., stock prices, weather, IoT data). They act
as bridges between the blockchain and the real world, ensuring contracts can execute based on
real-world conditions.
Oracles provide:
● Standard Oracles: Centralized, trusted entities (e.g., large data providers). These raise
concerns about trust and centralization.
● Decentralized Oracles: Distribute data sourcing across multiple parties or blockchains,
reducing reliance on any single entity and enhancing trust.
● Hardware Oracles: Supply data directly from tamper-proof physical devices (common
in IoT and telemetry use cases).
BB Gang
Smart Oracles
● Smart Oracles extend the concept of standard Oracles by adding the ability to execute
contract code.
● They not only supply external data but can also process and run the business logic
associated with that data.
● Codius is a notable implementation of Smart Oracles.
○ Developed to enable both data delivery and contract execution.
○ Utilizes Google Native Client — a sandboxed environment designed for safely
running untrusted x86 native code.
● Smart Oracles enhance flexibility by combining external data feeds with on-chain and
off-chain code execution.
● Smart contracts can function with or without being deployed on a blockchain, but
deployment on blockchain is preferred due to distributed consensus.
● Ethereum natively supports smart contract development and deployment, often as part of
larger systems like Decentralized Autonomous Organizations (DAOs).
● Bitcoin has limited smart contract capability:
○ Uses lock_time in transactions to lock/unlock funds after a certain time or block
count (a basic contract feature).
○ Its scripting language allows constructing simple contracts (e.g., funding an
address spendable only with a hash collision attack).
● Bitcoin's contract capabilities are basic compared to platforms like Ethereum designed for
richer smart contract functionality.
BB Gang
The DAO
● The DAO (Decentralized Autonomous Organization) launched in April 2016 as one of
the largest crowdfunded projects.
● It was a set of smart contracts designed to provide a decentralized investment platform.
● In June 2016, a bug in the code led to an exploit where ~$50 million worth of Ether was
siphoned into another account.
● The incident triggered a hard fork on Ethereum to recover the stolen funds.
● This event showed:
○ The immaturity of the "code is law" concept and the risks of blindly trusting smart
contract code.
○ The Ethereum foundation’s intervention via a hard fork contradicted the principle
of unstoppable decentralization.
● The hard fork led to the split between:
○ Ethereum (ETH) — the forked chain with recovered funds.
○ Ethereum Classic (ETC) — the original chain adhering to "code is law".
BB Gang
Unit-4
Ethereum
Introduction
● Ethereum was conceptualized by Vitalik Buterin in November 2013.
● The key idea was to develop a Turing-complete language that enables creation of
arbitrary programs (smart contracts) on the blockchain.
● This contrasts with Bitcoin, which has a limited scripting language allowing only basic,
necessary operations.
● Ethereum supports the development of decentralized applications (dApps) beyond simple
transactions.
BB Gang
The Ethereum stack
● Ethereum blockchain
○ Operates on a peer-to-peer (P2P) Ethereum network
○ Forms the core of the Ethereum ecosystem
● Ethereum client (e.g., geth)
○ Runs on nodes to connect with the P2P network
○ Downloads and stores the blockchain locally
○ Provides functions like mining, account management, and network
synchronization
● web3.js library
○ Interacts with the Ethereum client through Remote Procedure Call (RPC)
interface
○ Enables external applications to communicate with the Ethereum network
BB Gang
Ethereum blockchain
BB Gang
Forks
● The Homestead release introduced major protocol upgrades, leading to a hard fork at
block number 1,150,000, transitioning from Frontier to Homestead.
● An unintentional fork occurred on November 24, 2016, at 14:12:07 UTC at block
number 2,686,351.
● Cause:
○ A bug in the geth client's journaling mechanism.
○ Geth failed to revert empty account deletions during an empty out-of-gas
exception.
○ Parity client was unaffected by this issue.
● Result:
○ The blockchain split into two chains — one using parity and the other using
geth.
● Resolution:
○ The issue was fixed with the release of geth version 1.5.3.
○
Gas
Gas is another key concept in Ethereum. All transactions on the Ethereum blockchain are
required to cover the cost of computation they are performing. The cost is covered by gas or
crypto fuel, a concept introduced by Ethereum. This gas, as an execution fee, is paid upfront by
the transaction originators. The fuel is consumed with each operation.
Gas provides:
● Cost coverage for each operation: Each operation has a predefined amount of gas
associated with it.
● Control over transaction execution: Each transaction specifies the amount of gas it is
willing to consume for its execution.
● Rollback mechanism: If it runs out of gas before execution is completed, any operation
performed by the transaction up to that point is rolled back.
● Refund of unused gas: If the transaction is successfully executed, any remaining gas is
refunded to the transaction originator.
BB Gang
The Consensus Mechanism
The consensus mechanism in Ethereum is based on the GHOST protocol (Greedy Heaviest
Observed Subtree), originally proposed by Zohar and Sompolinsky in December 2013.
● Selection of the main chain: The chain that has the most computational effort spent on it
is identified as the definite version.
● Longest chain rule: The longest chain is considered valid, as it reflects the most mining
effort.
● Stale blocks: Blocks that are not part of the main chain due to fast block generation
times.
● Uncles/Ommers: The stale blocks in Ethereum, which are still included in calculations to
determine the longest and heaviest chain.
BB Gang
The World State
The world state in Ethereum represents the global state of the Ethereum blockchain. It is
basically a mapping between Ethereum addresses and account states. The addresses are 20
bytes long.
● Mapping of addresses to account states: This mapping forms the global state structure
of Ethereum.
● Serialization of data: The mapping is serialized using Recursive Length Prefix (RLP).
BB Gang
The account state provides:
● Nonce: A value incremented every time a transaction is sent from the address. For
contract accounts, it represents the number of contracts created by the account.
● Balance: Represents the number of Weis (the smallest unit of Ether) held by the address.
● Storageroot: Represents the root node of a Merkle Patricia tree that encodes the storage
contents of the account.
● Codehash: An immutable field containing the hash of the smart contract code associated
with the account. For normal accounts, it contains the Keccak 256-bit hash of an empty
string. This code is invoked via a message call.
● The account data structure contains a storage root hash derived from the root node of
the account storage trie.
● The account data structure is used in the world state trie, which maps addresses to
account states.
● The root node of the world state trie is hashed using the Keccak 256-bit algorithm and
included in the block header as the state root hash.
● The accounts trie is a Merkle Patricia tree that encodes the storage contents of an
account. The contents are stored as a mapping between Keccak 256-bit hashes of 256-bit
integer keys and RLP-encoded 256-bit integer values.
BB Gang
Transactions
A transaction in Ethereum is a digitally signed data packet using a private key that contains the
instructions that, when completed, either result in a message call or contract creation.
Transactions can be divided into two types based on the output they produce:
● Message call transactions: This transaction simply produces a message call that is used
to pass messages from one account to another.
● Contract creation transactions: As the name suggests, these transactions result in the
creation of a new contract. This means that when this transaction is executed
successfully, it creates an account with the associated code.
● Nonce: A counter incremented with each transaction from the sender; ensures
uniqueness.
● Signature (V, R, S): ECDSA signature parts used to verify sender identity.
BB Gang
Contract Creation Transaction
There are a few essential parameters that are required when creating an account. These
parameters are listed as follows:
Addresses generated as a result of contract creation transaction are 160-bit in length. Precisely,
as defined in the yellow paper, they are the rightmost 160-bits of the Keccak hash of the RLP
encoding of the structure containing only the sender and the nonce.
BB Gang
The account is initialized when the EVM code (Initialization EVM code) is executed. In the
case of any exception during code execution, such as not having enough gas, the state does not
change. If the execution is successful, then the account is created after the payment of
appropriate gas costs.
The current version of Ethereum (Homestead) specifies that the result of contract transaction is
either:
This is in contrast to previous versions, where the contract could be created regardless of the
contract code deployment being successful or not due to an out-of-gas exception.
Message calls also produce output data, which is not used if transactions are executed. In cases
where message calls are triggered by VM code, the output produced by the transaction execution
is used.
BB Gang
BB Gang
Elements of the Ethereum Blockchain
In the following section, you will be introduced to various components of the Ethereum network
and the blockchain. First, the basic concept of the EVM is given in the next section.
● Memory: A byte array that is cleared when the contract finishes execution. It is like
RAM. Memory is unlimited but constrained by gas fee requirements.
● Storage: Permanently stored on the blockchain. It is a key-value store. The storage is a
word-addressable word array that is nonvolatile and part of the system state. Keys and
values are 32 bytes in size.
Other details:
● The program code is stored in a virtual read-only memory (virtual ROM) that is
accessible using the CODECOPY instruction. This instruction copies the program code
into main memory.
● Initially, all storage and memory are set to zero in the EVM.
● The program counter and EVM stack are updated accordingly with each instruction
execution.
BB Gang
EVM optimization is an active area of research. Recent research suggests EVM can be
optimized to achieve high performance. Research into using WebAssembly (WASM) is
underway. WASM is developed by Google, Mozilla, and Microsoft and is being designed as an
open standard by the W3C community group. The aim of WASM is to run machine code in the
browser at native speed. Similarly, the aim of EVM 2.0 is to run the EVM instruction set
(opcodes) natively in CPUs to make it faster and more efficient.
BB Gang
Execution Environment
There are some key elements that are required by the execution environment in order to execute
the code. The key parameters are provided by the execution agent, for example, a transaction.
These are listed as follows:
1. The address of the account that owns the executing code.
2. The address of the sender of the transaction and the originating address of this
execution.
3. The gas price in the transaction that initiated the execution.
4. Input data or transaction data depending on the type of executing agent. This is a byte
array; in the case of a message call, if the execution agent is a transaction, then the
transaction data is included as input data.
5. The address of the account that initiated the code execution or transaction sender.
This is the address of the sender in case the code execution is initiated by a transaction;
otherwise, it's the address of the account.
6. The value or transaction value. This is the amount in Wei. If the execution agent is a
transaction, then it is the transaction value.
7. The code to be executed presented as a byte array that the iterator function picks up in
each execution cycle.
8. The block header of the current block.
9. The number of message calls or contract creation transactions currently in
execution. In other words, this is the number of CALLs or CREATEs currently in
execution.
BB Gang
Machine State
Machine state is also maintained internally by the EVM. Machine state is updated after each
execution cycle of EVM. An iterator function (detailed in the next section) runs in the virtual
machine, which outputs the results of a single cycle of the state machine.
● Available gas
● Memory contents
The EVM is designed to handle exceptions and will halt (stop execution) in case any of the
following exceptions occur:
● Invalid instructions
Iterator Function
The iterator function mentioned earlier performs various important functions that are used to set
the next state of the machine and eventually the world state. These functions include the
following:
● It fetches the next instruction from a byte array where the machine code is stored in the
execution environment.
BB Gang
● It adds/removes (PUSH/POP) items from the stack accordingly.
BB Gang
Accounts
Accounts are one of the main building blocks of the Ethereum blockchain. The state is created or
updated as a result of the interaction between accounts. Operations performed between and on
the accounts represent state transitions. 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. Transaction fee is calculated and the sending address is resolved using the signature.
Furthermore, sender's account balance is checked and subtracted accordingly and nonce
is incremented. An error is returned if the account balance is not enough.
3. Provide enough ether (gas price) to cover the cost of the transaction. This is charged per
byte incrementally according to the size of the transaction.
4. In this step, the actual transfer of value occurs. The flow is from the sender's account to
receiver's account. The account is created automatically if the destination account
specified in the transaction does not exist yet. Moreover, if the destination account is a
contract, then the contract code is executed. This also depends on the amount of gas
available. If enough gas is available, then the contract code will be executed fully;
otherwise, it will run up to the point where it runs out of gas.
5. In cases of transaction failure due to insufficient account balance or gas, all state changes
are rolled back with the exception of fee payment, which is paid to the miners.
6. Finally, the remainder (if any) of the fee is sent back to the sender as change and fee is
paid to the miners accordingly. At this point, the function returns the resulting state.
BB Gang
Types of accounts
There are two types of accounts in Ethereum:
● Externally owned accounts: The first is externally owned accounts (EOAs) and the
other is contract accounts. EOAs are similar to accounts that are controlled by a private
key in bitcoin. Contract accounts are the accounts that have code associated with them
along with the private key.
● Contract accounts: An EOA has ether balance, is able to send transactions, and has no
associated code, whereas a Contract Account (CA) has ether balance, associated code,
and the ability to get triggered and execute code in response to a transaction or a
message.
It is worth noting that due to the Turing-completeness property of the Ethereum blockchain, the
code within contract accounts can be of any level of complexity. The code is executed by EVM
by each mining node on the Ethereum network. In addition, contract accounts are able to
maintain their own permanent state and can call other contracts.
It is envisaged that in the serenity release, the distinction between externally owned accounts and
contract accounts may be eliminated.
Block
As discussed earlier, blocks are the main building blocks of a blockchain. Ethereum blocks
consist of various components, which are described as follows:
The transaction list is simply a list of all transactions included in the block. In addition, the list of
headers of Uncles is also included in the block. The most important and complex part is the
block header, which is discussed here.
BB Gang
Block Header
Block headers are the most critical and detailed components of an Ethereum block. The header
contains valuable information, which is described in detail here:
● Parent hash: The Keccak 256-bit hash of the parent (previous) block's header.
● Ommers hash: The Keccak 256-bit hash of the list of Ommers (Uncles) blocks included
in the block.
● Beneficiary: Contains the 160-bit address of the recipient that will receive the mining
reward once the block is successfully mined.
● State root: The Keccak 256-bit hash of the root node of the state trie. It is calculated after
all transactions have been processed and finalized.
● Transactions root: The Keccak 256-bit hash of the root node of the transaction trie,
representing the list of transactions included in the block.
● Receipts root: The Keccak 256-bit hash of the root node of the transaction receipt trie,
composed of receipts of all transactions included in the block.
● Logs bloom: A bloom filter composed of the logger address and log topics from the log
entry of each transaction receipt in the block.
● Number: The total number of all previous blocks; the genesis block is block zero.
● Gas limit: The limit set on the gas consumption per block.
● Gas used: The total gas consumed by the transactions included in the block.
● Mixhash: A 256-bit hash that, combined with the nonce, proves that adequate
computational effort has been spent to create the block.
BB Gang
● Nonce: A 64-bit hash (number) that is used with the mixhash to prove that adequate
computational effort has been spent to create the block.
○ Gas limit must not be less than the gas used by the transaction.
○ The sender's account contains enough balance to cover the execution cost.
BB Gang
The transaction sub-state
● A transaction sub-state is created during the execution of the transaction and processed
immediately after execution completes.
BB Gang
Block finalization
Block finalization is the process run by miners to validate block contents and apply rewards. It
consists of four steps:
● Ommers validation
○ Validate Ommers (stale blocks, also called Uncles).
○ In mining, determine Ommers.
○ Check that the header of each Uncle is valid.
○ Ensure the Uncle’s relationship with the current block satisfies the maximum
depth of 6 blocks.
○ A block can contain a maximum of 2 Uncles.
● Transaction validation
○ Validate transactions.
○ In mining, determine transactions.
○ Confirm that the total gas used in the block equals the final gas consumption after
all transactions.
● Reward application
○ Apply rewards by updating the beneficiary's account balance.
○ Miners get rewards for stale blocks (1/32 of the block reward).
○ Uncles included in a block get 7/8 of the total block reward.
○ The current block reward is 5 Ether.
○ A block can have a maximum of 2 Uncles.
BB Gang
Ether
● Ether is minted by miners as a currency reward for the computational effort they spend in
order to secure the network by verifying and validating transactions and blocks.
● Ether is used within the Ethereum blockchain to pay for the execution of contracts on the
EVM.
● Ether is used to purchase gas as crypto fuel, which is required in order to perform
computation on the Ethereum blockchain.
● Fees are charged for each computation performed by the EVM on the blockchain. A
detailed fee schedule is shown in the upcoming section.
Messages
Messages, as defined in the Ethereum Yellow Paper, represent the data and value passed between
two accounts within the Ethereum network. A message is essentially a data packet that carries
both data and value (amount of Ether) from one account to another. Messages can be sent:
Contracts themselves can also generate messages to interact with other contracts. Importantly,
messages exist only during execution and are never stored on the blockchain.
BB Gang
Messages are similar to transactions, but there is a key difference:
Components of a message:
Messages are typically generated when contracts execute certain EVM instructions —
specifically the CALL or DELEGATECALL opcodes.
Calls
● A call does not broadcast anything to the blockchain; it is a local call to a contract
function.
● Runs locally on the node (similar to a local function call).
● Does not consume gas because it is read-only — acts as a dry run.
● Generally does not result in any state change.
BB Gang
Mining
● Mining is the process by which new currency (Ether) is added to the blockchain.
● It serves as an incentive for miners to validate and verify blocks of transactions.
● Mining helps secure the network by verifying computations.
Functions of a Miner
1. Listens for transactions broadcasted on the Ethereum network and determines which
transactions to process.
2. Determines stale blocks (called Uncles or Ommers) and includes them in the block.
3. Updates the account balance with the reward earned from successfully mining the
block.
4. Computes a valid state and finalizes the block, defining the result of all state transitions.
Mining Mechanism
BB Gang
Unit - 5
Hyperledger
Main Components
BB Gang
2. Hyperledger APIs, SDKs, and CLI
○ Provide interfaces to interact with blockchain services through:
■ Application Programming Interfaces (APIs)
■ Software Development Kits (SDKs)
■ Command Line Interfaces (CLI)
Event Stream
● A gRPC channel runs across all services, forming the event stream.
● It is used to send and receive events (either pre-defined or custom).
● Validating peers or chaincode can emit events.
● External applications can listen and respond to these events.
Hyperledger Requirements
Modular approach
BB Gang
Identity
Auditability
● Hyperledger must maintain an immutable audit trail of all identities, operations, and
changes.
Interoperability
Portability
● Hyperledger should work across various platforms and environments without requiring
code changes.
● Portability applies to the infrastructure, code, libraries, and APIs, enabling uniform
development across different implementations.
BB Gang