�CS61065: Theory and Applications of Blockchain
Ethereum
TA – Utkalika Satapathy
INDIAN INSTITUTE OF TECHNOLOGY
KHARAGPUR
Department of Computer Science and Engineering
CONTENT
Indian Institute of Technology Kharagpur
Ethereum – Decentralized Computation Platform
Indian Institute of Technology Kharagpur
Ethereum – Decentralized Computation Platform
Indian Institute of Technology Kharagpur
Ethereum Consensus Mechanism
Indian Institute of Technology Kharagpur
Key Terms
Ether
Gas
Wallet
Smart Contract
DApps
Indian Institute of Technology Kharagpur
Ethereum Stack
Ethereum Virtual Machine (EVM)
Smart Contract
Ethereum Nodes
Ethereum Client APIs
End-User Application
Indian Institute of Technology Kharagpur
Blockchain Stack
Tools and Interfaces
GUI
(Mist Wallet & Browser)
DApp
Framework
(Truffle, Embark)
Ethereum Clients
(Geth, PyEthApp)
Compilers
(Solidity, Serpent)
JSON RPC
Web3.js API
Decentralized Applications (DApps)
Front-End
(HTML, CSS)
Back-End
(JavaScript)
Contracts
(Solidity, Serpent, LLL)
Ethereum
(Decentralized Computation)
Ethereum Protocol
Ethereum Virtual Machine (EVM)
Blockchain
Accounts
Mining
Transactions
Contracts
Indian Institute of Technology Kharagpur
Ethereum Network
P2P
EVM
PoS
Consensus
Eth State
TX Mempool
NPTEL Blockchain and its Applications https://onlinecourses.nptel.ac.in/noc23_cs47/unit?unit=53&lesson=55
Indian Institute of Technology Kharagpur
Ethereum Accounts
Externally Owned Account (EOA)
Account Address
Account Keys
Ether Balance
Contract Account
Contract Address
Contract Code
Ether Balance
Indian Institute of Technology Kharagpur
Externally Owned Account (EOA)
Externally Owned Account (EOA)
Account Address
Account Keys
Ether Balance
Indian Institute of Technology Kharagpur
Contract Account
Contract Account
Contract Address
Contract Code
Ether Balance
Indian Institute of Technology Kharagpur
Ethereum Transactions
World State
(t)
World State
(t+1)
Transaction
Requires:
Indian Institute of Technology Kharagpur
Ethereum Transactions
Indian Institute of Technology Kharagpur
Ethereum Transactions
{
from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",
to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",
gasLimit: "21000",
maxFeePerGas: "300",
maxPriorityFeePerGas: "10",
nonce: "0",
value: "10000000000"
}
Indian Institute of Technology Kharagpur
Ethereum Transactions
{
from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",
to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",
gasLimit: "21000",
maxFeePerGas: "300",
maxPriorityFeePerGas: "10",
nonce: "0",
value: "10000000000"
}
address of the sender
receiving address
amount of ETH to transfer from sender to recipient
the maximum amount of gas units that can be consumed by the transaction
the maximum price of the consumed gas
to be included as a tip to the validator
Indian Institute of Technology Kharagpur
Ethereum Transactions Types
Indian Institute of Technology Kharagpur
Ether
Indian Institute of Technology Kharagpur
Gas
Indian Institute of Technology Kharagpur
Ethereum Units
Unit | Wei Value | Wei |
wei | 1 wei | 1 |
kwei (babbage) | 1e3 wei | 1000 |
mwei (lovelace) | 1e6 wei | 1,000,000 |
gwei (shannon) | 1e9 wei | 1,000,000,000 |
microether (szabo) | 1e12 wei | 1,000,000,000,000 |
milliether (finney) | 1e15 wei | 1,000,000,000,000,000 |
ether (ETH) | 1e18 wei | 1,000,000,000,000,000,000 |
Indian Institute of Technology Kharagpur
EVM - Ethereum Virtual Machine
NPTEL Blockchain and its Applications https://onlinecourses.nptel.ac.in/noc23_cs47/unit?unit=53&lesson=55
Indian Institute of Technology Kharagpur
EVM - Ethereum Virtual Machine
Indian Institute of Technology Kharagpur
NODES AND CLIENTS
Indian Institute of Technology Kharagpur
NODES AND CLIENTS
Indian Institute of Technology Kharagpur
Node Types
Indian Institute of Technology Kharagpur
Sync modes
full: Downloads all blocks (including headers, transactions, and receipts) and generates the state of the blockchain incrementally by executing every block.
snap (Default): Same functionality as fast, but with a faster algorithm.
fast: Downloads all blocks (including headers, transactions and receipts), verifies all headers, and downloads the state and verifies it against the headers.
light: Syncs very quickly and stores the bare minimum of blockchain data. Light nodes only process block headers, not entire blocks. (Light nodes are not currently working on proof-of-stake Ethereum.)
Indian Institute of Technology Kharagpur
Programmatically access Ethereum networks
Ethereum Node
Smart Contract 1
Code
Storage
User
Web UI
web3.js
ethers.js
Ethereum Network (Mainnet / Testnet)
geth / Infura
Endpoints
Ethereum Client/ Node
Smart Contract 2
Accounts
Ethereum Node
Smart Contract 1
Code
Storage
Smart Contract 2
Accounts
Ethereum Node
Smart Contract 1
Code
Storage
Smart Contract 2
Accounts
JSON - RPC
DAPP UI
Indian Institute of Technology Kharagpur
Ethereum Mainnet
Source: https://ethstats.dev
Indian Institute of Technology Kharagpur
Ethereum Mainnet
Indian Institute of Technology Kharagpur
Prerequisites
Indian Institute of Technology Kharagpur
Ethereum Client
Indian Institute of Technology Kharagpur
Ethereum Client
Indian Institute of Technology Kharagpur
Go-Ethereum Client (geth)
Indian Institute of Technology Kharagpur
Installing Go-Ethereum Client (geth)
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
Indian Institute of Technology Kharagpur
Managing Ethereum Accounts
geth account command [command options] [arguments...]
Indian Institute of Technology Kharagpur
Create an account
geth account new
Indian Institute of Technology Kharagpur
List Accounts
geth account list
cat ~/.Ethereum/keystore/<Keyfile-Name>
Indian Institute of Technology Kharagpur
Consensus Client
Indian Institute of Technology Kharagpur
Consensus Client
Indian Institute of Technology Kharagpur
Beacon Light Client
Indian Institute of Technology Kharagpur
Beacon Light Client
Indian Institute of Technology Kharagpur
Connect to a network
Indian Institute of Technology Kharagpur
Connecting to sepolia testnet
geth --sepolia --datadir light-sepolia-dir
Indian Institute of Technology Kharagpur
Interacting with Geth
Or
Indian Institute of Technology Kharagpur
Using RPC over HTTP
geth --sepolia --http
Indian Institute of Technology Kharagpur
Query Balance
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",
"latest”
],
"id": 1
}
Indian Institute of Technology Kharagpur
Query using curl
Request:
curl 127.0.0.1:8545 \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_gasPrice","params": [],"id":1}’
Response:
Indian Institute of Technology Kharagpur
Query using requests
pip install requests
Indian Institute of Technology Kharagpur
Query using requests
import requests
url = http://127.0.0.1:8545
payload = {
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",
"latest"
],
"id": 1
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
Indian Institute of Technology Kharagpur
Query using Tools
geth attach http://127.0.0.1:8545
eth.getBalance("0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4", "latest")
Indian Institute of Technology Kharagpur
Unlock Account
Indian Institute of Technology Kharagpur
MetaMask
Download Metamask: https://metamask.io/download/
Indian Institute of Technology Kharagpur
Extracting Private Key of Account in Geth
curl -LSs https://raw.githubusercontent.com/gochain/web3/master/install.sh | sh�
web3 account extract --keyfile <Keyfile-Location> --password <Password>
Example:
web3 account extract --keyfile /home/utkalika/.ethereum/keystore/UTC--2024-08-20T15-51-10.491464251Z--d7ff489a267d6310c68f2756991baf09204806f8 --password 12345
Downoad Metamask: https://metamask.io/download/
Indian Institute of Technology Kharagpur
Get ether in testnet
Indian Institute of Technology Kharagpur
eth_sendTransaction
Indian Institute of Technology Kharagpur
Prepare Transaction
{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [
{
"from": "04e7ad5d91bedef78e57ee6c56db10de39478232",
"to": "3873dcdb0d5177b2be28ffb911e08be6dbb40f7a",
"value": "0x2386F26FC10000"
}
],
"id": 0
}
0.1 Ether
Indian Institute of Technology Kharagpur
Submit Transaction
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
--data{"jsonrpc": "2.0", "method": "eth_sendTransaction", "params": [{"from": "04e7ad5d91bedef78e57ee6c56db10de39478232", "to": "3873dcdb0d5177b2be28ffb911e08be6dbb40f7a", "value": "0x2386F26FC10000"}],"id": 0}
Indian Institute of Technology Kharagpur
View Transaction on Etherscan
Indian Institute of Technology Kharagpur
Many More RPC Methods
Indian Institute of Technology Kharagpur
INFURA
Indian Institute of Technology Kharagpur
Getting Started with INFURA
Indian Institute of Technology Kharagpur
INFURA – Sending Requests
Request:
Response
curl https://sepolia.infura.io/v3/<INFURA-API-KEY> \
-X POST \
-H "Content-Type: application/json" \
--data '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}'
{"jsonrpc":"2.0","id":1,"result":"0x63dcea"}
Indian Institute of Technology Kharagpur
INFURA – Sending Requests
Request:
Response
curl https://sepolia.infura.io/v3/<INFURE-API-KEY> \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_getBalance",
"params": ["ADDRESS", "latest"],"id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x1c535fcc941d10cf"}
Indian Institute of Technology Kharagpur
INFURA – Sending Requests Using Postman
Indian Institute of Technology Kharagpur
INFURA – Sending Requests Using NodeJS
{
"name": ”<PROJECT_NAME>",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"dependencies": {
"node-fetch": "^2.6.1"
}}
import fetch from 'node-fetch';
fetch("https://sepolia.infura.io.infura.io/v3/YOUR-API-KEY", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
jsonrpc: "2.0",
method: "eth_blockNumber",
params: [],
id: 1
})
})
.then(response =>
response.json()
)
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
OUTPUT:
{ jsonrpc: '2.0', id: 1, result: '0x63dd6b' }
Indian Institute of Technology Kharagpur
Sending Requests Using web3.js
https://web3js.readthedocs.io/
Indian Institute of Technology Kharagpur
Connecting web3.js to Clients
Create your Javascript file and copy the following code:
Connecting to INFURA:
var { Web3 } = require("web3");
var provider = "https://sepolia.infura.io/<YOUR-API-KEY>";
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);
�web3.eth.getBlockNumber().then((result) => {
console.log("Latest Ethereum Block is ", result);
});
Connecting to Geth:
var { Web3 } = require("web3");
var provider = “http://localhost:8545";
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);
Run the code using: node index.js
Indian Institute of Technology Kharagpur
Query Balance
var { Web3 } = require("web3");
var provider = "http://localhost:8545";
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);
console.log("Balance of the account 0x8cD5F171e45d899d7FeB56206a030d749a1A7257 is:");
web3.eth.getBalance("0x8cD5F171e45d899d7FeB56206a030d749a1A7257").then(console.log);
$ node checkBalance.js
Indian Institute of Technology Kharagpur
Ethereum Smart Contracts
Indian Institute of Technology Kharagpur
Smart Contracts
Smart Contract
Value
Address
State
Functions
External Owned Account (EOA)
Transaction
(Data, Value)
Messages to other contracts
(Data, Values)
Events
Indian Institute of Technology Kharagpur
Ethereum Smart Contracts
Indian Institute of Technology Kharagpur
Ethereum Smart Contracts
Smart Contract Code
Compiler
Bytecode
Application Binary
Interface (ABI)
Smart Contract
Deploy
web3.js
Execute
Indian Institute of Technology Kharagpur
Ethereum Smart Contracts
Indian Institute of Technology Kharagpur
Solidity & Bytecode
Indian Institute of Technology Kharagpur
Solidity & Bytecode
compile
Bytecode
OPCODE
Add up all opcodes, Multiply by price = GAS PRICE
Smart Contract
Bytecode
Indian Institute of Technology Kharagpur
Solidity
// SPDX-License-Identifier: GPL-3.0
�pragma solidity >=0.8.2 <0.9.0;
�/**
* @title Storage
* @dev Store & retrieve value in a variable
* @custom:dev-run-script ./scripts/deploy_with_ethers.ts
*/
contract Storage {
�uint256 number;
�/**
* @dev Store value in variable
* @param num value to store
*/
function store(uint256 num) public {
number = num;
}
�/**
* @dev Return value
* @return value of 'number'
*/
function retrieve() public view returns (uint256){
return number;
}
}
Indian Institute of Technology Kharagpur
Solidity Syntax and Structure
Indian Institute of Technology Kharagpur
Data Types
Indian Institute of Technology Kharagpur
Global Variables and Functions
Indian Institute of Technology Kharagpur
Ether Transactions
function deposit() public payable {
// Function to accept Ether into the contract
}
function withdraw() public {
payable(msg.sender).transfer(address(this).balance);
}
Indian Institute of Technology Kharagpur
Inheritance
contract Base {
uint256 data;
function set(uint256 x) public { data = x; }
}
contract Derived is Base {
function get() public view returns (uint256) { return data; }
}
Indian Institute of Technology Kharagpur
Access Control
// Modifier to restrict access to the seller
modifier onlySeller(uint256 itemId) {
require(items[itemId].seller == msg.sender, "Not the item seller");
_;
}
// Modifier to restrict access to the owner
modifier onlyOwner() {
require(msg.sender == owner, "Not the contract owner");
_;
}
Indian Institute of Technology Kharagpur
Example
// 1. Solidity version declaration
pragma solidity ^0.8.0; //The ^0.8.0 means the contract is compatible with version 0.8.0 and above, but below 0.9.0
contract SimpleStorage { // 2. Declaring the contract
uint256 storedData; // 3. Declaring a State Variable to store data
event DataChanged(uint256 newValue); // 4. Declaring an event that is triggered when data is changed
function set(uint256 x) public { // 5. Function to set the stored data
storedData = x; // 6. Setting the state variable 'storedData' to the input value
emit DataChanged(x); // 7. Emitting an event when the data is changed
}
// 8. Function to retrieve the stored data
function get() public view returns (uint256) {
return storedData; // 9. Returning the stored value
}
}
Indian Institute of Technology Kharagpur
Compiling Solidity
• Remix editor
Indian Institute of Technology Kharagpur
Create a project directory
ETHEREUM_NETWORK = "sepolia"
INFURA_API_KEY = "<Your-API-Key>"
SIGNER_PRIVATE_KEY = "<Your-Private-Key>”
DEMO_CONTRACT = "<Contract_Address>” //Once the smart contract is deployed
Indian Institute of Technology Kharagpur
Create a smart contract
pragma solidity >=0.5.8;
contract Demo {
event Echo(string message);
function echo(string calldata message) external {
emit Echo(message);
}
}
Indian Institute of Technology Kharagpur
Create the compile script
Indian Institute of Technology Kharagpur
compile.js
const fs = require("fs").promises;
const solc = require("solc");
async function main() {
const sourceCode = await fs.readFile("Demo.sol", "utf8");
const { abi, bytecode } = compile(sourceCode, "Demo");
const artifact = JSON.stringify({ abi, bytecode }, null, 2);
await fs.writeFile("Demo.json", artifact);}
function compile(sourceCode, contractName) {
const input = {
language: "Solidity",
sources: { main: { content: sourceCode } },
settings: { outputSelection: { "*": { "*": ["abi", "evm.bytecode"] } } }, };
const output = solc.compile(JSON.stringify(input));
const artifact = JSON.parse(output).contracts.main[contractName];
return { abi: artifact.abi, bytecode: artifact.evm.bytecode.object, };}
main()
Indian Institute of Technology Kharagpur
Run the compile script
node compile.js
Indian Institute of Technology Kharagpur
Create a Deployment Script
node deploy.js
Indian Institute of Technology Kharagpur
deploy.js
const { Web3 } = require("web3");
const fs = require("fs");
const { abi, bytecode } = JSON.parse(fs.readFileSync("Demo.json"));
async function main() {
const network = process.env.ETHEREUM_NETWORK;
const web3 = new Web3(
new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`,),);
const signer = web3.eth.accounts.privateKeyToAccount('0x' + process.env.SIGNER_PRIVATE_KEY,);
web3.eth.accounts.wallet.add(signer);
const contract = new web3.eth.Contract(abi);
contract.options.data = bytecode;
const deployTx = contract.deploy();
const deployedContract = await deployTx
.send({ from: signer.address, gas: await deployTx.estimateGas(),})
.once("transactionHash", (txhash) => { console.log(`Mining deployment transaction ...`);
console.log(`https://${network}.etherscan.io/tx/${txhash}`);});
console.log(`Contract deployed at ${deployedContract.options.address}`);
console.log(`Add DEMO_CONTRACT to the.env file to store the contract address: ${deployedContract.options.address}`,);}
require("dotenv").config();
main();
Indian Institute of Technology Kharagpur
Call a contract
node call.js
Indian Institute of Technology Kharagpur
DAPPS in Ethereum
Indian Institute of Technology Kharagpur
DAPPS in Ethereum
DApp
Smart Contracts
Frontend HTML
(index.html)
Frontend JS
(app.js)
Other Files
(css, images)
Ethereum Node
Compiler
Ethereum
Client
1. Send contract for compilation
2. Contract binary sent back to DApp
3. Deploy Contract
4. Contract address and ABI sent back to DApp
5. Send Transaction to contract
Communication network Ethereum Client and Ethereum Network for deploying contract and interacting with contract
DApp Creation workflow
Indian Institute of Technology Kharagpur
References (Extra Resources)
Indian Institute of Technology Kharagpur
96
Indian Institute of Technology Kharagpur