Understanding the magic and the traps of smart contracts!
Hello again, young blockchain explorer! π In Module One, we discovered what blockchain is and how it works. You learned about blocks, hashes, and why blockchain is like a digital notebook that cannot be changed. Now, it's time to meet the heart of blockchain applications: Smart Contracts!
Smart contracts are like digital promises that automatically happen when conditions are met. They're powerful, fast, and don't need a middleman. But just like any powerful tool, they can have bugs and weaknesses that hackers love to exploit. That's why we need to understand vulnerabilities and how to audit them.
In this module, we'll explore what smart contracts are, how they are written, and the most common mistakes that lead to hacks. We'll also learn about the audit process β how experts check smart contracts for problems before hackers can find them. Think of it like learning to drive a car and also learning how to check the brakes and engine to stay safe!
Let's dive into the world of smart contracts! π
After finishing this module, you will be able to:
In the village of Techville, there was a special vending machine. This was no ordinary vending machine β it was a smart vending machine! You could put money in, and it would automatically give you the item you selected. No shopkeeper needed!
The villagers loved it. They could buy snacks, drinks, and even tickets for the town cinema. The machine was fast, fair, and available 24/7. It was a smart contract in real life.
One day, a clever but tricky visitor named Zara noticed something. The machine had a bug. If you put in a coin, got your snack, and then quickly put in another coin while the machine was still processing the first purchase, the machine would give you another snack without taking the second coin! This was like a reentrancy attack β a bug that lets someone take more than they should.
The village needed a smart contract auditor β someone who checks the machine's code to find problems before tricksters like Zara can exploit them. The auditor found the bug and fixed it. Now, the machine works perfectly and fairly.
This story shows that smart contracts can do amazing things, but they can also have bugs. That's why we need to audit them to keep everyone safe!
Definition: A smart contract is a computer program that automatically executes (performs) when certain conditions are met. It's like a digital promise that keeps itself.
Why important: Smart contracts allow people to transact (exchange things) without needing a middleman (like a bank or a lawyer). They are fast, transparent, and trustworthy.
Simple explanation: Imagine a vending machine. You put in money, and the machine automatically gives you a snack. No person is needed. A smart contract works the same way.
Real-life example: A smart contract could be used to automatically pay your rent on the 1st of every month. The contract checks the date and automatically sends the money.
School example: A smart contract could automatically award a certificate to a student when they complete all their courses and pass all exams.
Home example: A smart contract could automatically transfer pocket money to your account every Friday, only if you have completed your chores.
Nigerian example: A farmer uses a smart contract to automatically sell his cocoa beans to a buyer when the price reaches a certain amount. No need for a middleman!
Illustration:
VENDING MACHINE = SMART CONTRACT
You put in money β Machine checks money β Machine gives you snack
Mini summary: A smart contract is a program that automatically executes when conditions are met.
Definition: A smart contract is a set of rules and conditions written in code. When the conditions are met, the contract performs its action.
Why important: Understanding how they work helps you see why they are powerful and why they can have bugs.
Simple explanation: Think of a smart contract like a recipe. If you have all the ingredients, you follow the steps and get the finished dish. If you miss an ingredient, the recipe stops.
Real-life example: A crowdfunding smart contract: If the total donations reach a target by a certain date, the money is released to the project creator. If not, the money is returned to the donors.
School example: A smart contract for a class project: If all group members submit their parts on time, the project is submitted to the teacher.
Home example: A smart contract for chores: If you finish your chores by 6 PM, you get your allowance. If not, you don't.
Nigerian example: A smart contract for a cooperative: If all members pay their monthly dues on time, the contract distributes the payout to all members.
Illustration:
IF (condition is true) THEN (execute action)
IF (donation total reaches 100 coins) THEN (release funds to creator)
Mini summary: Smart contracts work by checking conditions and performing actions when conditions are met.
Definition: A smart contract has different parts that tell it what to do. The main parts are state variables, functions, and events.
Why important: Knowing the parts helps you understand what a contract does and where bugs can hide.
Simple explanation: Think of a smart contract like a recipe card. The state variables are the ingredients, the functions are the steps, and the events are the notes you write.
Real-life example: A contract for a rental agreement: The state variables are the renter, the landlord, and the monthly price. The functions are "pay rent," "end lease," and "refund deposit."
School example: A contract for a group project: The state variables are the group members and the deadline. The functions are "submit part," "review project," and "submit final."
Home example: A contract for chores: The state variables are the chore list and the allowance amount. The functions are "complete chore" and "pay allowance."
Nigerian example: A contract for a farmer's cooperative: The state variables are the members, their contributions, and the payout schedule.
Illustration:
SMART CONTRACT STRUCTURE
+-----------------------------------+
| STATE VARIABLES (data stored) |
| - Owner: address |
| - Balance: uint256 |
| |
| FUNCTIONS (actions) |
| - transfer(address, amount) |
| - deposit() |
| |
| EVENTS (notifications) |
| - Transfer(from, to, amount) |
+-----------------------------------+
Mini summary: A smart contract has state variables (data), functions (actions), and events (notifications).
Definition: Most smart contracts use "IF-THEN" logic. This means "IF condition A is true, THEN do action B."
Why important: This is the core of how smart contracts make decisions.
Simple explanation: It's like a simple rule: "IF you complete your chores, THEN you get allowance."
Real-life example: "IF it rains, THEN take an umbrella."
School example: "IF you get an A on the test, THEN you get a prize."
Home example: "IF you finish your homework, THEN you can watch TV."
Nigerian example: "IF the price of cocoa reaches β¦500 per kg, THEN sell 100 kg."
Illustration:
IF (condition) { action }
IF (price >= 500) { sell(); }
Mini summary: Smart contracts use IF-THEN logic: IF condition is true, THEN do action.
Definition: Vulnerabilities are bugs or weaknesses in a smart contract that hackers can exploit to steal money or cause problems.
Why important: If you know the vulnerabilities, you can avoid them and write safer contracts.
Simple explanation: It's like knowing the holes in a net. If you know where the holes are, you can fix them.
Real-life example: In 2016, a bug in "The DAO" smart contract allowed hackers to steal over $60 million worth of cryptocurrency.
School example: If a test has a "gotcha" question, knowing about it helps you avoid it.
Home example: If you know your door lock is weak, you get a stronger lock.
Nigerian example: A Nigerian blockchain project lost funds because of a smart contract bug. Now they use audits to prevent it.
Illustration:
Common Vulnerabilities:
1. Reentrancy
2. Front-Running
3. Access Control Issues
4. Integer Overflow/Underflow
5. Unchecked External Calls
6. Denial of Service (DoS)
Mini summary: Vulnerabilities are bugs in smart contracts that hackers can exploit.
Definition: Reentrancy is when a hacker calls a function that makes a contract send money, and before the contract finishes processing, the hacker calls the function again to get more money.
Why important: Reentrancy has caused some of the biggest hacks in blockchain history. It's the "most wanted" vulnerability.
Simple explanation: It's like going to a candy store and saying, "I want 5 candies." The shopkeeper gives you 5 candies. But while the shopkeeper is counting, you say, "I want 5 more," and the shopkeeper gives you another 5. If the shopkeeper doesn't stop you, you can keep getting candy!
Real-life example: The DAO hack in 2016 was a reentrancy attack. The hacker called the withdrawal function repeatedly before the contract could update its balance.
School example: Imagine a school raffle where students can withdraw tickets. If a student withdraws tickets and then withdraws again before the school updates the total, they could get more tickets than they paid for.
Home example: If a shopkeeper gives you change and then, before recording the sale, you ask for change again, you could get double the change.
Nigerian example: A Nigerian DeFi project was hacked in 2022 due to a reentrancy vulnerability. The hacker stole over β¦200 million.
Illustration:
Step 1: Hacker asks for money.
Step 2: Contract sends money.
Step 3: BEFORE contract updates balance, hacker asks for money again.
Step 4: Contract sends more money.
Step 5: Repeat.
Result: Hacker gets much more money than they should.
Mini summary: Reentrancy is when a hacker repeatedly calls a function to get more money than they should.
Definition: Front-running is when someone sees a pending transaction and quickly submits another transaction to profit from it. MEV is the value gained from these types of attacks.
Why important: Front-running can harm users and make them pay more than they should.
Simple explanation: Imagine you're about to buy a rare toy at a store. But someone sees you heading to the store, runs ahead, and buys it first. Then they sell it to you at a higher price. That's front-running.
Real-life example: On Ethereum, a trader might see a large buy order and quickly submit their own buy order to get the asset cheaper before the price goes up.
School example: If a teacher is about to give a prize to a student, but another student rushes to get it first, that's front-running.
Home example: If you're about to take the last slice of pizza, but your sibling grabs it before you, that's front-running.
Nigerian example: A Nigerian trader on a DEX (decentralized exchange) might be front-run by a bot that buys tokens before the trader's order executes.
Illustration:
User A: "I want to buy 100 tokens at 10 coins each."
Front-runner: "I see that order. I'll buy 100 tokens at 10 coins first."
Front-runner then sells at 11 coins to User A.
Front-runner makes profit. User A pays more.
Mini summary: Front-running is when someone uses information about a pending transaction to profit unfairly.
Definition: Access control issues happen when a smart contract allows someone to do something they shouldn't be allowed to do, like withdrawing money from a contract they don't own.
Why important: Access control failures can lead to anyone stealing funds or changing important settings.
Simple explanation: It's like leaving your front door unlocked. Anyone can walk in.
Real-life example: In 2017, the Parity Wallet bug froze over $150 million worth of Ether because the contract allowed anyone to become the owner and destroy the contract.
School example: If the school's grade system allowed any student to change their own grade, that would be an access control problem.
Home example: If you have a diary and you leave it open, anyone can read it.
Nigerian example: A Nigerian smart contract allowed any user to call the "withdraw" function. A hacker exploited this and stole all the funds.
Illustration:
π BAD: withdraw() allowed anyone to call it.
π GOOD: withdraw() allowed only the owner to call it.
Mini summary: Access control issues mean the wrong people can perform sensitive actions.
Definition: Integer overflow and underflow happen when a number in a smart contract gets too big or too small and wraps around to the opposite end.
Why important: This can cause the contract to think a user has more money than they do, or can make balances become negative.
Simple explanation: Imagine a car odometer that shows 999,999 miles. If you drive one more mile, it wraps around to 0. That's an overflow.
Real-life example: In 2018, a bug in the "BEC" token contract allowed an attacker to create infinite tokens by causing an integer overflow.
School example: If a test has a maximum score of 100, but a student gets 101, the system might show 0 or a weird number.
Home example: If your phone storage shows 99% full and you add more, it might show 0% or crash.
Nigerian example: A Nigerian startup's token contract had an integer overflow bug, allowing hackers to mint (create) millions of new tokens.
Illustration:
uint8 (0 to 255)
If value = 255 and you add 1 β it becomes 0 (overflow)
If value = 0 and you subtract 1 β it becomes 255 (underflow)
Mini summary: Integer overflow/underflow happens when numbers wrap around, causing unexpected results.
Definition: When a smart contract calls another contract, it might not check if the call succeeded. This can lead to problems like funds being stuck or lost.
Why important: You should always check the outcome of external calls to make sure they worked.
Simple explanation: It's like sending a letter and not checking if it was delivered. You might think the person got it, but they never did.
Real-life example: If a contract sends money to another address and doesn't check if the transfer worked, the sender might think the transaction failed when it actually succeeded.
School example: If you submit your homework but don't check if the teacher received it, you might get a zero.
Home example: If you call a friend to make plans but don't check if they heard you, you might show up to an empty restaurant.
Nigerian example: A Nigerian DeFi contract failed to check the return value of an external call, leading to funds being lost.
Illustration:
β BAD: externalCall(); // No check if it worked
β
GOOD: require(externalCall(), "Call failed");
Mini summary: Unchecked external calls happen when you don't check if an external action succeeded.
Definition: A DoS attack makes a smart contract unusable or prevents other people from using it. It can cause the contract to be stuck or unable to process transactions.
Why important: DoS attacks can freeze funds and prevent legitimate users from accessing the contract.
Simple explanation: It's like someone blocking the entrance to a store so that no one can get in.
Real-life example: A contract might be vulnerable to DoS if a function requires a specific condition that can be manipulated.
School example: If a student blocks the door to the classroom, no one can enter.
Home example: If someone unplugs the internet router, no one can use the internet.
Nigerian example: A Nigerian blockchain game was unusable for days because a DoS attack prevented transactions.
Illustration:
DoS Attack: "I'll make this contract unusable by making it impossible to complete transactions."
Mini summary: Denial of Service attacks make a contract unusable.
Definition: Logic errors are mistakes in the rules or design of a contract. These are not coding bugs but flaws in how the contract is supposed to work.
Why important: Logic errors can be just as dangerous as coding bugs. They can allow hackers to exploit the rules of the contract.
Simple explanation: It's like having a rule in a board game that is unfair and allows someone to cheat.
Real-life example: A lottery contract might have a logic error that allows the creator to always win.
School example: A school rule that allows students to re-take tests until they pass might be exploited by lazy students.
Home example: A family rule that "the first person to the table gets the last slice" might cause fights.
Nigerian example: A Nigerian lending platform had a logic error that allowed borrowers to take loans without collateral.
Illustration:
Logic Error: IF (user has 0 coins) THEN (allow borrowing 100 coins)
β Users could borrow even with no money.
Mini summary: Logic errors are flaws in the design of a contract that can be exploited.
Definition: An oracle is a service that provides external data to a smart contract. Oracle manipulation is when a hacker provides fake data to the contract.
Why important: If a contract relies on external data, that data must be trustworthy. Fake data can lead to incorrect decisions.
Simple explanation: It's like someone telling you a lie about what the weather is outside.
Real-life example: A DeFi lending contract uses an oracle to determine prices. If a hacker manipulates the oracle, they can borrow more than they should or liquidate positions unfairly.
School example: If a teacher tells you a test is on Friday, but they lied and it was actually on Monday, that would be like oracle manipulation.
Home example: If someone tells you the store is open but it's actually closed, that's misleading information.
Nigerian example: A Nigerian stablecoin project was attacked when hackers manipulated the price oracle to steal funds.
Illustration:
Smart Contract β Asks Oracle: "What is the price?"
Hacker β Manipulates Oracle: "The price is 100% higher!"
Smart Contract β "Based on the fake price, you can borrow more!"
Mini summary: Oracle manipulation is when hackers provide fake external data to a contract.
Definition: A smart contract audit is a thorough check of a contract's code and logic to find vulnerabilities and bugs before they are exploited.
Why important: Audits are the best defense against hacks. They find problems before hackers do.
Simple explanation: It's like taking your car to a mechanic to check for problems before you go on a long trip.
Real-life example: A company hires an auditing firm like CertiK to check their smart contract before launching.
School example: A student's essay is proofread by a teacher before submission to find errors.
Home example: You check your bike's brakes and tires before a long ride.
Nigerian example: A Nigerian blockchain startup hires a global auditing firm to check their contract before launch.
Illustration (Flowchart):
Audit Process:
1. Scope Definition β What to review?
2. Manual Review β Code read line by line
3. Automated Testing β Tools find bugs
4. Reporting β Findings & recommendations
5. Remediation β Fix the bugs
6. Re-audit β Check the fixes
Mini summary: The audit process checks a contract for bugs and vulnerabilities.
Definition: Audits prevent hacks that could cost millions of dollars. They are a smart investment for any blockchain project.
Why important: The cost of an audit is tiny compared to the cost of a hack.
Simple explanation: It's better to pay a small amount to prevent a big loss.
Real-life example: A project spent $200,000 on an audit and prevented a $10 million hack. That's a 50x return on investment!
School example: Spending 30 minutes checking your homework prevents you from getting a bad grade.
Home example: Spending a few hundred naira on a good lock prevents a theft worth thousands of naira.
Nigerian example: A Nigerian DeFi project that was audited avoided a hack that would have cost their users millions of naira.
Illustration:
$200,000 Audit β Prevents $10,000,000 Hack β Saves $9,800,000
Mini summary: Audits prevent expensive hacks and save millions.
Emphasize that smart contracts are powerful but can have bugs. Use the vending machine analogy frequently. Encourage students to think about how they would design a smart contract to avoid vulnerabilities. Use real-world hacks (like the DAO) to show the importance of audits.
Discuss with your child how smart contracts could be used in Nigeria to solve problems like land disputes and food safety. Encourage them to think about how to make smart contracts safe.
Did you know that there is a whole industry of "white hat" hackers who find bugs in smart contracts and help fix them? They are like digital superheroes!
+-------------------------------------------+
| SMART CONTRACT |
+-------------------------------------------+
| STATE VARIABLES (Storage) |
| - owner: address |
| - balances: mapping(address => uint256) |
| - totalSupply: uint256 |
+-------------------------------------------+
| FUNCTIONS (Actions) |
| - transfer(address to, uint256 amount) |
| - approve(address spender, uint256 amt) |
| - deposit() |
| - withdraw(uint256 amount) |
+-------------------------------------------+
| EVENTS (Notifications) |
| - Transfer(address from, to, amount) |
| - Approval(address owner, spender, amt) |
+-------------------------------------------+
Hacker Contract β Calls withdraw on Target Contract
Target sends money to Hacker
BEFORE Target updates balance...
Hacker calls withdraw again (reentrant call)
Target sends more money
... repeats until empty
Target updates balance (too late!)
| Vulnerability | Description | Real-World Example |
|---|---|---|
| Reentrancy | Repeatedly calling a function before the contract updates | The DAO Hack (2016) |
| Front-running | Using information about a pending transaction to profit | DEX arbitrage bots |
| Access Control | Allowing the wrong people to perform actions | Parity Wallet (2017) |
| Integer Overflow | Numbers wrapping around when they get too big/small | BEC Token (2018) |
| DoS | Making a contract unusable | Gas limit attacks |
| Feature | Vulnerable Contract | Secure Contract |
|---|---|---|
| Reentrancy Protection | β No protection | β Checks-Effects-Interactions pattern |
| Access Control | β Anyone can call functions | β Only owner or authorized users |
| Integer Safety | β No overflow/underflow checks | β SafeMath library used |
| Audit | β No audit | β Audited by professionals |
| Testing | β Minimal testing | β Extensive automated testing |
Amazing work! π You have completed Module Two of the "Blockchain Security & Contract Auditing" course. You now understand what smart contracts are, how they work, and the most common vulnerabilities that hackers exploit. You've learned about reentrancy, front-running, access control, integer overflow, DoS, and more. You also understand the importance of audits in finding bugs before hackers do.
These vulnerabilities have caused billions of dollars in losses. But with the knowledge you now have, you can help prevent them. Remember, a smart contract is only as safe as its code and its audit!
Match the term with its definition:
| Term | Definition |
|---|---|
| Smart Contract | Program that executes automatically |
| Reentrancy | Repeatedly calling a function to get more |
| Front-running | Using information to profit |
| Access Control | Restricting who can perform actions |
| Audit | Security check for smart contracts |
Scenario 1: A Nigerian farmer wants to use a smart contract to sell her cocoa beans. What vulnerabilities should she be aware of?
Answer: She should be aware of oracle manipulation (if the contract uses price oracles), access control issues (who can trigger the sale), and logic errors (the rules of the contract).
Scenario 2: A startup wants to launch a DeFi lending platform. They have written a smart contract. What should they do before launching?
Answer: They should get the smart contract audited by a reputable firm, test it extensively, and run a bug bounty program.
In groups, create a "Vulnerability Wanted" poster for one of the smart contract vulnerabilities. Include a description, a drawing, and an example of how the vulnerability can be exploited. Present your poster to the class.
Write a short report on a real-world smart contract hack (like The DAO). Describe what happened, what vulnerability was exploited, and how it could have been prevented.
Design a simple smart contract (in plain English) for a community project. Include state variables, functions, and IF-THEN logic. Then list at least 3 vulnerabilities that could affect your contract.
Find a real smart contract on a blockchain explorer (like Etherscan). Copy the code and try to identify one potential vulnerability. Write a paragraph explaining what you found.
Write a vulnerable smart contract in plain English (not code) that contains at least two of the vulnerabilities discussed in this module. Then write a corrected version that fixes those vulnerabilities.
Fill-in-the-Blank: 1. smart contract, 2. Reentrancy, 3. Access control, 4. Integer overflow, 5. DoS, 6. Logic errors, 7. Oracle, 8. Audits, 9. Front-running, 10. DAO.
True/False: 1F, 2T, 3T, 4F, 5T.
Multiple Choice: 1B, 2B, 3B, 4A, 5A, 6A, 7B, 8A, 9A, 10A, 11A, 12A, 13A, 14B, 15A.
In Module Three, we will explore the smart contract audit process in detail. You will learn how auditors review code, what tools they use, and how they write audit reports. We will also look at real-world audit reports and learn how to read them. Get ready to become an audit expert!
End of Module Two. You're now a smart contract safety expert! π