0% found this document useful (0 votes)
37 views18 pages

BT Module 3

Ethereum is a blockchain platform that enables the creation of decentralized applications (DApps) and extends blockchain's utility beyond cryptocurrencies. It features Turing-complete smart contracts, the Ethereum Virtual Machine (EVM), and uses Ether (ETH) as its cryptocurrency, with a focus on simplicity and freedom of development. Ethereum's architecture includes complex data structures like Merkle Patricia Tries for state management, and it employs a gas system to regulate transaction costs and prevent network abuse.

Uploaded by

akash.2211005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views18 pages

BT Module 3

Ethereum is a blockchain platform that enables the creation of decentralized applications (DApps) and extends blockchain's utility beyond cryptocurrencies. It features Turing-complete smart contracts, the Ethereum Virtual Machine (EVM), and uses Ether (ETH) as its cryptocurrency, with a focus on simplicity and freedom of development. Ethereum's architecture includes complex data structures like Merkle Patricia Tries for state management, and it employs a gas system to regulate transaction costs and prevent network abuse.

Uploaded by

akash.2211005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

ETHEREUM

Ethereum is a groundbreaking blockchain platform designed for building decentralized applications


(DApps). It extends blockchain's utility beyond cryptocurrencies, enabling the creation of diverse
applications across industries.

Features and Evolution


1. From Bitcoin to Ethereum:
o Bitcoin introduced blockchain as a decentralized peer-to-peer network for cryptocurrency.
o Ethereum expanded blockchain's potential by enabling transactions of assets like shares, land,
and digital content.
o Unlike Bitcoin's focus on cryptocurrency, Ethereum provides an abstract foundation layer for
diverse applications.
2. Ethereum's Innovations:
o Turing-Complete Smart Contracts: Programmable contracts executed automatically when
predefined conditions are met.
o Ethereum Virtual Machine (EVM): A decentralized computing environment running smart
contracts on all Ethereum nodes.
o DApps: Decentralized applications that run on the Ethereum blockchain without downtime,
fraud, or central control.
3. Advantages Over Bitcoin:
o Supports complex programming for various use cases, unlike Bitcoin's limited scripting
capabilities.
o Tracks states persistently, unlike Bitcoin’s stateless transaction model.
o Developers can create custom state transition functions and transaction formats.
4. Ethereum's Cryptocurrency:
o Ether (ETH): A tradeable cryptocurrency generated by miners, used to sustain the network.
o Gas Fees: Paid for executing smart contracts and transactions, ensuring network
sustainability and preventing spam.

Ethereum's Design Philosophy


1. Simplicity: Keeps implementation straightforward for easier DApp development.
2. Freedom of Development: Encourages innovation without discriminating against specific use cases.
3. Generalization: Does not provide predefined features, instead offers a Turing-complete language for
developers to build custom functionalities.
Use Cases
 Ethereum has applications in supply chain, healthcare, e-commerce, and government sectors.
 Example: Proof of Existence use cases for verifying document timestamps.
ETHEREUM BLOCKCHAIN
Ethereum Blockchain Data Structure
1. Differences from Bitcoin: Ethereum's block header is more complex, featuring additional Merkle
roots.
o stateRoot: Tracks the global state.
o transactionsRoot: Ensures transaction integrity (like Bitcoin).
o receiptsRoot: Tracks receipts for each transaction.
2. Block Components:
o Header Fields: Metadata (e.g., parentHash, timestamp), data references (e.g.,
transactionsRoot), transaction execution info (e.g., stateRoot), and consensus-related data
(e.g., difficulty, nonce).
o Other Components: Transactions list, uncles list, and optional extraData.

ETHEREUM ACCOUNTS
1. Types:
o Externally Owned Accounts (EOAs): Controlled by private keys, used for transactions.
o Contract Accounts: Contain code (smart contracts), activated by EOAs or other contracts.
2. Differences from Bitcoin:
o Ethereum is stateful, while Bitcoin uses the UTXO model.
o Accounts enable more complex interactions and business logic.
3. Advantages:
o UTXO Model: Offers better privacy and scalability for parallel execution.
o Account Model: Simplifies coding, reduces space usage, and facilitates lightweight client
interactions.

ACCOUNT STATE
Components:
o Balance: Ether in Wei (1 ETH = 1018 Wei).
o CodeHash: Hash of contract code (EOAs have a hash of an empty string).
o StorageRoot: Root hash of the Merkle tree representing account storage.
o Nonce: Tracks transaction count (EOAs) or contracts created (Contract Accounts).
TRIE USAGE
The “state” trie that is responsible to keep track of the state changes of Ethereum blockchain. The state trie is
a Merkle Patricia Trie (MPT) that tracks all state changes in Ethereum. The state is stored as Recursive
Length Prefix (RLP)-encoded data in the MPT, not directly in the blockchain's blocks. Each block in
Ethereum contains a stateRoot field in its header. The stateRoot is the Merkle root of the state trie at the time
the block was created, representing the blockchain's global state at that moment.
1. Types of Tries:
o State Trie: Tracks the global state after block execution.
o Transaction Trie: Maps transactions in a block by their order.
o Receipt Trie: Stores receipts for each transaction.

2. Receipt Structure:
o medstate: State trie root after transaction execution.
o gas_used: Gas consumed by the transaction.
o logs: Logs generated by the transaction.
o logBloom: A Bloom filter summarizing logs for efficient lookup.

MERKLE PATRICIA TREES (MPTS)


MPT combines features of Merkle Trees and Patricia Tries, making it a powerful data structure for
Ethereum:
1. Merkle Tree:
o Facilitates cryptographic integrity.
o Leaf nodes store the hash of data blocks.
o Non-leaf nodes store the hash of their child nodes.
o Enables efficient proof of membership with a minimal subset of data (e.g., Merkle branch).
2. Patricia Trie:
o A variant of a Radix tree optimized for efficient key-value lookups, inserts, and deletions.
o Keys are encoded in paths within the tree, guiding traversal to locate the associated value.
Merkle Patricia Trees

Role in Ethereum:
 The World State—a mapping of accounts to states—is stored in the MPT.
 Each key-value pair (e.g., account address → state data) is encoded into this trie.
 Ethereum uses a hexadecimal trie, where each node can have up to 16 children (0-9 and A-F), and
paths are defined by hex characters (nibbles).

Key Features:
1. Deterministic:
o The same key-value bindings always produce the same tree structure and root hash.
2. Efficient:
o Insert, delete, and lookup operations have O(log(n)) complexity.
3. Tamper-Proof:
o Hashes ensure cryptographic integrity; the root hash acts as a "fingerprint" of the entire
structure.
4. Minimal Modifications:
o Changes to the tree (e.g., inserting/updating data) only affect the minimum number of nodes
necessary, recalculating the root hash efficiently.

RECURSIVE LENGTH PREFIX (RLP) ENCODING


RLP is Ethereum's serialization format, optimized for:
1. Space Efficiency:
o Minimalistic, reducing overhead compared to JSON or XML.
2. Consistency:
o Ensures byte-perfect results across encodings/decodings.
3. Flexibility:
o Supports nested arrays of raw bytes.
Features:
1. Purpose:
o Encodes complex data structures (e.g., blocks, transactions, account states) into a compact
format for storage or transmission.
2. Data Agnostic:
o Does not define explicit data types; encodes raw byte arrays only.
3. Serialization Format:
o Ideal for nested arrays, though key-value pairs require additional encoding (e.g., as sorted
lists of key-value pairs).

Use Cases in Ethereum:


1. Transaction Serialization:
o Transactions are serialized with RLP before being transmitted or saved.
2. State Storage:
o Account state data in the MPT is RLP-encoded for efficient storage and reconstruction.
Example of Key/Value Mapping:
 Key-value pairs can be represented as [[k1, v1], [k2, v2], ...] for RLP serialization.
 Alternatively, Patricia tree encoding (which uses RLP internally) is used for structured storage.

ETHEREUM TRANSACTIONS AND MESSAGES


ETHEREUM TRANSACTIONS
An Ethereum transaction is a signed data package sent by an Externally Owned Account (EOA). It
instructs the blockchain to perform actions such as transferring Ether, interacting with contracts, or creating
contracts.
Fields in a Transaction:
1. nonce:
o A counter representing the number of transactions sent by the sender's account.
o Ensures transactions are processed in order and prevents replay attacks.
2. gasPrice:
o The price (in Wei) per unit of gas the sender is willing to pay for the transaction.
3. gasLimit:
o The maximum amount of gas allocated for the transaction.
o Limits the computational resources the transaction can consume.
4. To:
o The recipient's 160-bit address.
o Left empty if the transaction is creating a contract.
5. Value:
o The amount of Ether (in Wei) transferred to the recipient.
6. V, r, s:
o Components of the ECDSA signature, authenticating the transaction and identifying the
sender.
7. init (only for contract creation):
o Contains the EVM code for initializing a new contract account.
o Used once during contract creation and discarded afterward.
8. Data:
o An optional field.
o Holds input data for contract calls or arbitrary data for EOAs.

Execution Flow:
o The transaction is validated by miners or Ethereum nodes.
o Transactions are RLP-encoded for consistency and minimal storage.
o Each node executes the transaction if it is valid, consuming gas for each computational step.
o Unused gas is refunded, and additional refunds may occur if storage is freed during execution (via
SSTORE operations).

ETHEREUM MESSAGES
Messages are like transactions but are initiated by Contract Accounts, not EOAs. They represent internal
communication between contracts and do not exist outside the Ethereum Virtual Machine (EVM).
Fields in a Message:
1. Sender:
o Implicitly included, representing the originating contract.
2. Recipient:
o The address of the recipient contract.
3. Value:
o The amount of Wei sent along with the message.
4. Data:
o Optional input data provided for the recipient contract.
5. gasLimit (or startGas):
o Limits the maximum gas that can be used by the message-triggered code execution.

Characteristics:
 Messages are internal transactions, triggered by contracts using opcodes like CALL or
DELEGATECALL.
 They are not serialized or transmitted like transactions.

Transaction Lifecycle and Substate


When a transaction is injected into the blockchain:
1. It is executed by each node if valid.
2. Substate tracks execution flow to manage:
o Self-destruct set:
 Accounts flagged for deletion post-transaction.
o Log series:
 Indexed checkpoints to monitor contract calls.
o Refund balance:
 Refunds accrued by deleting storage during execution.
3. If execution stops (e.g., out of gas):
o The entire transaction is reverted, restoring the original state.
4. After successful execution:
o The state transition is recorded, modifying the global state.
Messages vs. Transactions

Aspect Transactions Messages


Initiator EOAs Contract Accounts
Serialization Yes (RLP-encoded) No
Purpose External communication Internal communication
Fields nonce, gasPrice, etc. sender, recipient, etc.

ETHEREUM STATE TRANSITION FUNCTION


The state transition function in Ethereum describes how the global state S evolves to a new state S′ after
processing a transaction Tx. This function ensures that transactions are validated, executed, and their effects
are recorded in a deterministic manner.
Formal Representation
APPLY (S, Tx) → S′
 S: Current state of the Ethereum network.
 Tx: Transaction applied to SSS.
 S′: Updated state after applying Tx.

Steps in the State Transition Function


1. Transaction Validation:
o Ensure Tx is well-formed:
 All required fields are present and correctly structured.
o Verify the signature:
 Confirm that the transaction is signed by the sender.
o Match the nonce:
 The nonce in Tx must equal the sender account's nonce.
o Error Handling:
 If any validation step fails, the transaction is rejected.
2. Transaction Fee Calculation and Account Settlement:
o Compute the transaction fee: Fee = gasLimit × gasPrice
o Determine the sender’s address from the transaction signature.
o Deduct the fee from the sender's balance.
o Increment the sender's nonce.
o Error Handling:
 If the sender’s balance is insufficient, the transaction is rejected.
3. Initialize Gas:
o Set GAS = gasLimit
o Deduct gas for the transaction size (bytes) as an initial fee.
4. Value Transfer:
o Transfer the transaction value from the sender to the recipient:
 This value could represent Ether, ERC20 tokens, or other assets.
o If the recipient account does not exist, create it.
5. Contract Execution (if applicable):
o If the recipient is a contract account:
 Execute the contract code on the EVM.
 Execution continues until:
 Completion of the code, or
 The transaction runs out of gas.
o Deterministic Execution:
 Every node independently executes the contract as part of block validation.
 The contract's output is recorded on the blockchain.

6. Failure Handling:
o If the transaction fails due to:
 Insufficient sender funds, or
 Running out of gas during contract execution:
 Revert all state changes (excluding fee payment) using the MPT structure.
 Add the paid transaction fee to the miner's account.
7. Fee Refund:
o Refund the sender for unused gas.
o Transfer the gas fee already consumed to the miner.

GAS AND TRANSACTION COST


Ethereum transactions use gas as the unit of computation. This system ensures that computational resources
are properly valued and prevents misuse of the network.

Understanding Gas
1. GasLimit and GasPrice:
o GasLimit: The maximum amount of gas a user is willing to spend on a transaction.
o GasPrice: The price per unit of gas (set by the user) in Ether (usually in Wei).
2. Purpose of Gas:
o Compensates miners for their computational resources and effort.
o Prevents abuse such as infinite loops or excessive data storage, which could result in network
attacks.

Gas Costs for Common Operations


 Simple Operations:
o Adding two numbers (ADD): ~3 gas.
o Multiplying two numbers (MUL): ~5 gas.
o Calculating a hash (SHA3): ~30 gas (compute-intensive).
 Transaction Data:
o 68 gas per byte of nonzero transaction data.
o 20,000 gas to store a 256-bit word in a contract (storage-intensive).

Calculating Transaction Costs


 Total Cost:
Total Cost (Ether) = GasUsed × GasPrice
o GasUsed: Actual gas consumed during transaction execution.
o GasPrice: Specified by the sender.
 Refunds for Unused Gas:
o Unused gas is refunded to the sender in Ether.
o Miners only collect fees for gas actually used.
 Exceeding GasLimit:
o If gas consumption exceeds the GasLimit:
 The transaction reverts, except for the fee already allocated to the miner.

Key Transaction Steps


1. Initial Deduction:
o Ether worth GasLimit × GasPrice is deducted from the sender's account.
o Ensures the sender has enough funds to complete the transaction.
2. Execution:
o Each operation during execution consumes a predefined gas amount (e.g., addition, storage,
hash computation).
o Gas for each operation is deducted from the transaction’s remaining gas.
3. Post-Execution:
o Successful Execution:
 Remaining gas (gas_rem) is refunded.
 Miner collects (GasLimit − gas_rem) × GasPrice.
o Failed Execution:
 All operations are reverted.
 Miner collects the full GasLimit × GasPrice

Typically, 21,000 gas is charged for any transaction as a "base fee" to cover the cost of an elliptic curve
operation to compute the sender address from the signature, and also for the disk space of storing the
transaction.

Gas and Ether Decoupling


 Gas measures computation, while Ether’s price fluctuates due to market dynamics.
 Decoupling allows a stable computation costs (gas) and market-driven Ether valuation.
ETHEREUM SMART CONTRACTS
Ethereum's defining feature is its ability to host smart contracts—self-executing pieces of code stored on
the blockchain. Unlike Bitcoin, which is solely a cryptocurrency, Ethereum supports programmable logic,
making it a versatile platform.

What Are Smart Contracts?


 Smart contracts are programs deployed and executed on the Ethereum blockchain.
 They reside in Contract Accounts (CA) and:
o Have their own address and balance.
o Can send and receive messages and transactions.
o Are activated when they receive a transaction.
o Can be terminated under specified conditions.

Characteristics
 Code Language:
o Written in high-level languages like Solidity, Serpent, and LLL.
o Compiled into Ethereum Virtual Machine (EVM) bytecode for execution.
 Execution and Storage Costs:
o Smart contracts incur execution and storage fees.
o Optimized coding practices are necessary to minimize costs.

How They Work


1. Deployment:
o Smart contracts are deployed via a special contract creation transaction.
o Once deployed, their functions are accessible on the blockchain.
2. Interactivity:
o Users interact with smart contracts by sending transactions to their address.
o Contracts process these transactions according to their encoded logic.
3. Security:
o Contract functions can include security mechanisms to prevent unauthorized access.

Example: Voting Application


Imagine a voting system implemented as a smart contract:
1. The contract resides at a specific address within a block.
2. Voters send transactions to this address (cast votes).
3. The smart contract:
o Updates the vote count with each transaction.
o Publishes results (Ethereum state change) and self-destructs after the voting period ends.
CONTRACT CREATION PROCESS
When a smart contract is created, it undergoes a specific initialization process:
1. Account Initialization:
o Nonce: Set to 0.
o Account Balance: Initialized with Ether transferred by the sender, deducted from the sender's
account.
o StorageRoot: Empty initially.
o CodeHash: Set to the Keccak-256 hash of an empty string.
2. Execution of Init Code:
o The init code is sent with the contract creation transaction.
o Init code execution can:
 Modify the contract’s storage.
 Create additional accounts.
 Trigger further message calls.

ETHEREUM VIRTUAL MACHINE (EVM) AND CODE EXECUTION


The Ethereum Virtual Machine (EVM) is the heart of Ethereum's blockchain functionality. It is a Turing-
complete execution engine that facilitates the deployment and execution of smart contracts.

Key Features of EVM


1. Turing-Complete:
o Capable of executing operations of any computational complexity.
o Allows developers to create custom logic using high-level languages like Solidity.
2. Deterministic:
o Execution with the same inputs will always yield the same outputs, ensuring consistency and
consensus.
3. Space Efficiency:
o Compact design minimizes storage requirements in the decentralized Ethereum network.
4. Security and Gas Model:
o Gas fees prevent abuse by making attacks costly.
o Operations require gas, ensuring that resources are used judiciously.
5. Native Operations:
o Optimized for cryptographic operations, transaction processing, and state interactions.
o Uses a 256-bit word length for cryptographic hashes and arithmetic.

EVM Execution and Role


 EVM executes all transactions and smart contracts on the Ethereum network.
 It serves as a runtime environment (RTE) for smart contracts, ensuring secure and deterministic
execution.
 Changes in Ethereum’s global state occur only after successful execution of instructions in the EVM.

Memory Management in EVM


The EVM uses three types of memory during code execution:
1. Storage (Persistent)
o Used for state variables that define a contract's persistent state.
o Expensive to read/write.
o Can only be accessed and modified by the contract that owns it.
o Common instructions:
 SSTORE: Stores a value at a specified index.
 SLOAD: Loads a value from storage.
2. Memory (Volatile)
o Temporary and similar to RAM in traditional computing.
o Used during transaction execution and wiped after execution.
o Can only be used within contract methods.
o Common instructions:
 MSTORE: Stores a value in memory.
 MLOAD: Loads a value from memory.
3. Stack
o EVM is stack-based, following a Last-In-First-Out (LIFO) model.
o Used for computation, storing local variables, and passing function parameters.
o Supports a maximum of 1024 elements.
o Most operations occur on the top of the stack.
o Fast and nearly cost-free.
EVM Execution State
When executing transactions or smart contracts, the EVM’s computational state is represented by the tuple:
[block_state, transaction, message, code, memory, stack, pc, gas]
 block_state: Represents the global state (persistent storage).
 transaction: Contains details of the current transaction.
 message: Refers to the communication between accounts.
 code: The smart contract’s bytecode.
 memory: Volatile memory used during execution.
 stack: Stack for computation.
 pc: Program counter (points to the current instruction).
 gas: Tracks the remaining gas for execution.

ETHEREUM ECOSYSTEM
The Ethereum ecosystem is a comprehensive stack of technologies and tools that enable the creation and
execution of decentralized applications (DApps). While Ethereum’s core features make it a robust
blockchain platform, it also comes with inherent limitations and a suite of supporting components to address
these challenges.

Limitations of Ethereum
1. Slow Execution:
o The Ethereum Virtual Machine (EVM) is not optimized for large-scale computations.
2. High Costs:
o Computation and storage on the blockchain are expensive.
o Developers often rely on off-chain computation and Swarm for decentralized storage.
3. Scalability:
o Current infrastructure struggles with scaling.
o Solutions like Layer 2 protocols and sidechains can help but must align with specific use
cases.
4. Private Blockchains:
o Many businesses prefer private Ethereum-based blockchains for tailored solutions and data
privacy.

ETHEREUM TECH STACK


Swarm
 A decentralized storage platform for static files and a distribution service.
 Key Features:
o Stores Ethereum blockchain data, DApp code, and more.
o Ensures decentralization, redundancy, and fault tolerance.
o Resistant to DDoS attacks and designed for zero downtime.

Whisper
 A decentralized communication protocol for DApps.
 Functionality:
o Supports private and distributed messaging.
o Facilitates singlecast, multicast, and broadcast messaging between DApps.

DApps (Decentralized Applications)


 Consist of two main components:
1. Back-End:
 Runs on the Ethereum blockchain, typically implemented using smart contracts.
2. Front-End:
 User interfaces written in common web languages (HTML, CSS, JavaScript).
 Can be hosted on decentralized storage platforms like Swarm or IPFS.
 DApp Browsers:
o Allow users to interact with decentralized applications and browse DApp catalogs.
o Pull front-end components dynamically from decentralized storage.
DEVELOPMENT COMPONENTS
Ethereum’s development ecosystem includes a range of tools to simplify the creation and deployment of
DApps:
1. Web3.js:
o A JavaScript library for interacting with the Ethereum blockchain.
o Enables developers to query blockchain data, send transactions, and interact with smart
contracts.
2. Truffle:
o A development framework for Ethereum.
o Features:
 Simplifies compiling, deploying, and testing blockchain applications.
 Includes a suite of tools for debugging and managing smart contracts.
3. Mist Wallet:
o A UI-based wallet application for managing Ether and interacting with the Ethereum
blockchain.
o Features:
 Create and manage accounts.
 Deploy and interact with smart contracts.
 Send and receive Ether.
 View transaction history.
o Relies on Geth (Go Ethereum Client) to perform blockchain operations seamlessly.

You might also like