0% found this document useful (0 votes)
14 views27 pages

Blockchain Module3 Notes

This document outlines Module 3 of the M.Sc (IT) program focusing on Blockchain Technology, specifically Smart Contracts, Tokens, and Mining Ether. It covers the architecture of decentralized applications, the concept of asset-backed tokens, the mining process of Ether, and the significance of NFTs and digital collectibles. The module includes detailed explanations of various token standards and platforms, emphasizing the advantages of blockchain in creating trustless, automated systems.

Uploaded by

bihonay813
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)
14 views27 pages

Blockchain Module3 Notes

This document outlines Module 3 of the M.Sc (IT) program focusing on Blockchain Technology, specifically Smart Contracts, Tokens, and Mining Ether. It covers the architecture of decentralized applications, the concept of asset-backed tokens, the mining process of Ether, and the significance of NFTs and digital collectibles. The module includes detailed explanations of various token standards and platforms, emphasizing the advantages of blockchain in creating trustless, automated systems.

Uploaded by

bihonay813
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

M.

Sc (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

BLOCKCHAIN TECHNOLOGY
Module 3 — Smart Contracts & Tokens + Mining Ether
[Link] (IT) | Year II / Semester IV | SVKM's UPG College | 2024-25
Duration: 15 Lectures · Exam Weightage: ~25%

Part A — Smart Contracts & Tokens: EVM as Back End, Assets Backed by Anything,
Cryptocurrency as Measure of Time, Collectibles in Human Systems, Platforms for High-Value
Digital Collectibles, Tokens as Category of Smart Contract, Creating a Token, Deploying the
Contract, Playing with Contracts
Part B — Mining Ether: Why? Ether's Source, Defining Mining, Difficulty, Self-Regulation, Race
for Profit, How PoW Regulates Block Time, DAG and Nonce, Faster Blocks, Stale Blocks,
Difficulties, Ancestry of Blocks and Transactions, Ethereum and Bitcoin, Forking, Mining on
Windows/Geth, Executing EVM Commands via Geth Console, Launching Geth with Flags, Mining
on Testnet, GPU Mining Rigs, Pool Mining with Multiple GPUs

Page 1 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

PART A — SMART CONTRACTS & TOKENS

1. EVM as Back End


Traditional applications have a front end (UI), a back end (server/API), and a database. In
decentralised applications (DApps), the Ethereum Virtual Machine (EVM) replaces the traditional
back end and database — executing logic and persisting state trustlessly.

1.1 Traditional vs DApp Architecture

Traditional Application DApp (Decentralised Application)


Back end: Centralised server ([Link], Java, Back end: Smart contract on EVM
PHP)
Database: MySQL, MongoDB, PostgreSQL Database: Ethereum world state (Merkle
Patricia Trie)
Business logic: Code on private server Business logic: Solidity code on-chain (public)
Trust: Users trust the company/server Trust: Users trust auditable, immutable code
Authentication: Username + password / Authentication: Private key signature (wallet)
OAuth
Hosting: AWS, Google Cloud, Azure Hosting: Distributed across 10,000+
Ethereum nodes
Upgrades: Server admin can change Upgrades: Require governance / proxy
anything pattern
Single point of failure: Server goes down No single point of failure: Network is always
up

1.2 How Smart Contracts Function as a Back End


• Smart contracts ARE the back end. They contain all business logic — rules for token
transfers, ownership, conditions, state transitions.
• Persistent state: Contract storage persists between calls. Just like a database table that
never loses data.
• API replacement: The contract's ABI (Application Binary Interface) is the equivalent of a
REST API — it defines the functions that the front end can call.
• Front end interaction: DApp frontend (React/HTML) uses [Link] or [Link] to call
contract functions through the user's wallet (MetaMask).
• Call flow: User clicks 'Swap' on Uniswap → MetaMask signs transaction → [Link] sends
to network → Ethereum nodes execute swap() function in EVM → state updated → event
emitted → UI refreshes.

1.3 Advantages of EVM as Back End


• No downtime: As long as Ethereum network runs, the contract runs. No server
maintenance.
• Trustless: Anyone can read the contract code on Etherscan and verify it does what it
claims.

Page 2 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• Censorship resistant: No hosting company can take down your DApp's back end.
• Composability: Contracts can call other contracts — Lego-like composition. Uniswap +
Aave + MakerDAO can all interact atomically.
• Automated settlement: No manual processing. Funds move atomically with contract
execution.
💡 EXAM TIP: EVM as back end question: List 5 differences between traditional back end and
EVM. Include trust model, hosting, persistence, authentication, and upgradability.

2. Assets Backed by Anything


One of Ethereum's most powerful capabilities is the ability to create digital tokens backed by any
real-world or digital asset. This tokenisation enables unprecedented liquidity and programmability
for assets that were previously illiquid or difficult to divide.

2.1 The Concept of Asset Backing


📌 Tokenisation: The process of representing ownership rights to a real-world asset as a digital
token on a blockchain. The token IS the ownership claim — backed by the underlying asset.
• Traditional assets have friction: physical transfer, legal paperwork, geographic restrictions,
minimum investment sizes, slow settlement.
• Tokenised assets: Instant transfer, programmable conditions, fractional ownership, global
accessibility, 24/7 trading.

2.2 Categories of Assets that Can Back Tokens


Physical Assets:
• Real estate: Tokenise a $10M building → 10 million tokens at $1 each → anyone can own
a fraction. RealT, Lofty AI do this on Ethereum/Algorand.
• Precious metals: 1 PAXG (Paxos Gold) = 1 troy oz of London Good Delivery gold bar held
in Brinks vault.
• Art: Masterworks tokenises blue-chip art (Banksy, Basquiat) — fractions sold to retail
investors.
• Commodities: Oil barrels, carbon credits, agricultural commodities tokenised for easier
trading.
Financial Assets:
• Stocks/Equity: Tokenised shares of Apple, Tesla (Mirror Protocol, synthetix).
• Bonds/Fixed Income: US Treasury Bills tokenised (Ondo Finance, Mountain Protocol
USDM — yield-bearing stablecoin).
• Private equity: VC fund interests tokenised for secondary market liquidity.
Digital Assets:
• Cryptocurrency itself: Wrapped Bitcoin (WBTC) = Bitcoin locked in custody, ERC-20 token
issued on Ethereum 1:1.
• NFTs: Unique digital artwork, music, gaming items, virtual real estate.
• In-game items: Swords, characters, land in blockchain games (Axie Infinity, Decentraland).
Rights and Claims:
• Intellectual property: Music royalties ([Link] lets artists sell % of streaming revenue as
tokens).
• Carbon credits: Toucan Protocol tokenises carbon offsets — transparent, tradeable,
verifiable.
• Insurance policies: Parametric insurance payouts in tokens.

Page 3 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

2.3 Stablecoins — Fiat-Backed Tokens


📌 Stablecoin: A token designed to maintain a stable value, typically pegged 1:1 to a fiat currency
(USD) through various backing mechanisms.
• Fiat-collateralised: USDC (Circle), USDT (Tether) — each token backed by $1 in
bank/Treasuries. Centralised.
• Crypto-collateralised: DAI (MakerDAO) — over-collateralised by ETH/WBTC. Decentralised
but capital inefficient.
• Algorithmic: UST (Terra, collapsed 2022) — maintained peg through algorithm without real
backing. High risk.
• Yield-bearing: USDM (Mountain Protocol) — backed by US T-Bills, passes yield to holders.
RWA stablecoin.
💡 EXAM TIP: Asset backing question: Give 3 examples of physical assets, 3 financial assets,
and 3 digital assets that can be tokenised. Explain benefits: fractionalization, liquidity,
programmability.

3. Cryptocurrency Is a Measure of Time


This concept, highlighted by Saifedean Ammous and others, provides a unique philosophical lens
for understanding what cryptocurrency — particularly Bitcoin and Ethereum — represents: not just
money, but a measure of human time and energy.

3.1 The Economic Concept


• All goods and services ultimately cost human time. Money is a medium to store and
exchange the value of that time.
• Fiat money: Governments can print unlimited fiat, which dilutes the value of past work
(inflation). Your savings represent stored time — inflation steals that time.
• Bitcoin/ETH: Production requires real computational work (PoW) consuming real electricity
— a proxy for real human time and energy.
• Stock-to-Flow: Bitcoin's scarcity (21M cap, halvings) means its stock (existing supply) to
flow (annual production) ratio increases over time — like gold. High S/F = high value
storage.

3.2 Ethereum's Gas as Computation Time


• Gas = the price of computational time on the EVM. When you pay gas, you are renting
processing time from Ethereum validators.
• High demand → high gas prices → expensive computation time. Low demand → cheap.
• Smart contracts let you automate what previously required human time (lawyers,
accountants, brokers). ETH paid as gas replaces the payment to those humans.
• Result: Ethereum enables trustless automation of tasks that previously required trusted
intermediaries, effectively buying their time via gas payments to validators.
💡 EXAM TIP: This is a conceptual question. Explain: money = stored time, PoW requires real
energy (real time), gas pays for computation time, ETH replaces intermediary time.

Page 4 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

4. Function of Collectibles in Human Systems


Human civilisations have always assigned value to scarce, unique items beyond their intrinsic
utility — collectibles. Understanding this helps explain why NFTs (Non-Fungible Tokens) have real-
world value.

4.1 Why Humans Value Collectibles


• Scarcity creates value: Rarity makes something desirable. A 1952 Mickey Mantle baseball
card is valuable because few exist in mint condition.
• Provenance matters: A painting's history (who owned it, where it's been) affects value
enormously. A piece 'signed by Picasso' vs unsigned = 100x price difference.
• Social signalling: Luxury goods signal status. Owning a rare collectible signals wealth,
taste, and membership in an elite group.
• Community/identity: Sports card collectors share identity. NFT community membership
(Bored Apes) provides social network and status within crypto culture.
• Store of value: Art, rare coins, vintage cars have historically preserved value better than fiat
currencies.

4.2 Traditional Collectibles — Problems Blockchain Solves


• Authenticity: Is this really a Picasso? Requires expensive expert authentication. Blockchain:
ownership and provenance immutably recorded since creation.
• Provenance fraud: Physical certificates can be forged. NFT: creator's digital signature in
immutable transaction history.
• Illiquidity: Selling a painting requires galleries, auctions, months of time. NFT: instant global
marketplace (OpenSea, Blur).
• Indivisibility: Can't sell 10% of a painting. NFT: can fractionalise (ERC-1155, [Link]).
• Geographic restrictions: Art market concentrated in NYC, London, Basel. NFT: global, 24/7,
accessible to anyone with internet.

4.3 Digital Collectibles Before Blockchain — The Problem


• Pre-blockchain, digital items could be infinitely copied. A JPG is just bits — anyone can
copy it.
• Games like World of Warcraft had valuable in-game items, but the game company owned
everything — could delete your account, shut down servers, change item properties.
• No true digital ownership: You owned a licence to use the item, not the item itself.

5. Platforms for High-Value Digital Collectibles


Blockchain enables true digital ownership of unique items through NFTs. Several platforms have
emerged as primary marketplaces and creation tools.

5.1 NFT Standards


📌 ERC-721: Ethereum's Non-Fungible Token standard. Each token has a unique tokenId. No two
tokens are alike. Defined functions: ownerOf(tokenId), transferFrom(), safeTransferFrom(),
approve(), tokenURI().
📌 ERC-1155: Multi-token standard supporting both fungible and non-fungible tokens in one
contract. More efficient for games (one contract for all items). Supports batch transfers.
• ERC-721 use case: CryptoPunks, Bored Apes, Art Blocks — each token = unique artwork.
• ERC-1155 use case: Gaming (Gods Unchained cards — same card art but 100 copies),
event tickets (100 seats on same date but unique seat numbers).

Page 5 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

5.2 Major NFT Platforms

Platform Description & Key Features


OpenSea Largest NFT marketplace. Supports ETH,
Polygon, Solana. Royalties enforceable.
Founded 2017. $13.7B trading volume in
2022.
Blur Pro-trader focused. Zero marketplace fees.
Aggregate orders from OpenSea + Blur.
Launched 2022, quickly surpassed OpenSea
in volume.
Foundation Curated fine art NFTs. Artists invite-only.
Single 1/1 auctions. Higher-end collector
market.
Art Blocks Generative art platform. Algorithm-generated
art. Each mint = new unique piece.
CryptoPunks-era artists.
SuperRare High-end single-edition digital art. Artist-
curated. Strong community of serious
collectors.
Zora Creator-centric. Revenue sharing tools. Own
your NFT platform infrastructure.
Magic Eden Dominant Solana NFT marketplace.
Expanding to Bitcoin Ordinals and Ethereum.
Tensor Solana's pro-trading NFT platform. Real-time
order books, analytics tools.

5.3 High-Value NFT Collections


• CryptoPunks (Larva Labs, 2017): 10,000 24x24 pixel art punks. First major NFT project.
Floor price historically $100K+. Visa bought one for $150K. First NFTs with cultural
significance.
• Bored Ape Yacht Club (Yuga Labs, 2021): 10,000 ape PFPs. Members include Eminem,
Justin Bieber, Steph Curry. IP rights granted to holders. Floor: $80K+ at peak.
• Art Blocks: Fidenza #313 sold for $3.3M. Generative art by Tyler Hobbs.
• Beeple's 'Everydays' (2021): $69.3M sold at Christie's. First major auction house NFT sale.
Legitimised NFTs in mainstream art world.
• Jack Dorsey's first tweet: Sold as NFT for $2.9M in 2021. Later offered for resale, highest
bid $280 — illustrating NFT valuation volatility.
💡 EXAM TIP: NFT question: Explain ERC-721 vs ERC-1155 (3 differences), list 4 major
platforms with their specialisation, and name 3 high-value NFT collections with context.

Page 6 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

6. Tokens as a Category of Smart Contract


Tokens on Ethereum are not a separate blockchain feature — they are simply smart contracts that
implement a specific interface. Any ERC-20 token is just a Solidity contract with standardised
functions managing a mapping of addresses to balances.

6.1 Types of Tokens

Token Type Standard Characteristics


Fungible Token ERC-20 Interchangeable. 1 USDC =
any other 1 USDC. Used for
currencies, governance,
utility.
Non-Fungible Token ERC-721 Unique. Each has distinct
tokenId. Used for art,
collectibles, gaming items.
Multi-Token ERC-1155 Supports both fungible and
non-fungible in one contract.
Efficient for games.
Semi-Fungible ERC-1155 Fungible until redeemed, then
becomes unique (event
tickets — same type until
used).
Governance Token ERC-20 Voting rights in protocol
governance. UNI (Uniswap),
COMP (Compound), MKR
(Maker).
Utility Token ERC-20 Access to a platform's
features. LINK (Chainlink
oracle payment), FIL (Filecoin
storage).
Security Token ERC-20/ERC-1400 Represents securities.
Subject to financial regulation
(KYC/AML required).
Wrapped Token ERC-20 Token backed 1:1 by another
asset. WBTC (Bitcoin on
Ethereum), wETH (ETH as
ERC-20).

6.2 ERC-20 Standard — Complete Interface


ERC-20 defines 6 mandatory functions and 2 mandatory events that all fungible tokens must
implement:
Mandatory Functions:
• totalSupply() → uint256: Returns the total number of tokens in existence.
• balanceOf(address account) → uint256: Returns token balance of any address.
• transfer(address to, uint256 amount) → bool: Transfers tokens from [Link] to 'to'.
Emits Transfer event. Reverts if insufficient balance.

Page 7 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• allowance(address owner, address spender) → uint256: Returns how many tokens


'spender' can spend on 'owner's behalf.
• approve(address spender, uint256 amount) → bool: Sets allowance. Emits Approval event.
• transferFrom(address from, address to, uint256 amount) → bool: Transfer on behalf of
'from', using allowance. Used by DEXes, DeFi protocols.
Mandatory Events:
• event Transfer(address indexed from, address indexed to, uint256 value): Emitted by
transfer() and transferFrom(). Indexed = can be filtered efficiently.
• event Approval(address indexed owner, address indexed spender, uint256 value): Emitted
by approve().
Optional but Standard Extensions:
• name() → string: Token name (e.g., 'Uniswap').
• symbol() → string: Ticker symbol (e.g., 'UNI').
• decimals() → uint8: Decimal places (usually 18). 1 UNI stored as 1 × 10^18 in contract.
💡 EXAM TIP: ERC-20 functions are very commonly examined. Memorise all 6 functions + 2
events. Explain purpose of each. Know: approve+transferFrom enables DEX trading without
giving away private key.

7. Creating a Token
Creating an ERC-20 token on Ethereum is surprisingly straightforward with modern tooling. The
most common approach uses OpenZeppelin's battle-tested contract library.

7.1 Token Design Decisions


Supply Model:
• Fixed supply: Mint all tokens at deployment. E.g., 1 billion USDT minted at launch.
• Mintable: Owner can mint more later. E.g., governance can vote to mint more UNI.
• Burnable: Tokens can be permanently destroyed. Deflationary mechanism.
Access Control:
• Owner-controlled: [Link] — single address (owner) has admin rights.
• Role-based: [Link] — define MINTER_ROLE, BURNER_ROLE, etc. Assign to
multiple addresses.
• Multisig: Admin functions require M-of-N signatures (Gnosis Safe).
Tokenomics (Token Economics):
• Name and Symbol: Descriptive name and 3-4 letter ticker.
• Total supply: How many tokens? Bitcoin: 21M. Ethereum: uncapped (but EIP-1559
burning).
• Distribution: Team allocation, investors, community treasury, airdrop, liquidity mining.
• Vesting: Team tokens locked for 1-4 years, release linearly (prevent dump).

7.2 Minimal ERC-20 Token — Solidity Code


Using OpenZeppelin's ERC-20 base contract (most production tokens do this):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/[Link]";
import "@openzeppelin/contracts/access/[Link]";

Page 8 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

contract MyToken is ERC20, Ownable {


// Constructor: Called once at deployment
constructor(uint256 initialSupply) ERC20('MyToken', 'MTK')
Ownable([Link]) {
// Mint all initial tokens to the deployer
_mint([Link], initialSupply * 10 ** decimals());
}

// Only owner can mint new tokens


function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}

// Anyone can burn their own tokens


function burn(uint256 amount) public {
_burn([Link], amount);
}
}
What OpenZeppelin's ERC20 provides automatically: balanceOf mapping, totalSupply tracking,
transfer/transferFrom/approve/allowance implementations, Transfer and Approval events,
name/symbol/decimals.
What you add: Custom business logic (mint, burn, pause, governance, taxation, staking rewards).

7.3 Token with Advanced Features


Pausable: [Link] — owner can pause all transfers (emergency stop). Used in
regulated security tokens.
Snapshots: [Link] — record historical balances at specific block numbers. Used for
governance voting (snapshot balance at proposal creation, not current balance — prevents vote
manipulation).
Permit (EIP-2612): [Link] — approve via off-chain signature. Gasless approval. DeFi
protocols use this for better UX.
Votes (ERC20Votes): Tracks voting power with delegation. Used in on-chain governance
(OpenZeppelin Governor).
💡 EXAM TIP: Token creation: Know the 4 design decisions (supply model, access control,
tokenomics, features). Be able to explain the constructor, mint function, and what
OpenZeppelin provides vs what you implement.

8. Deploying the Contract


Deploying a smart contract means publishing its bytecode to the Ethereum blockchain, creating a
new contract account at a deterministic address. This is a one-time, irreversible action — once
deployed, the code cannot be changed (unless using a proxy pattern).

8.1 Deployment Tools


Remix IDE (Recommended for beginners):
• Browser-based Solidity IDE at [Link]. No installation required.
• Write, compile, deploy, and interact with contracts in one interface.
• Deploy to: JavaScript VM (in-memory, for testing), Injected Provider (MetaMask →
mainnet/testnet), or Hardhat node.
Hardhat (Production standard):

Page 9 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• [Link]-based development framework. Local Ethereum node for testing.


• Scripts: [Link] scripts automate deployment. Handles constructor args, gas estimation.
• Plugins: hardhat-ethers, hardhat-verify (auto-verify on Etherscan).
Foundry (Modern, Rust-based):
• forge script — deploy contracts with Solidity scripts directly.
• Extremely fast (Rust-based). Better testing capabilities than Hardhat.

8.2 Deployment Process — Step by Step


• Step 1 — Write contract in Solidity (.sol file).
• Step 2 — Compile: solc or Hardhat/Foundry compile. Produces: ABI (JSON interface) +
Bytecode (EVM machine code).
• Step 3 — Fund deployer wallet with ETH (testnet: get free ETH from Sepolia faucet).
• Step 4 — Create deployment transaction: to = null (empty address = contract creation),
data = bytecode + ABI-encoded constructor arguments.
• Step 5 — Sign and send transaction via MetaMask or deployment script.
• Step 6 — Transaction mined → EVM runs constructor code → Contract created at new
address.
• Step 7 — Contract address = Keccak256(RLP(deployer_address, nonce))[12:].
Deterministic — can be calculated before deployment.
• Step 8 — Verify source code on Etherscan: Upload Solidity source + compiler settings →
Etherscan compiles and confirms bytecode matches deployed code. Builds user trust.

8.3 Testnets for Development

Testnet Details
Sepolia Current recommended Ethereum testnet. PoS
consensus. Free test ETH from faucet. Use
for all development.
Goerli (deprecated) Older PoS testnet. Being phased out. Do not
use for new projects.
Holesky Large-scale testnet for staking/validator
testing. 1.6B initial supply.
Hardhat Network Local in-memory blockchain. Instant mining.
No real ETH needed. Best for unit tests.
Anvil (Foundry) Local testnet by Foundry. Can fork mainnet
state for integration testing.

8.4 Gas Cost of Deployment


• Contract deployment costs: 32,000 gas base + 200 gas per non-zero byte of bytecode + 4
gas per zero byte.
• Simple ERC-20 token: ~1-2M gas to deploy. At 20 Gwei: ~$10-50 on mainnet.
• Complex DeFi protocol (Uniswap V3): ~30M gas. Cost millions of dollars at peak gas
prices.
• Optimisation: Remove unused code, use libraries, deploy on L2 (Arbitrum deployment = 10-
100x cheaper).
💡 EXAM TIP: Deployment question: List the 8 deployment steps. Know: constructor args in
calldata, address calculation formula, why verify on Etherscan, testnet options.

Page 10 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

9. Playing with Contracts (Interacting with Smart Contracts)


Once deployed, smart contracts can be interacted with in multiple ways — from simple web
interfaces to programmatic scripts to direct command-line interaction.

9.1 Interaction via Remix IDE


• After deployment, Remix shows all public functions with input fields.
• Call read functions (view/pure) for free — no gas, no transaction.
• Call write functions — MetaMask pops up asking for gas approval.
• Read transaction receipts, events, and return values in Remix's console.

9.2 Interaction via [Link] (DApp Frontend)


const { ethers } = require('ethers');

// Connect to MetaMask
const provider = new [Link]([Link]);
const signer = await [Link]();

// Load contract
const contract = new [Link](CONTRACT_ADDRESS, ABI, signer);

// Call view function (free, no transaction)


const balance = await [Link](userAddress);
[Link]('Balance:', [Link](balance, 18));

// Send transaction (costs gas, needs wallet signature)


const tx = await [Link](recipientAddress, amount);
await [Link](); // Wait for confirmation
[Link]('Transfer confirmed in block:', [Link]);

9.3 Interaction via Geth Console


Geth's JavaScript console (attached to a running geth node) allows direct interaction with
contracts:
// Attach to running Geth node
geth attach [Link]

// Load Web3
var Web3 = require('web3');
var web3 = new Web3('[Link]

// Create contract instance


var contract = new [Link](ABI, CONTRACT_ADDRESS);

// Read balance
[Link](address).call().then([Link]);

// Send transaction
[Link](to, amount).send({ from: accounts[0] });

Page 11 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

9.4 Interaction via Etherscan


• Every verified contract on Etherscan has a 'Read Contract' and 'Write Contract' tab.
• Read Contract: Call any view function directly — no wallet needed.
• Write Contract: Connect MetaMask and call any write function through the web UI.
• Events tab: View all emitted events with their decoded arguments.
• This is the most user-friendly way for non-developers to interact with contracts.
💡 EXAM TIP: Interaction question: Explain 4 ways to interact with a deployed smart contract.
Include Remix, [Link] (with code flow), Geth console, and Etherscan.

Page 12 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

PART B — MINING ETHER

10. Why? Ether's Source — Defining Mining


Mining (in Proof of Work systems) is the mechanism by which new cryptocurrency is created and
transactions are secured. Even though Ethereum has moved to Proof of Stake post-Merge (2022),
understanding PoW mining is essential exam content as it forms the conceptual foundation.

10.1 Why Mining Exists


• Problem: In a decentralised network with no central authority, how do we decide who gets
to write the next block of transactions? And how do we prevent spam/fake blocks?
• Solution: Proof of Work mining. To write a block, you must prove you did real, expensive
computational work. Cheating costs electricity. Honest mining is rewarded.
• Mining serves 3 purposes:
– 1. Block production: Miners create new blocks, ordering transactions.
– 2. Security: PoW makes attacking the chain prohibitively expensive.
– 3. New coin issuance: Mining is the ONLY way new ETH/BTC entered circulation (pre-
Merge for Ethereum).

10.2 Ether's Source (Pre-Merge)


📌 Block Reward: The newly created ETH (or BTC) awarded to the miner who successfully mines
a block. This is how new coins enter circulation — like a central bank printing money, but on a
fixed, predictable schedule.
• Ethereum's initial block reward: 5 ETH per block (2015 launch).
• Byzantium hard fork (October 2017): Reduced to 3 ETH per block.
• Constantinople hard fork (February 2019): Reduced to 2 ETH per block.
• The Merge (September 15, 2022): PoW mining ended. Ethereum switched to PoS. Block
rewards now come from staking issuance (~0.5% annually vs 4.5% under PoW). Base fee
burned since EIP-1559.
• Uncle block reward: Miners of uncle/ommer blocks received 7/8 of the full block reward.
• Including uncle reward: Miner who included an uncle in their block received extra 1/32 block
reward.

10.3 Defining Mining — The Technical Process


Mining = finding a nonce (number used once) such that the hash of the block header is below the
current target value.
• Mining algorithm (Ethereum): Ethash (memory-hard, designed to be ASIC-resistant and
GPU-friendly).
• The puzzle: Find nonce N such that: Keccak256(block_header + N) < Target.
• This is essentially a guessing game — must try billions of nonces per second.
• Probability of success per attempt: Target / 2^256 (extremely small).
• Expected attempts: 2^256 / Target = difficulty.
• At difficulty D and hashrate H (hashes/sec): Expected time to find block = D / H seconds.

Page 13 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

11. Difficulty, Self-Regulation, and the Race for Profit


11.1 What is Difficulty?
📌 Mining Difficulty: A number that determines how hard it is to find a valid block hash. A higher
difficulty means the hash must have more leading zeros — harder to find. Adjusts automatically to
maintain target block time.
• Target = Max_Target / Difficulty. Smaller target = more leading zeros required = harder.
• Bitcoin: Max_Target = 0x00000000FFFF0000... Difficulty 1 block requires hash starting with
8 zeros.
• At Bitcoin's current difficulty (~90 trillion), the hash must have ~23 leading zeros.
• Ethereum Difficulty (pre-Merge): Adjusted every block (vs Bitcoin's 2016 blocks). More
responsive to hashrate changes.

11.2 Self-Regulation Mechanism


The difficulty adjustment algorithm ensures block times remain stable regardless of how many
miners join or leave the network — a brilliant self-regulating economic system.
Bitcoin Difficulty Adjustment (every 2016 blocks, ~2 weeks):
• Measure actual time for last 2016 blocks.
• new_target = old_target × (actual_time / 20160 minutes).
• Capped: Max 4× increase or 4× decrease per adjustment.
• If more miners join (hashrate doubles): blocks found every 5 min → adjustment doubles
difficulty → back to 10 min.
• If miners leave (price crash): blocks slow to 20 min → adjustment halves difficulty → back
to 10 min.
Ethereum Difficulty Adjustment (every block, pre-Merge):
• Adjusted every block using a formula based on parent block timestamp vs current
timestamp.
• If block found < 10 seconds after parent: Difficulty increases by ~1/2048.
• If block found 10-19 seconds after parent: Difficulty unchanged.
• If block found 20+ seconds after parent: Difficulty decreases.
• Target block time: ~15 seconds (much faster than Bitcoin's 10 minutes).

11.3 The Race for Profit


Mining is a competitive business. Miners maximise profit through:
• Profit formula: Mining Profit = (Block Reward + Transaction Fees) × ETH Price - Electricity
Cost - Hardware Amortisation.
• Electricity cost: The dominant variable cost. Miners seek cheapest electricity globally
(hydropower in Sichuan China, geothermal in Iceland, stranded gas in Texas).
• Hardware efficiency: Measured in megahashes per second per watt (MH/s/W). More
efficient = more hashes for same electricity.
• Pool vs solo: Solo mining = random but full reward. Pool mining = frequent small rewards
proportional to hashrate contributed.
• MEV (Maximal Extractable Value): Miners (and now validators) can reorder, insert, or
censor transactions for profit. Flashbots emerged to formalise this market.
• When price drops: Many miners become unprofitable → shut down → hashrate decreases
→ difficulty adjusts down → remaining miners become more profitable → equilibrium
restored. Beautiful self-regulation.
💡 EXAM TIP: Difficulty question: Explain what difficulty is, how adjustment works (formula),
and the self-regulation cycle with mining profit formula.

Page 14 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

12. How Proof of Work Regulates Block Time


Proof of Work's difficulty adjustment creates a feedback control system that maintains consistent
block production rates regardless of network conditions.

12.1 The Control System


• Setpoint: Bitcoin target = 10 minutes per block. Ethereum target = ~15 seconds.
• Sensor: Measure actual time between blocks over the adjustment period.
• Controller: Difficulty adjustment algorithm.
• Actuator: New difficulty setting changes hash requirements.
• Result: Blocks come too fast → difficulty up → blocks slow down. Blocks come too slow →
difficulty down → blocks speed up.

12.2 Block Time Importance


• Too fast (1 second): High orphan/uncle rate — many simultaneous blocks, network splits,
security weakened.
• Too slow (1 hour): Poor user experience, unresponsive to mempool, slow transaction
confirmation.
• Goldilocks zone: Bitcoin 10 minutes (high security, low orphan rate). Ethereum 15 seconds
(faster UX, higher orphan rate managed by GHOST).
• Block time × block reward = new coin issuance rate. Stable block time = predictable
monetary policy.

12.3 Uncle/Ommer Blocks — When Two Miners Win Simultaneously


📌 Uncle Block (Ommer): A valid block found at the same time as the main chain block but not
included in the main chain. In Bitcoin they are called orphan blocks and fully discarded. In
Ethereum's GHOST protocol they receive partial reward.
• Occurs when two miners find valid blocks within seconds of each other and different parts
of the network hear each first.
• One becomes the canonical block (whichever the next miner builds on). The other becomes
an uncle.
• GHOST protocol: Uncles included in headers within 7 generations can claim uncle reward.
• Uncle reward: 7/8 × block reward (pre-Merge: 7/8 × 2 ETH = 1.75 ETH) to uncle miner.
• Including miner bonus: 1/32 × block reward per uncle included.
• Why include uncles? Their PoW still contributed to network security. Rewarding them
prevents centralisation (large pools have lower uncle rates — including uncles levels the
playing field).

13. DAG and Nonce in Ethereum Mining


13.1 The DAG (Directed Acyclic Graph)
📌 DAG (Directed Acyclic Graph): A large dataset (~1 GB, growing each epoch) used in
Ethereum's Ethash mining algorithm. Miners must traverse the DAG pseudo-randomly for each
hash attempt, requiring fast GPU memory — making ASIC mining economically difficult.
• Purpose: Memory-hardness. Ethash is designed so that mining requires lots of fast memory
access, not just raw computational power.

Page 15 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• ASIC resistance: Custom ASICs are fast at computation but expensive to make with high-
bandwidth memory. This kept GPU miners competitive longer.
• DAG size: Started at ~1 GB in 2015, grew by ~8 MB per epoch (30,000 blocks, ~5.2 days).
• DAG generation: Each epoch, miners generate a new DAG from a smaller seed hash
(using Keccak512 operations). Generation takes ~10 minutes.
• Verification efficiency: Full nodes verify PoW using a smaller cache (~16 MB) without
storing the full DAG. Fast to verify, slow to produce — asymmetric difficulty.

13.2 Nonce — The Mining Variable


📌 Nonce: Number Used Once. A 64-bit (Ethereum) or 32-bit (Bitcoin) value that miners iterate
through trying to find a hash below the target. The primary variable miners control in the mining
loop.
• Mining loop:
– 1. Assemble block header (fixed fields: parent hash, timestamp, transactions, etc.)
– 2. Set nonce = 0.
– 3. Compute seed = Keccak512(block_header + nonce).
– 4. Use seed to traverse DAG pseudo-randomly → compute mixHash.
– 5. Final hash = Keccak256(seed + mixHash). If hash < target → FOUND! Broadcast
block.
– 6. If not: nonce++ → go to step 3.
• Nonce space: Bitcoin has 2^32 (~4 billion) nonce values. Ethereum uses 64-bit nonce =
2^64 values (much larger space).
• Extra nonce: When nonce space exhausted (all values tried, none valid), miner changes
the extra nonce in the coinbase transaction (Bitcoin) or modifies timestamp/extra fields
(Ethereum) to get a different starting state.
• MixHash: In Ethash, this intermediate value proves the miner actually traversed the DAG
(memory access proof). Included in block header.

14. Faster Blocks, Stale Blocks, and Difficulties


14.1 Faster Blocks — Trade-offs
Ethereum chose a much faster block time (~15 seconds) than Bitcoin (~10 minutes). This creates
both benefits and challenges:
Benefits of Faster Blocks:
• Better user experience: Transaction confirmed in 15 seconds vs 10 minutes.
• More throughput: ~15 TPS vs Bitcoin's ~7 TPS.
• More responsive: Mempool cleared faster. Less congestion during normal use.
Challenges of Faster Blocks:
• Higher orphan/uncle rate: 15-second block time vs ~12-second propagation delay →
significant fraction of blocks become uncles.
• Pre-Merge uncle rate: ~6-9% of blocks were uncles. Bitcoin's uncle rate < 1%.
• Security implications: If many miners are mining uncles (wasted PoW), an attacker needs
less total hashrate to 51% attack. GHOST protocol mitigates this.
• Network overhead: More blocks = more block announcements = more bandwidth used.

14.2 Stale Blocks — Types and Handling


Orphan Blocks (Bitcoin terminology): A valid block that is no longer part of the main chain
because a competing block at the same height was extended first. All transactions in the orphan
must go back to the mempool. Miner receives no reward.

Page 16 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

Uncle/Ommer Blocks (Ethereum terminology): Same concept as orphan, but Ethereum's


GHOST protocol gives these blocks partial credit (7/8 reward) and includes them in chain weight
calculation.
Stale Shares (Mining Pools): In pool mining, when a miner submits a valid share for a block that
was already found by someone else. The share is 'stale' — doesn't count toward reward.

14.3 Difficulties — The Difficulty Bomb


📌 Difficulty Bomb: A deliberate increase in Ethereum's mining difficulty coded into the protocol,
designed to make PoW mining increasingly infeasible over time — forcing the transition to Proof of
Stake.
• Mechanism: After a certain block number, difficulty increases exponentially ('ice age').
Block times would stretch from 15 seconds to minutes to hours — mining becomes
economically impossible.
• Purpose: Prevents miners from continuing on the old PoW chain after PoS launch. Creates
a 'carrot and stick' — miners must either upgrade to PoS or become irrelevant.
• Timeline: Bomb was delayed multiple times (Byzantium, Constantinople, Muir Glacier,
London, Arrow Glacier, Gray Glacier upgrades) as PoS development took longer than
expected.
• Final outcome: The Merge (September 15, 2022) occurred before the bomb made mining
unviable. Ethereum switched to PoS and mining ended permanently.
💡 EXAM TIP: Difficulty bomb is a common question: explain what it is, its purpose (force PoS
transition), mechanism (exponential difficulty), why it was delayed multiple times, and final
outcome (The Merge).

15. Ancestry of Blocks and Transactions


15.1 Block Ancestry — The Chain
Every block in the blockchain has exactly one parent (except the genesis block). This parent-child
relationship forms the 'ancestry' of the chain:
• Genesis Block (Block 0): No parent. Hard-coded into the client. Bitcoin genesis block was
mined by Satoshi on January 3, 2009.
• Block N's parent: Block N-1. Its grandparent: Block N-2. Its ancestor at depth K: Block N-K.
• Confirmation count: A transaction in Block N has 1 confirmation when Block N+1 is mined,
2 confirmations when Block N+2 is mined, etc.
• Why depth matters for security: To rewrite a transaction in Block N, an attacker must
recompute PoW for Block N through the current tip — more depth = more work needed =
more secure.
• 6 confirmations rule (Bitcoin): After 6 blocks, reversing a transaction would require
controlling >10% of the global hashrate — considered practically impossible for most
attacks.

15.2 Transaction Ancestry in the Mempool


📌 Mempool (Memory Pool): A temporary holding area on each node for valid but unconfirmed
transactions awaiting inclusion in a block. Like a waiting room before transactions are permanently
recorded.
• Transaction lifecycle: Created and signed by user → broadcast to network → enters
mempool of every receiving node → miner selects from mempool → included in block →
confirmed.

Page 17 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• Mempool ordering: Miners typically select transactions in order of fee/gas (highest paying
first). During congestion, low-fee transactions can wait hours or days.
• Child-pays-for-parent (CPFP): If transaction A is stuck (low fee), you can create a child
transaction B spending A's output with a very high fee. Miner picks up both A+B together
because the combined fee rate is attractive.
• Replace-by-Fee (RBF, Bitcoin): Replace a stuck low-fee transaction with a higher-fee
version of the same inputs. Signals the network to prefer the replacement.
• Transaction chains: In Ethereum, if your account nonce is 5 and you have pending nonce 3,
4 transactions — the nonce 5 transaction is 'stuck' until 3 and 4 are confirmed (nonces
must be sequential).

16. Ethereum and Bitcoin — Key Differences


While both are leading blockchains using similar cryptographic foundations, Ethereum and Bitcoin
have fundamentally different design philosophies and use cases.

Dimension Bitcoin Ethereum


Purpose Digital gold / P2P payment Programmable world
system computer / smart contracts
Created 2009 (Satoshi Nakamoto) 2015 (Vitalik Buterin + team)
Consensus (current) Proof of Work (SHA-256) Proof of Stake (post-Merge,
2022)
Block time ~10 minutes ~12 seconds (post-Merge)
Transaction speed ~7 TPS ~15-30 TPS (L1)
Supply cap 21 million BTC (hard cap) No hard cap (EIP-1559
creates deflationary pressure)
Scripting Bitcoin Script (non-Turing Solidity/EVM (Turing
complete) complete)
Smart contracts Limited (Taproot, Lightning) Full-featured (DeFi, NFTs,
DAOs)
Account model UTXO Account-based (EOA +
Contract)
Primary use Store of value, P2P payment DeFi, NFTs, dApps,
tokenisation
Mining algo SHA-256 (ASIC-dominant) Was Ethash (GPU). Now
PoS.
Market cap rank #1 (~$1.3T) #2 (~$450B)

💡 EXAM TIP: Ethereum vs Bitcoin comparison is a guaranteed 5-mark question. Use the table
above — minimum 6 comparison dimensions with specific examples.

Page 18 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

17. Forking
A fork occurs when the blockchain diverges into two or more paths. Forks can be intentional
(protocol upgrades) or unintentional (natural orphans).

17.1 Types of Forks


Accidental Fork (Natural):
• Two miners find valid blocks simultaneously → two competing chain tips.
• Resolved automatically: Next block extends one chain → that chain wins. Losing block
becomes uncle/orphan.
• Frequency: Happens regularly. Bitcoin: ~1-2 per month. Pre-Merge Ethereum: several per
day (faster blocks).
Soft Fork:
• Backward-compatible protocol upgrade. Old nodes still consider new blocks valid.
• New rules are a subset of (more restrictive than) old rules.
• Doesn't split the chain permanently — if majority miners upgrade, old nodes follow.
• Examples: Bitcoin SegWit (2017), Bitcoin P2SH (2012), Bitcoin Taproot (2021).
• Activation: BIP9 (miner signalling), BIP8 (timeout with forced activation), UASF (User
Activated Soft Fork).
Hard Fork:
• Non-backward-compatible. Old nodes reject new blocks as invalid.
• Creates two permanently separate chains if any nodes stay on old rules.
• Contentious hard fork: Community splits. Both chains continue with different communities,
different prices.
• Planned hard fork: All participants agree to upgrade. Old chain abandoned (no significant
mining support).

17.2 Famous Hard Forks


Ethereum Classic (ETC) — July 2016:
• Context: The DAO hack — attacker exploited reentrancy vulnerability, drained ~3.6M ETH
(~$50M at time).
• The fork: Ethereum Foundation proposed hard fork to return stolen funds to DAO holders.
Passed with ~85% community support.
• Ethereum (ETH): New chain with rolled-back DAO transactions. 'Code is law' broken
(edited blockchain history).
• Ethereum Classic (ETC): Old chain. Purists who believed 'code is law' — the hack was
valid under the rules. ETC still exists today (~$7B market cap).
Bitcoin Cash (BCH) — August 2017:
• Context: Bitcoin scaling debate. Block size limit (1MB) causing congestion, high fees.
• The fork: Bitcoin Cash increased block size to 8MB (later 32MB). Better for daily payments.
• Bitcoin (BTC): Kept 1MB limit, pursued SegWit + Lightning Network for scaling.
• Bitcoin Cash (BCH): Diverged as separate cryptocurrency. Later forked again into BCH and
BSV (Bitcoin SV).
Bitcoin SV (BSV) — November 2018:
• BCH hard fork. Craig Wright (claimed Satoshi) faction. Block size to 128MB, then 2GB.
Very controversial.
Ethereum's planned hard forks (upgrades):
• Homestead (2016), Byzantium (2017), Constantinople (2019), Istanbul (2019), Muir Glacier
(2020), Berlin (2021), London/EIP-1559 (2021), Arrow Glacier (2021), The Merge (2022),
Shanghai/Capella (2023), Dencun (2024).

Page 19 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• These were consensus upgrades — entire community agreed. No chain split.


💡 EXAM TIP: Forking question: Define soft fork vs hard fork (with example for each). Explain
the Ethereum Classic fork — context (DAO hack), decision, outcome, philosophical debate
('code is law').

18. Mining Setup — Geth on Windows


This section covers the practical setup of Ethereum mining using Geth (Go-Ethereum) client. Note:
All Ethereum PoW mining ended at The Merge (September 2022). This is historical but exam-
relevant content.

18.1 Installing Geth on Windows


• Download: [Link] — choose Windows installer (64-bit).
• Install: Run installer. Geth added to PATH automatically.
• Verify: Open Command Prompt → type 'geth version' → shows version info.
• Data directory: Default C:\Users\[user]\AppData\Roaming\Ethereum. Stores blockchain,
keystore.

18.2 Launching Geth with Flags


Geth is controlled through command-line flags. Key flags for mining and development:
// Start Geth on mainnet with HTTP JSON-RPC enabled
geth --http --[Link] eth,net,web3,personal --[Link] '*'

// Start on Sepolia testnet


geth --sepolia --http --[Link] eth,net,web3

// Start a private/development network


geth --datadir ./mychain --networkid 1234 --http

// Start with mining enabled (legacy PoW, now for private nets only)
geth --mine --[Link] 4 --[Link] 0xYourAddress

// Sync mode options


geth --syncmode snap // Snap sync (recommended, fastest)
geth --syncmode full // Full sync (downloads everything)
geth --syncmode light // Light sync (headers only, deprecated)

18.3 Key Geth Flags Explained

Flag Purpose
--datadir <path> Custom blockchain data directory
--networkid <id> Specify network ID (1=Mainnet,
11155111=Sepolia)
--http Enable HTTP-RPC server (default port 8545)
--[Link] Specify enabled API modules (eth, net, web3,
personal, debug)
--[Link] CORS whitelist for browser DApps

Page 20 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

Flag Purpose
--ws Enable WebSocket server (port 8546) for
real-time subscriptions
--mine Enable mining (only useful for private
networks now)
--[Link] Number of CPU threads for mining
--[Link] Address to receive mining rewards
--syncmode snap (fast), full (complete), light (headers
only)
--gcmode archive Keep all historical state (needed for block
explorers)
--bootnodes Hardcoded bootnode ENR addresses for
peer discovery
--maxpeers Maximum number of network peers (default
50)
--verbosity Log level (0=silent, 3=info, 5=debug)

19. Executing Commands in the EVM via the Geth Console


The Geth JavaScript console provides an interactive shell for interacting with the Ethereum node. It
exposes the [Link] API and all JSON-RPC endpoints.

19.1 Attaching to the Console


// Attach to running Geth node (IPC - most secure)
geth attach
// or specify IPC path
geth attach ipc:/path/to/[Link]

// Attach via HTTP (less secure, allows remote)


geth attach [Link]

// Start Geth directly with console


geth console

19.2 Essential Console Commands


Account Management:
[Link]('password') // Create new account
[Link] // List all accounts
[Link]([Link][0]) // Balance in Wei
[Link]([Link]([Link][0]), 'ether') // Balance in ETH
[Link]([Link][0], 'password', 300) // Unlock for 300
sec
Network Information:
[Link] // Network ID
[Link] // Connected peers
[Link] // Sync status (false if synced)

Page 21 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

[Link] // Current block height


[Link] // List connected peers
Transaction Operations:
// Send ETH transaction
[Link]({
from: [Link][0],
to: '0xRecipientAddress',
value: [Link](1, 'ether'),
gas: 21000
})

// Get transaction details


[Link]('0xTxHash')
[Link]('0xTxHash')
Block Information:
[Link]([Link]) // Latest block details
[Link]('latest') // Same as above
[Link](1000000) // Specific block by number
Mining Commands (Private Networks):
[Link](4) // Start mining with 4 threads
[Link]() // Stop mining
[Link]([Link][0]) // Set reward address
[Link] // Current hashrate (hashes/sec)
[Link] // true/false mining status
Contract Interaction:
// Load contract ABI and address
var abi = [...]; // Contract ABI
var addr = '0xContractAddress';
var contract = [Link](abi).at(addr);
[Link]([Link][0]); // Read function
[Link](recipient, amount, {from:
[Link][0]});

💡 EXAM TIP: Geth console is frequently asked. Memorise: [Link], [Link],


[Link], [Link], [Link]/stop, [Link] format.

20. Mining on the Testnet


Testnets are public blockchains that mirror mainnet functionality but use worthless test ETH. They
are used for development, testing, and learning — including practising mining (on PoW testnets).

20.1 Why Use a Testnet?


• Free: Test ETH from faucets. No real money at risk.
• Safe: Deploy buggy contracts without financial consequences.
• Realistic: Same EVM, same transaction mechanics as mainnet.
• Mining practice: Private PoW testnets allow mining practice without expensive hardware.

20.2 Setting Up a Private PoW Testnet


// Step 1: Create [Link]
{
"config": { "chainId": 1234, "homesteadBlock": 0, "ethash": {} },

Page 22 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

"difficulty": "0x400",
"gasLimit": "0x8000000",
"alloc": {
"0xYourAddress": { "balance": "1000000000000000000000" }
}
}

// Step 2: Initialise the chain


geth --datadir ./testchain init [Link]

// Step 3: Start geth with console


geth --datadir ./testchain --networkid 1234 --http console

// Step 4: In console - start mining


[Link](2) // 2 CPU threads
// Watch blocks being mined
[Link] // Check block height increasing

20.3 Generating the DAG for Mining


• Before mining starts, Geth must generate the Ethash DAG for the current epoch.
• First time: Takes ~5-10 minutes. Geth shows 'Generating DAG in progress' log messages.
• DAG stored in: ~/.ethash/ directory (Linux/Mac), C:\Users\[user]\AppData\Roaming\Ethash
(Windows).
• Low difficulty in [Link]: Set difficulty: '0x400' for private testnet so CPU mining finds
blocks quickly.

21. GPU Mining Rigs


GPU (Graphics Processing Unit) mining was the dominant form of Ethereum mining pre-Merge.
Understanding GPU mining rigs is still exam-relevant for understanding Ethereum's economic
history and the ASIC-resistance design philosophy.

21.1 Why GPUs for Ethereum?


• Ethash is memory-hard: requires high-bandwidth VRAM (Video RAM) to traverse the DAG.
GPUs have 8-24 GB of high-bandwidth GDDR6/HBM memory — far more cost-effective
than equivalent ASIC VRAM.
• ASIC resistance goal: Keep mining accessible to enthusiast GPU owners, not just industrial
ASIC manufacturers. More decentralised mining.
• Comparison: A top-end Nvidia RTX 3090 achieves ~120 MH/s Ethash. A Bitcoin ASIC
(Antminer S19) achieves 100 TH/s SHA-256 — impossible to GPU mine Bitcoin
competitively.

21.2 GPU Mining Rig Components


1. Motherboard: Mining-specific boards with 6-19 PCIe slots. Examples: ASUS B250 Mining
Expert (19 GPUs), MSI Z390-A Pro.
2. GPUs: Primary mining hardware. Best Ethereum miners: Nvidia RTX 3080 (98 MH/s, 230W),
RTX 3070 (62 MH/s, 117W), AMD RX 6800 XT (64 MH/s, 150W).
3. CPU: Budget processor sufficient — GPU does the work. Intel Celeron or AMD Athlon fine.
4. RAM: 4 GB minimum. Mining uses minimal system RAM.
5. Storage: 128 GB SSD for OS + Geth data. Not performance critical.

Page 23 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

6. Power Supply Unit (PSU): Must support total GPU wattage + 20% headroom. 6-GPU rig: 6 ×
200W + overhead = 1400W+ PSU needed. Efficiency: 80+ Platinum/Gold rated.
7. PCIe Risers: Short USB 3.0 cables connecting GPUs to motherboard slots. Allows GPUs to be
spread out for cooling.
8. Mining Frame: Open-air frame (aluminium or wood) for airflow. GPUs cannot be in a closed
case — they overheat.
9. Cooling: Additional fans, GPU overclocking/undervolting to maximise efficiency. Operating temp
target: < 75°C GPU core.

21.3 GPU Performance Metrics

GPU Ethash Hashrate (MH/s)


Nvidia RTX 3090 ~120 MH/s (350W power draw)
Nvidia RTX 3080 ~98 MH/s (230W)
Nvidia RTX 3070 ~62 MH/s (117W)
AMD RX 6800 XT ~64 MH/s (150W)
Nvidia RTX 3060 Ti ~60 MH/s (130W — best efficiency)
AMD RX 580 8GB (budget) ~32 MH/s (135W — older gen)

• Overclocking: Increase GPU memory clock → higher hashrate. Undervolting: Reduce core
voltage → lower power consumption. Both improve profitability.
• Memory overclocking matters most for Ethash (memory-bound algorithm). Core clock has
minimal impact.

22. Mining on a Pool with Multiple GPUs


22.1 Why Mining Pools?
Solo mining: Your rig competes against the entire network. With a 6-GPU rig at 600 MH/s vs
Ethereum's pre-Merge ~900 TH/s total hashrate — your share was 600/900,000,000 = 0.000067%
of blocks. Expected block every 1,500 years solo!
• Pool mining: Combine hashrate with thousands of other miners. Find blocks proportionally
more often. Distribute rewards based on each miner's hashrate contribution (shares
submitted).
• Variance reduction: Consistent, predictable payouts. Pool finds a block every few minutes.
Your share credited based on work done since last block.

22.2 How Pool Mining Works


• Step 1: Choose pool. Historically popular Ethereum pools: Ethermine, 2Miners, Hiveon,
Flexpool.
• Step 2: Configure mining software to connect to pool stratum server.
• Step 3: Pool sends 'work' (block header template) to your miner.
• Step 4: Miner finds hashes below pool's share difficulty (much lower than network difficulty).
• Step 5: Submit valid shares to pool — proves you're working.
• Step 6: Pool eventually finds a block (full network difficulty). Reward distributed to all
contributors based on shares submitted.

Page 24 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

• Pool fee: 1-2% of rewards. Fair price for variance reduction and pool infrastructure.

22.3 Pool Payout Models


PPS (Pay Per Share): Fixed payment per valid share, regardless of whether pool found a block.
Eliminates all variance for miner. Pool bears the variance risk. Typically lower expected payout.
PPLNS (Pay Per Last N Shares): Reward based on shares submitted in the window leading to a
block. Favours consistent miners — miners who join just before a block find ('pool hopping') earn
proportionally less. Most common model.
SOLO (Pool-facilitated Solo Mining): Pool handles network connectivity. You get full block
reward if your hashrate finds a block. High variance — same as solo mining but with better network
infrastructure.

22.4 Mining Software for GPU Pools

Software Details
Claymore's Miner (legacy) Most popular pre-Merge Ethereum miner.
Closed source. 1% dev fee. Windows/Linux.
Phoenix Miner Fast, low dev fee (0.65%). Windows/Linux.
Good AMD+Nvidia support.
TeamRedMiner AMD-optimised. Low dev fee. Good for RX
5000/6000 series.
T-Rex Miner Nvidia-optimised. Low fee. Excellent
efficiency optimisations.
lolMiner Cross-vendor, fast development, supports
AMD and Nvidia.
NBMiner Good for Nvidia, supports LHR (Lite Hash
Rate) unlock on 3000 series.

22.5 Sample Pool Mining Command (Historical)


// Phoenix Miner connecting to Ethermine pool (historical - Ethereum PoW
ended)
[Link]
-pool ssl://[Link]
-wal 0xYourEthereumWalletAddress
-worker Rig01
-log 1

// Equivalent command for private testnet with Geth stratum


ethminer --farm-recheck 200 -G \
--stratum stratum+tcp://localhost:8008

💡 EXAM TIP: GPU mining question: Explain pool mining vs solo mining (variance +
PPS/PPLNS models), list components of a GPU rig (6 components), and explain why GPU over
ASIC for Ethash (memory-hardness).

Page 25 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

MODULE 3 — QUICK REVISION SUMMARY


SMART CONTRACTS & TOKENS — Key Points:
• EVM = trustless back end. Replaces: server (logic), database (storage), auth (key
signatures).
• Asset tokenisation: Physical (real estate, gold), financial (bonds, equity), digital (WBTC,
NFTs).
• Stablecoins: Fiat-backed (USDC), crypto-backed (DAI), algorithmic (failed UST).
• NFT standards: ERC-721 (unique, 1 per tokenId), ERC-1155 (fungible + non-fungible in
one contract).
• ERC-20: 6 functions (totalSupply, balanceOf, transfer, allowance, approve, transferFrom) +
2 events (Transfer, Approval).
• Token deployment: Write → Compile (ABI + bytecode) → Deploy tx (to = null) → Address
generated → Verify on Etherscan.
• Interact via: Remix IDE, [Link] (DApp), Geth console, Etherscan Read/Write.
MINING ETHER — Key Points:
• Mining purpose: Block production + security + new coin issuance (only source of new ETH
pre-Merge).
• Difficulty: Target = Max/Difficulty. Adjusts to maintain block time. Ethereum: every block.
Bitcoin: every 2016 blocks.
• DAG: ~1 GB dataset for Ethash. Memory-hard → GPU-friendly, ASIC-resistant.
Regenerated every epoch.
• Nonce: 64-bit counter miners iterate. MixHash proves DAG traversal.
• Stale blocks: Orphan (Bitcoin, no reward) vs Uncle (Ethereum, 7/8 reward via GHOST).
• Difficulty bomb: Exponential difficulty increase forcing PoS transition. Delayed → The
Merge (Sept 2022).
• Hard forks: Ethereum Classic (DAO hack 2016), Bitcoin Cash (block size 2017).
• Geth flags: --mine, --[Link], --syncmode snap, --http, --[Link].
• Pool mining: Shares submitted → proportional rewards. PPS (fixed/share), PPLNS (last N
shares).

Topic Likely Question Key Answer Points


EVM as Back End 5 marks — DApp vs 8 differences: hosting, trust,
traditional architecture auth, upgrades, persistence,
censorship, SPoF,
composability
ERC-20 Token 5 marks — Explain ERC-20 6 functions + 2 events, with
standard purpose of each
Token Deployment 5 marks — Steps to deploy a 8 steps: write, compile, fund,
token create tx, sign, mine,
address, verify
Mining / Difficulty 5 marks — Explain PoW and Target formula, adjustment
difficulty algorithm, self-regulation
cycle
DAG + Nonce 5 marks — Ethash algorithm DAG purpose, size, epoch,
mining loop steps, nonce
exhaustion
Forking 5 marks — Hard fork vs soft Definitions + DAO hack (ETH
fork + example vs ETC) + BCH examples

Page 26 | SVKM's UPG College | Exam Notes 2024-25


[Link] (IT) Sem IV | Blockchain | Module 3: Smart Contracts & Tokens + Mining Ether

Topic Likely Question Key Answer Points


Pool Mining 5 marks — Pool vs solo + Variance, PPS vs PPLNS,
payout models pool fee, share submission
Geth Console 5 marks — Geth commands [Link], getBalance,
sendTransaction,
[Link]/stop,
blockNumber

— END OF MODULE 3 NOTES —


15 Lectures covered · 22 Major Topics · All Exam Topics Included

Page 27 | SVKM's UPG College | Exam Notes 2024-25

You might also like