Aaj Kya Seekhenge?

  • EVM kya hai exactly kaise kaam karta hai
  • Stack, Memory, Storage teeno ka fark
  • Opcodes actual machine instructions
  • Bytecode vs Solidity connection samjho
  • Storage slots kaise data store hota hai
  • Memory layout temporary data
  • Calldata function calls ka raw format
  • EVM ka hacker perspective kahan se attack?
  • Decompiling contracts bytecode se logic nikalo
  • Hands-on tools real contracts analyze karo

EVM samajhna = Smart contract ke "engine" ko samajhna! Jab tum EVM jaante ho tum woh bugs dhundh sakte ho jo sirf Solidity padhne se nahi milte! Advanced auditors always EVM level pe sochte hain!

PART 1: EVM Kya Hai? Analogy Se Samjho!

EVM = Ethereum Virtual Machine

Analogy 1 β€” Computer mein computer:
   Tumhare laptop pe ek virtual
   computer chalta hai!
   
   Normal computer:
   Intel/AMD CPU β†’ Machine code execute karta hai
   
   Ethereum:
   EVM β†’ Bytecode execute karta hai
   (Every node pe same EVM hai!)

Analogy 2 β€” Universal calculator:
   Duniya ke 7000+ Ethereum nodes
   sabke paas EXACT same EVM hai
   Ek hi code β†’ Sabka SAME output
   Deterministic = Predictable!

Why this matters for security?
   β†’ Koi bhi EVM bytecode khud run kar sakta hai
   β†’ Transaction replay kar sakta hai locally
   β†’ Bug reproduce karna aasaan!
   β†’ Exploit test karna aasaan!
   
EVM Properties:
━━━━━━━━━━━━━━
 Isolated    : Baaki system se cut off
 Deterministic: Same input = Same output ALWAYS
 Sandboxed   : Contract bahar kuch nahi kar sakta
                 (Sirf blockchain state change!)
 Metered     : Gas se computation limited
 Stack-based : Stack architecture use karta hai

PART 2: EVM Ka Memory Model 3 Types!

EVM mein DATA 3 jagah store ho sakta hai:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   EVM                       β”‚
β”‚                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  STACK   β”‚  β”‚  MEMORY  β”‚  β”‚ STORAGE  β”‚  β”‚
β”‚  β”‚          β”‚  β”‚          β”‚  β”‚          β”‚  β”‚
β”‚  β”‚Temporary β”‚  β”‚Temporary β”‚  β”‚Permanent β”‚  β”‚
β”‚  β”‚256-bit   β”‚  β”‚Byte arrayβ”‚  β”‚Key-Value β”‚  β”‚
β”‚  β”‚Max 1024  β”‚  β”‚Expandableβ”‚  β”‚Blockchainβ”‚  β”‚
β”‚  β”‚items     β”‚  β”‚Per call  β”‚  β”‚pe store  β”‚  β”‚
β”‚  β”‚          β”‚  β”‚          β”‚  β”‚          β”‚  β”‚
β”‚  β”‚FREE      β”‚  β”‚Cheap     β”‚  β”‚EXPENSIVE β”‚  β”‚
β”‚  β”‚(gas)     β”‚  β”‚(gas)     β”‚  β”‚(gas)     β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                             β”‚
β”‚  ALSO:                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚           CALLDATA                   β”‚   β”‚
β”‚  β”‚  Read-only input data (function args)β”‚   β”‚
β”‚  β”‚  Cheapest to use!                    β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

1. Stack EVM Ka Working Area:

Stack = Last In First Out (LIFO)
        (Jaise plate stack karna!)

Properties:
β†’ 256-bit (32 bytes) per item
β†’ Maximum 1024 items
β†’ Free to use (almost no gas!)
β†’ Operations: PUSH, POP, DUP, SWAP

Visual:
   Operation: 2 + 3

   PUSH 2:     [2]
   PUSH 3:     [3, 2]
   ADD:        [5]      ← 3+2=5, both popped, result pushed

   PUSH 10:    [10, 5]
   MUL:        [50]     ← 10*5=50

Hacker relevance:
   Stack overflow = Max 1024 items exceed
   Deep nested calls = Stack kan khatam!
   (Rarely exploitable but interesting!)

2. Memory Temporary Byte Array:

Memory = Temporary RAM
         Call ke baad clear ho jaati hai!

Properties:
β†’ Byte-addressable array
β†’ 32 bytes at a time read/write efficient
β†’ Gas cost: Grows quadratically!
   (Zyada use karo β†’ Gas exponentially badhe!)
β†’ Default: All zeros
β†’ Per-call: Fresh memory har call mein

Opcodes:
MSTORE  : 32 bytes store karo
MSTORE8 : 1 byte store karo
MLOAD   : 32 bytes load karo

Gas cost trap:
   Memory[0-31]   : Cheap
   Memory[32-63]  : Slightly more
   Memory[0-999]  : Getting expensive
   Memory[0-9999] : Very expensive!

Hacker relevance:
   β†’ Large memory allocation = Gas exhaustion
   β†’ Return bomb attack!
     (External call returns huge data β†’ Caller's
      memory explodes β†’ Caller runs out of gas!)

3. Storage Permanent Blockchain State:

Storage = Permanent Hard Drive
          Blockchain pe FOREVER remain!

Properties:
β†’ Key-Value mapping
β†’ Key: 256-bit (slot number)
β†’ Value: 256-bit (32 bytes)
β†’ MOST EXPENSIVE operation in EVM!
β†’ Persists between transactions
β†’ Public! (Anyone can read!)

Gas costs:
SSTORE (new value)  : 20,000 gas  ← Very expensive!
SSTORE (update)     : 5,000 gas
SSTORE (delete/zero): -15,000 gas ← Refund!
SLOAD               : 800 gas

Hacker CRITICAL insight:
"Private" variables in Solidity
are stored in STORAGE β€”
which is PUBLIC on blockchain!

Example:
contract Secret {
    uint256 private secretNumber = 12345;
    // "private" sirf Solidity compiler ke liye hai!
    // EVM storage slot 0 mein publicly readable hai!
}

// Read karo:
w3.eth.get_storage_at(contract_address, 0)
// Output: 12345 β€” "Secret" exposed!

PART 3: Storage Slots Deep Dive!

Solidity mein variables storage mein
SLOTS mein store hote hain:

Slot 0, Slot 1, Slot 2... aise

contract Example {
    uint256 public a;        // Slot 0
    uint256 public b;        // Slot 1
    address public owner;    // Slot 2
    bool public paused;      // Slot 2 (packing!)
    uint256 public c;        // Slot 3
}

SLOT PACKING (Gas optimization):
   Ek slot = 32 bytes (256 bits)
   address = 20 bytes
   bool    = 1 byte
   Total   = 21 bytes β†’ FIT in one slot!
   β†’ Slot 2 mein DONO store honge!

Visual Storage Layout:
Slot 0: [                    a (32 bytes)                    ]
Slot 1: [                    b (32 bytes)                    ]
Slot 2: [    padding    ][owner (20 bytes)][paused (1 byte)  ]
Slot 3: [                    c (32 bytes)                    ]

Mappings aur Arrays Ka Slot:

contract StorageLayout {
    uint256 public x;           // Slot 0
    uint256[] public arr;       // Slot 1 (length)
    mapping(address => uint256) // Slot 2
        public balances;

    // arr[i] actual data kahan?
    // keccak256(1) + i  ← slot 1 ka hash + index

    // balances[addr] kahan?
    // keccak256(addr . 2)  ← addr + slot 2 ka hash
}
# Python mein storage read karo:
from web3 import Web3
from eth_abi import encode

w3 = Web3(Web3.HTTPProvider(
    "https://cloudflare-eth.com"
))

CONTRACT = "0xSomeContract"

# Simple slot read:
slot_0 = w3.eth.get_storage_at(CONTRACT, 0)
print(f"Slot 0: {slot_0.hex()}")

# Mapping ka slot calculate karo:
def get_mapping_slot(key_address, mapping_slot):
    """mapping(address=>uint) ka slot find karo"""
    key_padded = encode(
        ['address'], [key_address]
    )
    slot_padded = mapping_slot.to_bytes(32, 'big')
    combined = key_padded + slot_padded
    return Web3.keccak(combined)

user_slot = get_mapping_slot(
    "0xUserAddress",
    2  # balances is at slot 2
)
balance = w3.eth.get_storage_at(CONTRACT, user_slot)
print(f"User balance slot: {balance.hex()}")

# Real world use:
# CTF challenges mein "hidden" passwords
# Private variables expose karna
# Proxy contracts ka implementation address find

PART 4: Opcodes EVM Ki Language!

Opcode = Ek byte instruction EVM ke liye

Jaise assembly language CPU ke liye,
Opcodes hain EVM ke liye!

Total: ~140+ opcodes Ethereum mein

Categories:
1. Arithmetic      : ADD, SUB, MUL, DIV, MOD
2. Comparison      : LT, GT, EQ, ISZERO
3. Bitwise         : AND, OR, XOR, NOT, SHL, SHR
4. Stack           : PUSH1-32, POP, DUP1-16, SWAP1-16
5. Memory          : MLOAD, MSTORE, MSTORE8
6. Storage         : SLOAD, SSTORE
7. Control Flow    : JUMP, JUMPI, PC, STOP
8. System          : CALL, DELEGATECALL, STATICCALL
9. Blockchain Info : ADDRESS, BALANCE, CALLER,
                     CALLVALUE, TIMESTAMP, NUMBER
10. Logging        : LOG0, LOG1, LOG2, LOG3, LOG4
11. Contract       : CREATE, CREATE2, SELFDESTRUCT

Most Important Opcodes For Security:

OPCODE      | HEX  | GAS   | DESCRIPTION
------------|------|-------|---------------------------
STOP        | 0x00 | 0     | Execution stop
ADD         | 0x01 | 3     | a + b
MUL         | 0x02 | 5     | a * b
SUB         | 0x03 | 3     | a - b
DIV         | 0x04 | 5     | a / b (integer)
SDIV        | 0x05 | 5     | Signed division
MOD         | 0x06 | 5     | a % b
ADDMOD      | 0x08 | 8     | (a+b) % N
MULMOD      | 0x09 | 8     | (a*b) % N
LT          | 0x10 | 3     | Less than
GT          | 0x11 | 3     | Greater than
EQ          | 0x14 | 3     | Equal
ISZERO      | 0x15 | 3     | Is zero?
AND         | 0x16 | 3     | Bitwise AND
OR          | 0x17 | 3     | Bitwise OR
XOR         | 0x18 | 3     | Bitwise XOR
SHA3/KECCAK | 0x20 | 30+   | Keccak-256 hash
ADDRESS     | 0x30 | 2     | Current contract address
BALANCE     | 0x31 | 700   | Account balance
ORIGIN      | 0x32 | 2     | tx.origin ⚠️
CALLER      | 0x33 | 2     | msg.sender
CALLVALUE   | 0x34 | 2     | msg.value
CALLDATALOAD| 0x35 | 3     | Load calldata
CODESIZE    | 0x38 | 2     | Contract code size
TIMESTAMP   | 0x42 | 2     | block.timestamp ⚠️
NUMBER      | 0x43 | 2     | block.number
DIFFICULTY  | 0x44 | 2     | Block difficulty ⚠️
GASLIMIT    | 0x45 | 2     | Block gas limit
SLOAD       | 0x54 | 800   | Storage read
SSTORE      | 0x55 | 5000+ | Storage write πŸ’°
JUMP        | 0x56 | 8     | Unconditional jump
JUMPI       | 0x57 | 10    | Conditional jump
MLOAD       | 0x51 | 3     | Memory read
MSTORE      | 0x52 | 3+    | Memory write
PUSH1-32    | 0x60 | 3     | Push N bytes to stack
DUP1-16     | 0x80 | 3     | Duplicate stack item
SWAP1-16    | 0x90 | 3     | Swap stack items
LOG0-4      | 0xa0 | 375+  | Emit event
CREATE      | 0xf0 | 32000 | Deploy contract
CALL        | 0xf1 | 700+  | Call contract ⚠️
DELEGATECALL| 0xf4 | 700+  | Delegatecall ⚠️⚠️
STATICCALL  | 0xfa | 700+  | Read-only call
RETURN      | 0xf3 | 0     | Return data
REVERT      | 0xfd | 0     | Revert (return data)
SELFDESTRUCT| 0xff | 5000  | Destroy contract ⚠️

Dangerous Opcodes For Hackers:

1. ORIGIN (0x32) = tx.origin β†’ Phishing attack!
2. TIMESTAMP (0x42) = Miner manipulate kar sakta!
3. DIFFICULTY (0x44) = Randomness nahi β€” predictable!
4. CALL (0xf1) = Reentrancy entry point!
5. DELEGATECALL (0xf4) = Storage collision attack!
6. SELFDESTRUCT (0xff) = ETH force-send + code delete!
7. CREATE2 (0xf5) = Counterfactual deployment attack!

PART 5: Bytecode Solidity Se EVM Tak

Solidity Code β†’ Compilation β†’ Bytecode β†’ EVM Execute

STEP 1: Solidity Source Code
━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Simple.sol
pragma solidity ^0.8.0;

contract Simple {
    uint256 public value;

    function setValue(uint256 _val)
        external
    {
        value = _val;
    }
}

STEP 2: Compilation Output
━━━━━━━━━━━━━━━━━━━━━━━━━━
solc --bin Simple.sol

Bytecode (hex):
0x608060405234801561001057600080fd5b506101
3b806100206000396000f3fe608060405234801561
001057600080fd5b50600436106100365760003560
e01c80633fa4f2451461003b5780635524107714610059
...

STEP 3: EVM Execute
━━━━━━━━━━━━━━━━━━
60 80    β†’ PUSH1 0x80 (Stack: [128])
60 40    β†’ PUSH1 0x40 (Stack: [64, 128])
52       β†’ MSTORE     (Memory[64] = 128)
...

Bytecode Parts:

Smart Contract Bytecode has 3 parts:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     CREATION CODE                  β”‚
β”‚   Deploy karte waqt run hota hai   β”‚
β”‚   Constructor logic here           β”‚
β”‚   Runtime code ko memory mein load β”‚
β”‚   Returns runtime code             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              ↓ deploys
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     RUNTIME CODE                   β”‚
β”‚   Actual contract logic            β”‚
β”‚   Blockchain pe store hota hai     β”‚
β”‚   Har call pe yahi execute hota    β”‚
β”‚   Function dispatcher here        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              ↓ appended
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     METADATA HASH                  β”‚
β”‚   IPFS hash of source + ABI        β”‚
β”‚   Verification ke liye             β”‚
β”‚   Ignore kar sakte hain mostly     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

PART 6: Function Selector Kaise Kaam Karta Hai?

Jab tum contract function call karte ho,
EVM ko kaise pata kaunsa function run karna hai?

ANSWER: Function Selector!

Function Selector = Keccak256(function_signature)
                    ka PEHLE 4 BYTES

Example:
transfer(address,uint256)
   β†’ Keccak256("transfer(address,uint256)")
   β†’ 0xa9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b
   β†’ First 4 bytes: 0xa9059cbb

Calldata structure:
[4 bytes selector][32 bytes arg1][32 bytes arg2]...

Example:
transfer(0xBob, 1000)
β†’ 0xa9059cbb                              (selector)
  0000000000000000000000003f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE  (Bob's address padded)
  00000000000000000000000000000000000000000000000000000000000003E8  (1000 in hex)

Security Implication Selector Collision!

ATTACK: Function Selector Collision!

Two different functions can have
SAME 4-byte selector!

Example:
collate_propagate_storage(bytes16) β†’ 0x42966c68
burn(uint256)                      β†’ 0x42966c68
SAME SELECTOR!

Real Attack:
β†’ Proxy contract ka function
  Accidentally same selector as
  implementation contract ka dangerous function!
β†’ Wrong function execute ho jaata hai!

Tools to find collisions:
https://www.4byte.directory/
(Known function selectors database)

Python se:
from web3 import Web3

def selector(sig):
    return Web3.keccak(
        text=sig
    )[:4].hex()

print(selector("transfer(address,uint256)"))
# 0xa9059cbb

# Find collision:
sigs = [
    "withdraw(uint256)",
    "transfer(address,uint256)",
    "burn(uint256)",
    "mint(address,uint256)",
]
selectors = {}
for s in sigs:
    sel = selector(s)
    if sel in selectors:
        print(f"COLLISION! {s} == {selectors[sel]}")
    selectors[sel] = s

PART 7: Contract Decompiling Bytecode Se Logic Nikalo!

SCENARIO:
   Ek contract deployed hai Ethereum pe
   Source code verified nahi hai Etherscan pe
   Sirf bytecode available hai
   
   Kya kare?
   DECOMPILE KAR DO!

Tools:
1. Dedaub (https://app.dedaub.com) β€” Best!
2. Panoramix / Heimdall
3. Ethervm.io
4. Etherscan ka "Decompile Bytecode" feature

Example:
Raw bytecode input:
0x608060405260043610610041576000357c010000...

Decompiled output (human readable):
function transfer(address _to, uint256 _amount)
    public
{
    require(balances[msg.sender] >= _amount);
    balances[msg.sender] -= _amount;
    balances[_to] += _amount;
}

Not perfect Solidity β€” but readable logic!

Hands-On Decompilation:

# Tool 1: Foundry ka cast disassemble
# Install foundry first!
curl -L https://foundry.paradigm.xyz | bash
foundryup

# Contract bytecode disassemble:
cast disassemble 0x608060405234801561001057600080fd5b...

# Output:
# 0x00: PUSH1 0x80
# 0x02: PUSH1 0x40
# 0x04: MSTORE
# 0x05: CALLVALUE
# 0x06: DUP1
# 0x07: ISZERO
# ...

# Tool 2: Online β€” Etherscan
# Contract page β†’ Contract tab
# "Decompile Bytecode" button!
# (Agar verified nahi hai toh)

# Tool 3: Python β€” pyevmasm
pip install pyevmasm

python3
from pyevmasm import disassemble_hex
bytecode = "0x6080604052..."
print(disassemble_hex(bytecode))

PART 8: EVM Execution Step by Step Trace!

Ek simple function trace karte hain:

Solidity:
function add(uint a, uint b)
    public pure returns(uint)
{
    return a + b;
}

Call: add(3, 5)

EVM Execution Trace:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Step  | Opcode    | Stack           | Note
------|-----------|-----------------|------------------
1     | CALLDATALOAD | [3]          | Load arg 'a' = 3
2     | CALLDATALOAD | [5, 3]       | Load arg 'b' = 5
3     | ADD       | [8]             | 3 + 5 = 8
4     | RETURN    | []              | Return 8

Simple! Ab complex example:

Solidity:
function transfer(address to, uint amount)
    external
{
    require(balances[msg.sender] >= amount,
            "Insufficient");
    balances[msg.sender] -= amount;
    balances[to] += amount;
}

EVM steps (simplified):
1. CALLER          β†’ Stack: [msg.sender]
2. SLOAD (slot)    β†’ Stack: [sender_balance]
3. CALLDATALOAD    β†’ Stack: [amount, sender_balance]
4. LT              β†’ Stack: [balance < amount?]
5. ISZERO          β†’ Stack: [balance >= amount?]
6. JUMPI (revert)  β†’ Jump if check fails!
7. CALLER + SLOAD  β†’ Load sender balance
8. CALLDATALOAD    β†’ Load amount
9. SUB + SSTORE    β†’ Subtract & store
10. CALLDATALOAD   β†’ Load 'to' address
11. SLOAD          β†’ Load receiver balance
12. CALLDATALOAD   β†’ Load amount again
13. ADD + SSTORE   β†’ Add & store
14. STOP           β†’ Done!

Reentrancy bug yahan hai:
Step 9 ke pehle agar external call hota
β†’ Balance update se PEHLE re-enter possible!
(Article #20-21 mein full detail!)

PART 9: Tenderly Transaction Trace Tool

Tenderly = Professional EVM debugger
           Transaction ka har step dekho!

Use cases:
β†’ Bug reproduce karo
β†’ Exploit trace karo
β†’ Gas optimization
β†’ Failing transaction debug karo

Setup:
1. https://tenderly.co
2. Free account banao
3. "Simulator" tab

Transaction simulate karo:
{
  "from"  : "0xAttacker",
  "to"    : "0xVulnerableContract",
  "data"  : "0xa9059cbb...",
  "value" : "1000000000000000000",
  "gas"   : 300000
}

Output:
β†’ Step-by-step execution
β†’ Storage changes
β†’ Events emitted
β†’ Gas consumed per step
β†’ Internal calls
β†’ Revert reason (agar fail ho)

Real hacker use:
1. Old hack transaction hash copy karo
2. Tenderly mein paste karo
3. Exact execution dekho
4. Bug samjho
5. Similar bugs dhundho new protocols mein!

Example hacks to trace:
Euler Finance: 0x71f68d3...
Ronin Bridge : 0xe9e7cea...

PART 10: Python EVM Interact Karo!

from web3 import Web3
import json

w3 = Web3(Web3.HTTPProvider(
    "https://cloudflare-eth.com"
))

# ─── 1. Contract Code Read ────────────────
contract_addr = Web3.to_checksum_address(
    "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
)  # USDC

# Bytecode fetch karo:
bytecode = w3.eth.get_code(contract_addr)
print(f"Bytecode length: {len(bytecode)} bytes")
print(f"First 20 bytes: {bytecode[:20].hex()}")

# ─── 2. Storage Slots Read ────────────────
# Slot 0 read:
slot0 = w3.eth.get_storage_at(contract_addr, 0)
print(f"\nSlot 0: {slot0.hex()}")

# ─── 3. Transaction Trace ─────────────────
# (Agar archive node available ho)

# ─── 4. Event Logs Read ──────────────────
# Transfer events last 100 blocks:
transfer_topic = Web3.keccak(
    text="Transfer(address,address,uint256)"
).hex()

logs = w3.eth.get_logs({
    "fromBlock" : w3.eth.block_number - 100,
    "toBlock"   : "latest",
    "address"   : contract_addr,
    "topics"    : [transfer_topic]
})

print(f"\nTransfer events (last 100 blocks):")
for log in logs[:5]:
    print(f"  TxHash: {log['transactionHash'].hex()}")
    print(f"  Block : {log['blockNumber']}")

# ─── 5. Function Selector ─────────────────
def get_selector(sig):
    return Web3.keccak(text=sig)[:4].hex()

print("\nCommon selectors:")
funcs = [
    "transfer(address,uint256)",
    "approve(address,uint256)",
    "balanceOf(address)",
    "withdraw(uint256)",
    "deposit()",
]
for f in funcs:
    print(f"  {get_selector(f)} β†’ {f}")

# ─── 6. Call Contract Function ────────────
abi = [{
    "name"   : "totalSupply",
    "type"   : "function",
    "inputs" : [],
    "outputs": [{"type": "uint256"}],
    "stateMutability": "view"
}]

contract = w3.eth.contract(
    address=contract_addr, abi=abi
)
supply = contract.functions.totalSupply().call()
print(f"\nUSDC Total Supply: "
      f"{supply / 10**6:,.2f} USDC")

PART 11: EVM Security Key Takeaways!

SECURITY INSIGHT 1: Storage is PUBLIC!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
"Private" Solidity variable β‰  Hidden data!
Anyone can read any storage slot!

Bug hunting tip:
β†’ Unverified contracts ka storage read karo
β†’ "Hidden" admin keys, prices, flags find karo
β†’ Proxy contracts ka implementation address find

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

SECURITY INSIGHT 2: Selector Collision
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Two functions β†’ Same 4-byte selector
Wrong function called unexpectedly!

Bug hunting tip:
β†’ Proxy + implementation selectors compare karo
β†’ Collision tool use karo:
   https://openchain.xyz/signatures

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

SECURITY INSIGHT 3: Gas Manipulation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Gas griefing attacks:
β†’ Return bomb: Huge return data
β†’ Out of gas: Nested calls
β†’ Block stuffing: Fill block gas

Bug hunting tip:
β†’ External calls ke gas limits check karo
β†’ Unbounded loops dhundho
β†’ Return data handling check karo

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

SECURITY INSIGHT 4: Dangerous Opcodes
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DELEGATECALL β†’ Storage collision possible
SELFDESTRUCT β†’ Force ETH + code wipe
TIMESTAMP    β†’ Miner manipulate kar sakta
CREATE2      β†’ Predictable address attack

Bug hunting tip:
β†’ DELEGATECALL ke sare uses check karo
β†’ SELFDESTRUCT impact analyze karo
β†’ Timestamp dependence flag karo

PART 12: Hands-On Challenges!

# ─── Task 1: Ethernaut Level 1 ────────────
# https://ethernaut.openzeppelin.com/level/1
# Contract ka bytecode dekho Etherscan pe
# Function selectors identify karo
# Fallback function dhundho!

# ─── Task 2: Storage Slot Read ────────────
# Etherscan pe koi unverified contract dhundho
# Python se storage slots 0-5 read karo
# Koi interesting data milta hai?

# ─── Task 3: Decompile Practice ───────────
# https://app.dedaub.com
# Paste karo kisi contract ka bytecode
# Kaunse functions hain identify karo
# Hidden admin functions?

# ─── Task 4: Function Selectors ───────────
python3
from web3 import Web3
# Yeh selectors identify karo:
sels = [
    "0x095ea7b3",
    "0xa9059cbb",
    "0x23b872dd",
    "0x70a08231",
    "0x18160ddd",
]
# Hint: ERC-20 standard functions!
# https://www.4byte.directory mein dhundho!

# ─── Task 5: Tenderly Trace ───────────────
# Famous hack trace karo:
# Euler Finance hack tx:
# 0x71f684...
# Tenderly simulator mein paste karo
# Har step samjho!

# ─── Task 6: EVM Playground ───────────────
# https://www.evm.codes/playground
# Opcodes manually run karo!
# PUSH1 3, PUSH1 5, ADD β†’ Result kya?

Quick Revision

πŸ–₯️  EVM       = Ethereum Virtual Machine
               (Deterministic, isolated, metered)

πŸ“š 3 Memory Types:
   STACK    β†’ Temporary, 256-bit items, free
   MEMORY   β†’ Temporary per-call, byte array
   STORAGE  β†’ PERMANENT, key-value, EXPENSIVE!

πŸ”‘ Key Points:
   "Private" = NOT hidden! (Storage is public!)
   Gas       = Computation meter (prevents DoS)
   Bytecode  = Actual deployed code
   Opcodes   = EVM ke instructions (~140 types)

⚠️  Dangerous Opcodes:
   ORIGIN      β†’ tx.origin (phishing!)
   TIMESTAMP   β†’ Miner manipulate kar sakta
   DELEGATECALL→ Storage collision attack!
   SELFDESTRUCT→ ETH force-send + code delete
   CALL        β†’ Reentrancy entry point!

🎯 Function Selector = First 4 bytes of keccak(sig)
   Collision possible β†’ Wrong function execute!

πŸ•΅οΈ  Tools:
   Dedaub    β†’ Bytecode decompile
   Tenderly  β†’ Transaction trace
   cast      β†’ Foundry CLI
   4byte.dir β†’ Selector database

Meri Baat…

Ek CTF challenge tha Contract unverified tha source nahi thaΰ₯€

Sabne socha: "Nahi padh sakte!"

Maine:

# Bytecode Etherscan se copy kiya
# Dedaub mein paste kiya
# Decompiled output padha:

function secret_withdraw() public {
    require(
        storage[0x1337] == msg.sender
    );
    payable(msg.sender).transfer(
        address(this).balance
    );
}

# Storage slot 0x1337 read kiya:
python3 β†’ get_storage_at(addr, 0x1337)
# Output: 0x0000...MyAddress (meri hi address!)
# Contract mujhe hi winner maanta tha!

Prize: 1 ETH β‰ˆ $3,500! πŸŽ‰

EVM knowledge = Hidden information access!
Hidden = CTF challenge mein free ETH!
Real world = Hidden admin keys, paused flags,
             secret prices β€” bug bounty material!

Agle article mein Solidity seekhenge β€”
Ab tum jaante ho "under the hood" kya hota hai β€”
Solidity bahut easy lagegi! πŸš€

Article #5 mein: Solidity Basics Part 1 Language fundamentals, data types, functions hacker ki nazar se!

HackerMD β€” Web3 Security Researcher GitHub: BotGJ16 | Medium: @HackerMD

Previous: Article #3 Ethereum: Accounts & Transactions Next: Article #5 Solidity Basics Part 1

#EVM #Ethereum #Opcodes #Web3Security #Bytecode #BugBounty #Hinglish #HackerMD