Unit5 - Subjective Questions
CSC203 • Practice Questions with Detailed Answers
Define Ethereum and explain its core architecture components.
Ethereum is a decentralized, open-source blockchain with smart contract functionality. Proposed by Vitalik Buterin in 2013, it enables developers to build and deploy decentralized applications (dApps).
Core Architecture Components:
- Ethereum Virtual Machine (EVM): A Turing-complete software that runs on the Ethereum network. It enables anyone to run any program, regardless of the programming language used, provided there is enough time and memory.
- Smart Contracts: Self-executing contracts with the terms of the agreement directly written into code.
- Ether (ETH): The native cryptocurrency used to pay for transaction fees and computational services on the network.
- Nodes: Computers participating in the network that maintain a copy of the blockchain and verify transactions.
What are Smart Contracts? How do they function within the Ethereum ecosystem?
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 an intermediary's involvement or time loss.
Functionality in Ethereum:
- Deployment: A developer writes code (e.g., in Solidity) and compiles it into bytecode. This bytecode is deployed to the blockchain via a transaction.
- Addressing: Upon deployment, the contract is assigned a unique address.
- Execution: Users interact with the contract by sending transactions to its address. The EVM executes the specific function triggered by the transaction.
- Immutability: Once deployed, the code cannot be changed (though data state can change), ensuring trust.
Explain the concept of 'Gas' in Ethereum. Why is it necessary?
Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network. Every instruction executed by the EVM requires a specific amount of gas.
Why is it necessary?
- Resource Allocation: It prevents users from spamming the network with infinite loops or computationally intensive tasks without paying for the resources consumed.
- Incentivization: The fees paid in Gas (converted to Ether) reward miners/validators for processing transactions and securing the network.
Calculation:
The transaction fee is calculated as:
Discuss the Turing Completeness of Ethereum's smart contract language. What implication does this have on the Halting Problem?
Turing Completeness:
A programming language is Turing complete if it can solve any computational problem, given enough time and memory. Ethereum's EVM is Turing complete because it supports loops and conditional jumps, allowing for complex logic.
The Halting Problem:
Alan Turing proved that it is impossible to determine universally whether a program will run forever or eventually stop (halt).
Implications for Ethereum:
Since the EVM is Turing complete, a smart contract could theoretically enter an infinite loop, freezing a node. Ethereum solves this using the Gas mechanism. Each transaction has a Gas Limit. If a computation takes too long (entering an infinite loop), it runs out of gas, the execution halts, state changes are reverted, and the fees are forfeited to the miner.
Compare and distinguish between Externally Owned Accounts (EOA) and Contract Accounts in Ethereum.
Ethereum has two types of accounts:
1. Externally Owned Accounts (EOA):
- Control: Controlled by a private key (human users).e.g., MetaMask wallets.
- Code: Has no associated code.
- Action: Can initiate transactions (send Ether or trigger contract code).
- Cost: Creating an EOA is free.
2. Contract Accounts:
- Control: Controlled by their contract code.
- Code: Associated with smart contract code stored on the blockchain.
- Action: Cannot initiate transactions on their own; they only fire in response to receiving a transaction.
- Cost: Creating a contract account costs gas because it uses network storage.
Describe the verification challenges associated with smart contracts.
Because smart contracts handle value and are immutable, verification is critical but challenging:
- Immutability: Once deployed, bugs cannot be patched easily. A flaw in the code remains until a new contract is deployed and users migrate.
- Complexity: Turing completeness allows complex logic, increasing the surface area for bugs like Reentrancy attacks or Integer Overflow/Underflow.
- Formal Verification: Mathematically proving the correctness of code is difficult and expensive for complex contracts.
- External Dependencies: Reliance on Oracles (external data feeds) introduces a point of failure that is hard to verify within the blockchain's isolated environment.
Analyze the potential and challenges of using smart contracts to enforce legal contracts.
Potential:
- Automation: Automatic execution of terms (e.g., releasing escrow funds) reduces administrative overhead.
- Trust: Code acts as a neutral arbiter, reducing reliance on intermediaries like lawyers or banks.
- Transparency: All parties can audit the contract logic.
Challenges:
- Ambiguity: Legal contracts often use subjective terms like "reasonable effort" or "good faith," which cannot be easily translated into binary code.
- Jurisdiction: Smart contracts exist on a global decentralized network, making it difficult to determine which country's laws apply.
- Enforceability: Courts may not yet recognize smart contract code as legally binding evidence in all jurisdictions.
Differentiate between Bitcoin Scripting and Ethereum Smart Contracts.
| Feature | Bitcoin Scripting | Ethereum Smart Contracts |
|---|---|---|
| Turing Completeness | Not Turing complete (no loops). | Turing complete (supports loops/complex logic). |
| State | Stateless (UTXO model). | Stateful (Account model). Contracts remember data. |
| Complexity | Limited to basic transactions and multi-sig. | Can run complex dApps, DAOs, and Tokens. |
| Language | Script (Stack-based, Forth-like). | Solidity, Vyper (High-level languages). |
| Purpose | Primarily digital currency transfer. | Programmable platform for decentralized applications. |
Explain the concept of UTXO vs. Account-Based models in the context of Bitcoin and Ethereum.
UTXO Model (Bitcoin):
- Stands for Unspent Transaction Output.
- There are no "accounts" or "balances" stored on the ledger. Instead, the user's balance is the sum of all unspent outputs controllable by their private key.
- Spending requires consuming specific previous outputs and creating new ones.
Account-Based Model (Ethereum):
- Works similar to a bank account.
- The global state stores a list of accounts with their current balances and storage (state).
- A transaction is a request to update the state (e.g., subtract from Account A, add to Account B).
- Advantage: Easier to implement complex smart contracts as the code can simply reference the persistent state of an account.
What is Solidity? Describe the basic structure of a Solidity smart contract.
Solidity is an object-oriented, high-level language for implementing smart contracts, influenced by C++, Python, and JavaScript. It is statically typed and designed to run on the EVM.
Basic Structure:
- Version Pragma: Defines the compiler version (e.g.,
pragma solidity ^0.8.0;). - Contract Definition: The keyword
contractis used (similar toclassin OOP). - State Variables: Variables whose values are permanently stored in contract storage.
- Functions: Executable units of code. Can be
public,private,view, orpure. - Events: Used to log data on the blockchain for external consumers (like JavaScript frontends).
Write a simple Solidity smart contract that stores and retrieves a number. Explain the code.
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private storedData; // State variable
// Function to store value
function set(uint256 x) public {
storedData = x;
}
// Function to retrieve value
function get() public view returns (uint256) {
return storedData;
}
}
Explanation:
uint256 private storedData;: Declares a state variable that is persistent on the blockchain.privatemeans it cannot be read directly by other contracts, though it is visible on the chain.function set: A public function that changes the state. Executing this requires a transaction and gas.function get: Aviewfunction, meaning it only reads data and does not modify the state. Calling this externally is free (no gas).
Explain the role of 'Modifiers' in Solidity with an example.
Modifiers are code that can be run before and/or after a function call. They are commonly used to restrict access to certain functions, validate inputs, or check states before execution.
Example: onlyOwner
solidity
address public owner;
modifier onlyOwner {
require(msg.sender == owner, "Not authorized");
_; // Continue execution of the function body
}
function changeSettings() public onlyOwner {
// critical code
}
In this example, changeSettings can only be executed if the caller (msg.sender) is the owner. If not, the require statement fails, and the transaction reverts.
What are Data Types in Solidity? Explain Mappings and Structs.
Solidity is statically typed. Common types include uint (unsigned integer), int, address, bool, and string.
1. Structs:
Used to define custom types that group several variables.
solidity
struct User {
string name;
uint age;
}
2. Mappings:
Key-value stores, essentially hash tables. They are virtually initialized such that every possible key exists and maps to a value of all zeros.
Syntax: mapping(_KeyType => _ValueType)
Example: mapping(address => uint) public balances; allows looking up the balance associated with an address.
How does JavaScript interact with Ethereum smart contracts? Explain the role of libraries like Web3.js.
JavaScript interacts with Ethereum using libraries like Web3.js or Ethers.js. These libraries act as a bridge between a standard web frontend and the Ethereum blockchain nodes via JSON-RPC calls.
Key Roles:
- Connection: Connects the frontend to a provider (e.g., MetaMask or Infura).
- Contract Instantiation: Creates JavaScript objects that represent deployed smart contracts using the ABI (Application Binary Interface) and the contract address.
- Transaction Signing: Allows users to sign transactions using their private keys (managed by the wallet) to call state-changing functions in the smart contract.
- Event Listening: Subscribes to contract events to update the UI in real-time.
What is the Application Binary Interface (ABI) in the context of Ethereum and Solidity?
The ABI (Application Binary Interface) is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain (using JS) and for contract-to-contract interaction.
- Purpose: Since the EVM executes bytecode, it doesn't understand high-level function names or variable types. The ABI defines how data structures and functions are encoded/decoded into formats the EVM understands.
- Representation: It is typically represented as a JSON array of objects describing the contract's functions, inputs, outputs, and events.
- Usage: When using Web3.js, the ABI is required so the library knows how to format the call to the smart contract.
Explain the significance of Events and Logs in Solidity.
Events allow smart contracts to communicate with the outside world (dApps/frontends). When an event is emitted, the arguments are stored in the transaction's Logs.
Significance:
- Lower Cost: Storing data in logs is significantly cheaper (in Gas) than storing it in contract state variables.
- Frontend Updates: JavaScript libraries can listen for these events to update the user interface automatically when a transaction is confirmed.
- Indexing: Parameters can be
indexed, allowing external applications to search and filter logs efficiently (e.g., finding all transfers from a specific address).
Example: event Transfer(address indexed from, address indexed to, uint value);
Describe the security vulnerability known as 'Reentrancy' in smart contracts.
Reentrancy is a vulnerability where a function makes an external call to an untrusted contract, and that untrusted contract calls back into the original function before the first execution is finished.
Scenario:
- Contract A holds user funds and has a
withdraw()function. - The
withdrawfunction sends Ether to the user before updating the user's balance to zero. - The attacker (Contract B) receives the Ether, triggering its
fallbackfunction. - The
fallbackfunction callswithdraw()on Contract A again. - Since the balance in Contract A hasn't been set to zero yet, the second withdrawal succeeds.
Prevention: Adhere to the Checks-Effects-Interactions pattern (update state before sending Ether) or use Reentrancy Guards.
Discuss the different visibility specifiers for functions in Solidity.
Solidity provides four types of visibility for functions:
- public: Can be called internally (from within the contract) and externally (by users or other contracts). The compiler automatically creates a getter function for public state variables.
- private: Can only be accessed from within the contract where they are defined. Not visible in derived contracts (inheritance).
- internal: Can be accessed from within the contract and by contracts inheriting from it. Similar to
protectedin other languages. - external: Can only be called from other contracts and via transactions. Cannot be called internally (except using
this.f()). External functions are sometimes more gas-efficient for large array arguments.
Explain the 'Ricardian Contract' concept and how it relates to Ethereum.
A Ricardian Contract is a method of recording a document as a contract at law in a way that is securely linked to other systems, such as an accounting system, offering a bridge between legal text and digital execution.
Relation to Ethereum:
- While a standard Smart Contract is purely code (machine-readable), a Ricardian contract includes both the human-readable legal prose and the machine-readable code.
- It cryptographically signs the legal document and links it to the smart contract code.
- This attempts to solve the "Code vs. Law" dispute by defining the intent of the code in legal terms, making it easier to resolve disputes in real-world courts if the code behaves unexpectedly.
Derive the cost execution model for a Smart Contract transaction involving memory expansion.
In Ethereum, the cost of execution is not just computational steps but also memory usage. The EVM charges for memory expansion to prevent abuse.
Cost Components:
- Base Fee: 21,000 gas for a standard transaction.
- Opcode Costs: Each operation (ADD, MUL, SSTORE) has a fixed cost.
- Memory Cost: The cost grows quadratically with size.
Let be the number of 32-byte words of memory used. The memory cost function is defined roughly as:
This quadratic term means that small amounts of memory are cheap, but allocating huge arrays becomes prohibitively expensive, protecting nodes from Running Out of Memory (OOM) attacks.