Web3Sec
Concepts
- Blockchain → A blockchain is a decentralized, distributed ledger that records transactions in a secure, transparent, and tamper-proof way.
- A public blockchain is a decentralized, permissionless network where anyone can participate, view, and validate transactions.
- A private blockchain is a permissioned network where access is restricted to selected participants, typically managed by a single organization or consortium.
- Blockchain transactions are verified through a decentralized process that ensures their validity and consistency across the network. This involves cryptographic checks, consensus mechanisms, and coordination among nodes. Here's a step-by-step explanation:
- NFT → Non-Fungible Token
- a unique digital asset that represents ownership of a specific item stored on a blockchain.
- Decentralized → No single entity or central authority has control over the operations or data. Instead, power and decision-making are distributed among multiple nodes or participants in the network
- Decentralization is the process of distributing power and authority among all participants in a network.
- DAO → Decentralized Autonomous System → A DAO is an organization that operates on a blockchain, governed by rules encoded in smart contracts, without a central authority.
- Decisions are made collectively by members, typically through a token-based voting mechanism.
- In Web3, Digital Identity is not 100% connected.
- Ethereum → Blockchain platform and runtime environment.
- Facilitates decentralized apps and transactions.
- Smart contracts run on the EVM.
- End-users interact with Ethereum via wallets (e.g., MetaMask).
- Core infrastructure for smart contracts and DApps.
- Smart Contract → A smart contract is a self-executing program stored on a blockchain, with the terms of the agreement between parties directly written into code.
- Once deployed, smart contracts automatically execute predefined actions when specific conditions are met, without requiring intermediaries.
Key Differences:
Feature | Web2 | Web3 |
---|---|---|
Ownership | Platforms own user data. | Users own their data and digital assets. |
Infrastructure | Centralized servers controlled by companies. | Decentralized networks using blockchain. |
Data Control | Companies monetize user data (e.g., ads, tracking). | Users control their data via encryption. |
Identity | Centralized login (e.g., email, social accounts). | Decentralized identity (e.g., crypto wallets). |
Monetization | Companies profit from user interactions. | Users and creators directly earn tokens/rewards. |
Applications | Apps rely on centralized services. | DApps run on decentralized blockchains. |
Censorship | Platforms can remove content at will. | Content is resistant to censorship. |
Economy | Primarily fiat-based transactions. | Native digital economies (cryptocurrencies). |
How Web3 enhance Privacy:
- Decentralized Identity (Self-Sovereign Identity) → A user can authenticate on a DApp using their Ethereum wallet without revealing their real-world identity.
- Data Ownership → In Web3, users own their data and can decide who can access or use it. Data is stored in decentralized systems (e.g., IPFS, Arweave) rather than centralized servers.
- With protocols like Ocean Protocol, users can monetize their data on their terms without exposing it to centralized platforms.
- Users can grant and revoke access to their data as needed.
- Encryption by Default → Web3 uses public and private key cryptography to secure user interactions.
- Transactions and messages are encrypted, ensuring that only intended parties can access the data.
- Messaging apps like Status use decentralized, encrypted communication to prevent eavesdropping.
- Pseudonymity → - Web3 users interact with platforms and other users using wallet addresses (e.g., 0x1234...abcd) rather than real-world identities.
- A user can trade NFTs or participate in a DAO without revealing their name or other personal details.
- Zero-Knowledge Proofs (ZKPs) → ZKPs allow users to prove the validity of a statement (e.g., "I am over 18") without revealing the underlying data (e.g., date of birth).
- A user can prove eligibility for a financial service without sharing income details or other private information.
- No Centralized Tracking → Web3 eliminates the need for centralized intermediaries that track user behavior (e.g., cookies and ads in Web2).
- Decentralized marketplaces like OpenBazaar allow peer-to-peer trading without tracking user activities.
- Decentralized Data Storage → Data is distributed across multiple nodes in decentralized storage networks (e.g., Filecoin, Storj) instead of centralized servers.
Consensus Mechanisms
- A consensus mechanism is a protocol that enables all participants (nodes) in a decentralized network to agree on the validity and order of transactions, ensuring a unified and tamper-proof ledger without the need for a central authority.
- Proof of Work (PoW) → Miners compete to solve complex mathematical problems using computational power.
- The first to solve the problem adds the new block to the blockchain and is rewarded.
- It secures the network through computational difficulty.
- It prevents tampering since altering a block would require re-mining all subsequent blocks.
- Ex. Bitcoin, Ethereum (pre-Merge).
- Proof of Stake (PoS) → Validators lock up (stake) a certain amount of cryptocurrency to participate.
- Validators are chosen to create new blocks and validate transactions based on the size of their stake and other factors (e.g., randomization).
- It reduces energy consumption compared to PoW.
- It aligns validators’ incentives with network health (bad actors lose their stake).
- Ex. Ethereum (post-Merge), Cardano, Solana.
- Proof of Authority (PoA) → A limited number of trusted validators are pre-approved to produce blocks.
- Solidity → Solidity is a high-level programming language used for writing smart contracts on the Ethereum blockchain.
- It was designed specifically for creating decentralized applications (DApps) and interacting with Ethereum Virtual Machine (EVM).
- Similar to JS or C++
- pragma solidity statement → used to specify the version of the Solidity compiler that should be used to compile the contract. It ensures compatibility and proper compilation.
- Ethereum Virtual Machine → A decentralized, runtime environment that executes smart contracts and manages the state of the Ethereum blockchain.
- The EVM runs on every node in the Ethereum network, ensuring consensus on the blockchain state.
- Components:
- Accounts → Contain smart contract code and are controlled by their code.
- Storage → Persistent storage for smart contracts (key-value storage).
- Gas → A measure of computational work required to execute transactions or operations.
- Opcodes → Low-level instructions executed by the EVM (e.g.,
ADD
,MUL
,SSTORE
).
- Smart Contract → Self Executing Code stored on Blockchain
- Executed the predefined actions automatically when conditions are met.
- Ex. If Alice sends 1 ETH to the contract, send Bob the ownership of an NFT.
- The code and its execution are publicly visible on the blockchain.
- Examples:
- DeFi (Decentralized Finance) → Lending and borrowing
- Aave smart contracts automatically manage loans, calculate interest, and liquidate collateral if conditions aren't met.
- NFT Marketplaces → Ownership transfer and royalties.
- On OpenSea, a smart contract transfers an NFT to the buyer and sends a royalty to the creator when an NFT is sold.
- Voting → Transparent elections
- A DAO uses smart contracts to tally votes and enforce outcomes automatically.
- DeFi (Decentralized Finance) → Lending and borrowing
- The DIO Hack → The DAO’s smart contract had a “reentrancy bug.”
- This allowed an attacker to repeatedly call a function before the previous execution was complete, draining funds from the contract.
- This created an infinite loop of withdrawals, stealing 3.6 million ETH.
- Vulnerabilities:
- Reentrancy → An attacker repeatedly calls a vulnerable function before the first call is finished, causing unexpected behavior such as draining funds.
- A DeFi lending platform allows users to withdraw funds. An attacker deploys a malicious contract that calls the withdrawal function repeatedly before the platform updates the balance, draining the entire pool.
- Integer Overflow and Underflow → When calculations exceed the maximum or minimum limits of an integer type, causing unexpected results.
- Ex.
uint8 x = 255; x += 1;
causesx
to wrap to 0 (overflow). - A token contract calculates rewards using
uint256
. IftotalSupply - reward
underflows, it wraps around to a huge number, causing the reward system to distribute tokens incorrectly.
- Ex.
- Unchecked External Calls → External contract calls may fail or behave maliciously, leading to unpredictable results.
- Ex. A contract sends funds to an external address without verifying success.
- A contract sends funds to an external address without verifying success. A malicious contract rejects the transfer, causing the entire transaction to fail and locking up other funds in the contract.
- Denial of Service (DoS) → An attacker prevents the contract from functioning properly by exploiting logic that depends on external factors.
- Ex. A malicious contract refuses Ether transfers in a function dependent on such transfers.
- A lottery smart contract transfers Ether to the winner's address. An attacker submits a malicious contract as the winner that rejects Ether transfers, preventing the contract from completing other transactions.
- Lack of Access Control → Functions that modify critical state variables are exposed to unauthorized users.
- Ex. Failing to restrict function access.
- An admin function to mint tokens is accidentally left public. An attacker calls the function, minting an unlimited number of tokens and crashing the token's value.
- Front-Running → Attackers exploit the ability to see pending transactions in the mempool to execute profitable transactions first.
- Ex. A user submits a transaction to buy a token. An attacker sees it and submits a higher gas fee transaction to buy first.
- A user submits a transaction to buy tokens at a specific price. An attacker sees the transaction in the mempool and submits a higher-gas transaction to buy the tokens first, increasing the price.
- Hardcoded Gas Limits → Fixed gas limits for external calls can lead to failures as gas requirements change.
- Ex.
recipient.call{gas: 5000, value: amount}(""); // May fail if 5000 gas is insufficient
- A multisig wallet sends funds using a hardcoded gas limit. Over time, the gas requirements for transactions increase, causing fund transfers to fail.
- Ex.
- Insecure Randomness → Using predictable values for randomness allows attackers to manipulate outcomes.
- Ex. A gambling DApp uses
block.timestamp
to generate random numbers. An attacker manipulates the timestamp by mining blocks, consistently winning games.
- Ex. A gambling DApp uses
- Insufficient Input Validation → Failing to validate user input can lead to unintended behavior or exploits.
- Ex. Fails to check sender's balance before sending money
- A token contract’s
transfer
function does not check for sufficient balances. A user transfers more tokens than they own, causing incorrect balances and potential insolvency.
- Self-Destruct Vulnerabilities → Contracts can be destroyed, potentially allowing attackers to reclaim Ether or alter behavior.
- Ex. A developer includes a
selfdestruct
function for debugging and forgets to restrict access. An attacker calls the function, destroying the contract and reclaiming any Ether stored in it.
- Ex. A developer includes a
- 51% Attack → A 51% attack occurs when a single entity or group of malicious actors gains control of more than 50% of a blockchain network's mining or validation power.
- This control allows the attackers to manipulate the blockchain, undermining its integrity and trustworthiness.
- Reentrancy → An attacker repeatedly calls a vulnerable function before the first call is finished, causing unexpected behavior such as draining funds.
Cryptography
- Markle Tree → a cryptographic data structure used to efficiently and securely verify the integrity of data in a blockchain
- Each data block (e.g., a transaction) is hashed to create a leaf node.
- Hashes of two child nodes are concatenated and hashed again to form their parent node.
- This process repeats until a single hash (Merkle Root) remains.