Sem 7

Cheat Sheet

One dense page for the night before the exam: blockchain basics, Bitcoin block and transaction facts, wallets, PoW/PoS/PoB, Bitcoin Script, Ethereum accounts and gas, then every Docker, JSON-RPC, Foundry, cast and anvil command and a Solidity syntax reference.

Blockchain fundamentals (L01)Search on YouTube

  • Blockchain: a cryptographically secure, open, distributed ledger. A distributed public database of immutable records called blocks, secured with cryptography. Each node stores and updates it independently and processes every transaction.
  • Blockchain is NOT Bitcoin, and NOT only about cryptocurrency.
  • Why blockchain: high transaction fees, double spending, net frauds, poor data recovery.
  • Block holds 4 details: hash of the previous block, transaction data, nonce, hash.
  • Features / digital identity: SHA-256 hash, digital signature, public and private key, Proof of Work, mining.
  • Hash function: fixed-length output (digest, "compression function"; n-bit output = n-bit hash), efficient, one-way, collision resistant. One character changed → completely different digest.
  • Digital signature: sign = hash the message, encrypt the hash with the signer's private key, attach. Verify = decrypt with the public key, re-hash the data, the two hashes should match. Bitcoin uses ECDSA.
  • Proof of Work: find a nonce so the hash is at or below a target. Miners try about 20.6 quadrillion nonces. First solver gets the reward; the block is added.
  • Mining reward: 3.125 BTC per block, halved every 210,000 blocks (about 4 years).
  • Syllabus base technologies: Docker, hash function, digital signature (ECDSA), zero-knowledge proof.
Type of blockchain (L09)ControlExamples
PublicPermissionless, anyone joinsBitcoin, Ethereum, Litecoin
PrivateOne organisationHyperledger Fabric, Corda, MultiChain
Consortium (federated)Group of organisationsQuorum, Energy Web Chain, We.trade
HybridPart private, part publicXinFin XDC, Dragonchain, IBM Food Trust
MainnetTestnet
PurposeReal useDevelopment and testing
TokensReal valueFree from faucets, no value
ExampleEthereum MainnetSepolia, Goerli

L1 = base chain (Bitcoin, Ethereum), source of truth, slow under load. L2 = faster layer settling on L1 (Lightning, Arbitrum, Polygon). Overlay = adds features without changing L1 (Ordinals/BRC-20, Counterparty).

Bitcoin and the white paper (L02)Search on YouTube

  • Bitcoin = P2P network + public transaction ledger + rules for independent validation + mechanism for decentralised consensus. Coins are created by mining. Not managed by any bank.
  • Electronic coin = a chain of digital signatures. Each owner signs a hash of the previous transaction and the next owner's public key.
  • Block header (Block j): Version, hash(header j−1), Merkle_Root, Timestamp, Target_Hash_nBits, Nonce. Transactions are hashed in a Merkle tree; only the root goes in the header.
  • Target: one new block about every 10 minutes. Header without transactions ≈ 80 bytes → 80 × 6 × 24 × 365 ≈ 4.2 MB per year.
  • Incentive: first transaction of a block (coinbase) creates new coins for the miner; plus transaction fees (input value − output value).
  • Combining and splitting value: multiple inputs, at most two outputs (payment and change).
  • Privacy: keep public keys anonymous; use a new key pair per transaction.
  • SPV (Simplified Payment Verification): keep only block headers, check a transaction with its Merkle branch.
  • PoW is "one-CPU-one-vote"; the longest chain is the majority decision. Secure while honest nodes control more CPU power than attackers.

Network steps (consensus in Bitcoin)

  1. New transactions are broadcast to all nodes.
  2. Each node collects them into a block.
  3. Each node works on a difficult PoW for its block.
  4. A node that finds a PoW broadcasts the block.
  5. Nodes accept it only if all transactions are valid and not already spent.
  6. Nodes show acceptance by mining the next block using its hash as the previous hash.

Wallets (L03)Search on YouTube

  • A wallet keeps private keys safe and accessible. It is the main user interface of Bitcoin (like a browser).
  • Hot wallet: online, convenient, easier to hack. Cold wallet: offline physical device (USB-like), more secure.
CategoryNotes
DesktopWindows, macOS; some security disadvantages
MobileiOS, Android; ease of use
WebKeys on a third-party server; avoid large amounts
HardwareSelf-contained wallet on special hardware
PaperKeys printed for long-term storage

Common wallets: Trezor Model T, Bitcoin Core, Electrum, Coinbase, Ledger Nano X, Exodus, Mycelium. Getting bitcoin: buy online (Coinbase), in person (Coin ATM Radar, LibertyX, LocalBitcoins), or earn (games, jobs, reading, writing). Price is set by the market: about 6 cents at start, 1inFeb2011,over1 in Feb 2011, over 140 in April 2013, over 1,000byDec2013,about1,000 by Dec 2013, about 27,159.60 in 2023.

Bitcoin stack: hardware → P2P network and OS → Bitcoin blockchain protocol → wallet/exchange app. Ethereum stack adds Ethereum blockchain + EVM → smart contracts (application framework) → end-user verticals.

Consensus algorithms (L04)Search on YouTube

  • PoW origin: Dwork and Naor (1992), pricing via processing to fight junk mail. Key feature: asymmetry, hard to do, easy to check.
  • Hashcash (Adam Back, 2002): stamp in the email header X-Hashcash: version:bits:date:resource:extension:rand:counter, for example 1:20:081022:.... Receiver checks date (within two days), email address, random string not reused (replay), and that the 160-bit SHA-1 hash starts with 20 zero bits.
  • Bitcoin PoW: BH = Hash(PH : MR : N), block hash must start with enough zeros (difficulty).
AttackDefence
TamperingAttacker must redo more work than the whole chain
Double spending (BTC 10 to Bob and Carol)Irreversible transactions; validate against the chain
Sybil (flood network with own nodes)Diversify connections
DoS (flood a node with data)No forwarding of orphan blocks, double spends or duplicates; disconnect noisy peers; 1 MB block size; 10,000-byte script limit
  • Monopoly problem: more hardware means more blocks; tragedy of the commons; few rich miners could control the network. PoW also uses huge power.
  • PoS: proposed 2011 on Bitcoin Forum. Mining chance ∝ coins held (1% of coins → 1% of blocks). Attack needs many coins. Variants: randomisation + stake (Nxt, BlackCoin), coin-age = coins × days held (Peercoin).
  • PoB: burn coins by sending them to a verifiably unspendable address. Uses virtual resources.
PoWPoSPoB
Do work to mine a blockAcquire enough stake to mineBurn wealth to mine
Physical resources: CPU power, timeNo external resource; take part in transactionsVirtual/digital resources (coins)
Power hungryPower efficientPower efficient

Work, Stake, Burn: "We Spend Bitcoin".

Bitcoin Script (L05)Search on YouTube

  • Bitcoin is permissionless: no account; the wallet makes keys; the address (from the public key) is used, not identity. Many addresses per person. Sample: 1PHYrmdJ22MKbJevpb3MBNpVckjZHt89hz.
  • Sending: Bob gives his address; Alice puts address and amount in a transaction, signs with her private key, announces her public key, broadcasts.
  • Script: simple, compact, stack-based, processed left to right, not Turing complete (no loops). Recorded with each transaction; says how the next owner can spend.
  • P2PKH: scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG, scriptSig: <sig> <pubKey>. Run scriptSig then scriptPubKey on an empty stack.
StepStack after (top on right)
push <sig>, <pubKey>sig, pubKey
OP_DUPsig, pubKey, pubKey
OP_HASH160sig, pubKey, hash(pubKey)
push <pubKeyHash>sig, pubKey, hash(pubKey), pubKeyHash
OP_EQUALVERIFYsig, pubKey (fails if hashes differ)
OP_CHECKSIGTRUE if signature valid

Ethereum (L06)Search on YouTube

  • Decentralised, programmable blockchain. ETH transfers + smart contracts run by the EVM. Apps: dApps, DeFi, stablecoins/tokens, NFTs, DAOs, gaming, identity.
  • Architecture: users/wallets sign transactions → execution layer (EVM) → consensus layer (validators, finality) → blocks record state transitions.
  • Tx lifecycle: create and sign → broadcast (wait in tx pool) → validator includes it in a block → executes and changes state → later blocks confirm.
  • Confirmations = current block number − transaction block number.
  • Consensus: Proof of Stake; validators stake ETH, propose and attest blocks. Finality is distinct from confirmations.
  • State: account info, balances, contract code, contract storage.
AccountControlled byHas
EOAPrivate key (MetaMask, seed phrase)Address + balance + nonce, no code
ContractIts code, no private keyAddress + balance + code + storage

Fee=Gas used×Effective gas price\text{Fee} = \text{Gas used} \times \text{Effective gas price}

  • ETH transfer ≈ 21,000 gas; contract calls more. Unused gas = limit − used (29,022 − 29,010 = 12, 99.96%).
  • 1 Gwei=10−91\ \text{Gwei} = 10^{-9} ETH; 1 ETH=10181\ \text{ETH} = 10^{18} wei.
  • Receipt status 0x1 success, 0x0 reverted; type 0x2 = EIP-1559.

Docker commands (L07, L08)Search on YouTube

docker --version ; docker info ; docker --help
docker pull ubuntu:24.04            # default tag latest
docker images                      # = docker image ls
docker rmi alpine ; docker image prune
docker create --name cont1 alpine  # created, not started
docker start cont1 ; docker stop cont1
docker run --name cont3 -d alpine sleep infinity   # run = create + start
docker run -d -p 8080:80 --name mysite1 mysite     # host:container
docker ps ; docker ps -a ; docker ps -q ; docker ps -n 5
docker exec -it cont3 /bin/sh
docker logs -f cont3 ; docker inspect cont3 ; docker container stats
docker rm cont3 ; docker rm -f cont3
docker build -t mycont1 . ; docker build -f customalpine.txt -t mycont2 . ; docker build -t img . --no-cache
docker history mycont2
docker login -u <user> ; docker push <user>/<image> ; docker search <image>
FROM python:3.12
LABEL app="payment-service" version="2.1.0"
ENV APP_ENV=production          # config only, never secrets
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 5000                     # documentation only; use -p
ENTRYPOINT ["python"]           # fixed executable; run args appended
CMD ["app.py"]                  # default args; replaced by run args
  • A container lives while its PID 1 runs. Exec form ["..."] makes the app PID 1; shell form runs /bin/sh -c.
docker volume create vol_data ; docker volume ls ; docker volume inspect vol_data   # /var/lib/docker/volumes/vol_data/_data
docker run -it --name cont_vol --mount type=volume,source=vol_data,target=/mydata nginx bash
docker run -it --name cont_vol2 -v vol_data:/mydata nginx bash
docker run -d --name cont_bind1 -p 8001:80 --mount "type=bind,src=.,target=/usr/share/nginx/html" nginx
docker run -d --name cont_bind2 -p 8002:80 -v ${PWD}:/usr/share/nginx/html nginx
docker network ls                                   # bridge, host, none
docker inspect network bridge                       # 172.17.0.0/16, gw 172.17.0.1
docker network create --driver bridge mynetwork     # 172.18.0.0/16, DNS by name
docker network connect mynetwork cont1 ; docker network disconnect bridge cont1
docker run -itd --network host --name cont4 nginx
docker network create -d macvlan --subnet <s> --gateway <g> -o parent=<nic> mymacvlan
docker network create -d ipvlan --subnet <s> --gateway <g> -o parent=<nic> my_ipvlan

Stop keeps container data; rm deletes it. Volume = Docker-managed, named; bind mount = exact host path, live edits. Default bridge: DHCP yes, DNS no. Macvlan needs promiscuous mode; ipvlan shares the MAC; overlay = Swarm; none = isolated.

Minichain (L09)Search on YouTube

Block = index, timestamp, transactions, previous_hash, nonce, hash (SHA-256 of json.dumps(..., sort_keys=True)). Genesis: index 0, previous_hash "0". Tx → pending_transactions (mempool). Mine: increment nonce until hash starts with "0" * 3. Validate: hash matches, link matches, work done. Routes: POST /transactions, POST /mine, GET /chain, GET /pending, GET /validate, POST /tamper, port 5000.

JSON-RPC and Sepolia (L10)Search on YouTube

{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}
Invoke-RestMethod -Uri $RPC_URL -Method Post -ContentType "application/json" -Body $body
$response | ConvertTo-Json -Depth 5
[Convert]::ToInt64("B13404", 16)
GroupMethods
Networketh_chainId (Sepolia 0xaa36a7 = 11155111), eth_blockNumber, eth_getBlockByNumber, eth_getBlockByHash, eth_gasPrice (wei), eth_getBlockTransactionCountByNumber
Accounteth_getBalance, eth_getTransactionCount (nonce), eth_getCode (0x = EOA), eth_getStorageAt
Transactioneth_getTransactionByHash, eth_getTransactionReceipt
Sendeth_sendRawTransaction

Faucet: Google Cloud Web3 Sepolia (0.05 ETH). Explorer: sepolia.etherscan.io. RPC provider: Alchemy https://eth-sepolia.g.alchemy.com/v2/<KEY>.

Foundry, Anvil and cast (L11)Search on YouTube

wsl --install -d Ubuntu
sudo apt update && sudo apt install curl git build-essential -y
curl -L https://foundry.paradigm.xyz | bash          # installs foundryup only
echo 'export PATH="$PATH:$HOME/.foundry/bin"' >> ~/.bashrc && source ~/.bashrc
foundryup                                            # forge, cast, anvil, chisel, solar
anvil --version
anvil                                                # chain 31337, 127.0.0.1:8545, 10 × 10,000 ETH
cast balance 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 --rpc-url http://127.0.0.1:8545
cast chain-id ; cast block-number ; cast block latest ; cast block 1
cast nonce <addr> ; cast code <addr> ; cast storage <addr> <slot>
cast tx <hash> ; cast receipt <hash> ; cast gas-price ; cast client
cast call <addr> <data> ; cast send ... ; cast publish <signed-tx> ; cast estimate ... ; cast logs ...
cast rpc eth_accounts ; cast rpc net_version ; cast rpc eth_feeHistory ...
forge init p ; forge build ; forge test ; chisel
ToolRole
forgeBuild, test (in Solidity), deploy
castCLI to EVM chains over JSON-RPC
anvilLocal Ethereum node
chiselSolidity REPL

MetaMask custom network: Anvil Local, http://127.0.0.1:8545, chain ID 31337, ETH. Account #0 key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 (public, never use for real funds).

Solidity syntax reference (L12, L13, L14)Search on YouTube

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract UniversityDegree {
    address public university;                       // 20-byte identity
    uint256 public constant MAX_STUDENTS = 100;      // fixed at compile time
    address public immutable deployer;               // set once in constructor

    struct Certificate {                             // template, no storage yet
        uint256 certificateId;
        string studentName;
        bool isValid;
    }
    mapping(uint256 => Certificate) public certificates;   // key => value

    constructor() {                                  // runs once at deployment
        university = msg.sender;
        deployer = msg.sender;
    }

    function issue(uint256 _id, string memory _name) public {
        require(msg.sender == university, "Only university can issue");   // check first
        certificates[_id] = Certificate(_id, _name, true);                 // mapping[key]
    }

    function isValid(uint256 _id) external view returns (bool) {           // read-only
        return certificates[_id].isValid;                                  // mapping[key].field
    }

    function makeId(uint256 roll, uint256 year) public pure returns (bytes32) {   // no state
        return keccak256(abi.encodePacked(roll, year));
    }

    function _helper() private {}                    // this contract only
    function _shared() internal {}                   // this contract + children
}
Value typeUseExample
uint256Non-negative integers25
int256Signed integers-10
boolTrue/falsetrue
stringText (dynamic)"Alice"
addressAccount0x123...
VisibilityOutsideInsideChild
publicYesYesYes
externalYesNoNo
internalNoYesYes
privateNoYesNo
ModifierReads stateWrites stateGas (external call)
(none)YesYesTransaction, gas
viewYesNoFree
pureNoNoFree
Data locationLikeLifetime
storageHard drivePermanent (state variables)
memoryRAMOne call, mutable
calldataRead-only mailboxOne call, read-only, cheaper
stackCPU registers1024 slots × 32 bytes
codeROMBytecode; constant/immutable
  • public state variable → free auto getter. Writing state → signed transaction + gas.
  • msg.sender = current caller (changes per call); stored address = authority.
  • require(cond, "msg") false → whole transaction reverts.
  • Mappings: unset keys return defaults; lookup only, no length or iteration.
  • Remix: Remix VM (in-browser, 100 fake ETH accounts), Injected Provider (MetaMask), Custom HTTP Provider (Anvil). ABI = JSON interface; creation vs runtime bytecode. Blue button = call, orange = transaction.