Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Blockchain Security & Contract Auditing Β· Lesson 3 of 7

Module Two

πŸ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
3
Module 2: Blockchain Security & Contract Auditing – Smart Contracts & Vulnerabilities

πŸ“˜ Module Two: Blockchain Security & Contract Auditing – Smart Contracts & Vulnerabilities

Understanding the magic and the traps of smart contracts!

🌟 Module Introduction

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! πŸš€

🎯 Learning Objectives

After finishing this module, you will be able to:

  • Explain what a smart contract is in simple words.
  • Describe the different parts of a smart contract.
  • Identify common smart contract vulnerabilities (bugs).
  • Understand what a reentrancy attack is and why it's dangerous.
  • Explain what front-running and MEV attacks are.
  • Understand the importance of access control in smart contracts.
  • Describe the audit process and why it's essential.
  • Give examples of real-world hacks and how they could have been prevented.
  • Apply basic security principles when thinking about smart contracts.

πŸ“– Warm‑up Story: The Town's Vending Machine

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!

πŸ“š Main Lessons

Lesson 1: What is a Smart Contract?

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.


Lesson 2: How Smart Contracts Work

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.


Lesson 3: The Structure of a Smart Contract

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).


Lesson 4: The "IF-THEN" Logic

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.


Lesson 5: Common Smart Contract Vulnerabilities

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.


Lesson 6: Reentrancy – The Most Dangerous Vulnerability

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.


Lesson 7: Front-Running and MEV (Maximal Extractable Value)

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.


Lesson 8: Access Control Issues

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.


Lesson 9: Integer Overflow and Underflow

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.


Lesson 10: Unchecked External Calls

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.


Lesson 11: Denial of Service (DoS)

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.


Lesson 12: Logic Errors and Business Logic Vulnerabilities

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.


Lesson 13: Oracle Manipulation

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.


Lesson 14: The Audit Process

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.


Lesson 15: Why Audits Save Millions

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.


πŸ“– Key Vocabulary

  • Smart Contract: A program that automatically executes when conditions are met.
  • Vulnerability: A bug or weakness that hackers can exploit.
  • Reentrancy: A vulnerability where a hacker repeatedly calls a function to get more than they should.
  • Front-running: Using information about a pending transaction to profit unfairly.
  • MEV (Maximal Extractable Value): Value gained from front-running and similar attacks.
  • Access Control: Restricting who can perform certain actions in a contract.
  • Integer Overflow/Underflow: Numbers wrapping around when they get too big or too small.
  • DoS (Denial of Service): Making a contract unusable.
  • Logic Error: A flaw in the design of a contract.
  • Oracle: A service that provides external data to a contract.
  • Audit: A security check that finds bugs in smart contracts.
  • Auditor: A security expert who checks smart contracts for bugs.

πŸ’‘ Important Concepts

  • Trustlessness: Smart contracts allow people to transact without needing to trust each other.
  • Immutability: Once a smart contract is deployed, it cannot be changed. This is why audits are so important.
  • Gas: The cost of executing a smart contract. Bugs that waste gas can be a form of Denial of Service.
  • Bug Bounties: Some projects offer rewards for people who find bugs in their contracts. This helps improve security.

πŸ“Œ Step‑by‑Step Explanations

How a Reentrancy Attack Works:

  1. Hacker creates a contract that calls the target contract.
  2. Hacker calls the target contract's withdraw function.
  3. Target contract sends money to hacker's contract.
  4. Before the target contract updates its balance, the hacker's contract calls the withdraw function again.
  5. Target contract sends more money.
  6. Steps 3-5 repeat until the target contract is empty.
  7. Target contract updates its balance, but it's too late.

🌍 Real‑life Examples

  • The DAO Hack (2016): A reentrancy vulnerability allowed hackers to steal over $60 million.
  • Parity Wallet Bug (2017): An access control issue froze over $150 million.
  • BEC Token (2018): An integer overflow allowed the creation of infinite tokens.
  • Poly Network Hack (2021): A logic error allowed a hacker to steal over $600 million.

πŸ‡³πŸ‡¬ Nigerian Examples

  • DeFi Hacks: Several Nigerian DeFi projects have been hacked due to reentrancy and access control vulnerabilities.
  • Audit Firms: Nigerian companies are starting to offer smart contract audit services.
  • Education: Nigerian universities are beginning to teach blockchain security.
  • Startups: Nigerian startups are increasingly using audits to build trust with users.

🎈 Fun Examples Children Can Relate To

  • Reentrancy: Like a vending machine giving you extra snacks if you keep pressing the button.
  • Front-running: Like someone running ahead of you to buy the last toy.
  • Access Control: Like leaving your diary open for anyone to read.
  • Integer Overflow: Like a video game score that goes from 999 back to 0.
  • DoS: Like someone blocking the entrance to your classroom.

🏠 Everyday Examples

  • Reentrancy: A shopkeeper giving double change if you ask again before they finish counting.
  • Front-running: Someone cutting in line before you.
  • Access Control: A bank vault that lets anyone in.
  • Integer Overflow: A car odometer that goes from 999,999 to 0.
  • DoS: Someone unplugging the internet router.

πŸ‘©β€πŸ« Teacher Notes

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.

πŸ‘¨β€πŸ‘©β€πŸ‘§ Parent Tips

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.

🧠 Interesting Facts

  • The DAO hack in 2016 was so big that Ethereum created a "hard fork" to return the stolen money.
  • Some smart contract audits can cost over $500,000.
  • Over $10 billion has been lost to smart contract vulnerabilities since 2016.
  • Bug bounties have helped prevent many hacks.

❓ Did You Know?

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!

πŸ”‘ Remember This

  • Smart contracts are digital promises that execute automatically.
  • Vulnerabilities are bugs that hackers can exploit.
  • Reentrancy is the most dangerous vulnerability.
  • Audits find bugs before hackers do.
  • Audits prevent hacks and save money.

⚠️ Common Mistakes

  • Thinking smart contracts are always safe: They can have bugs.
  • Not auditing: Many projects skip audits to save money, but this is a big mistake.
  • Ignoring access control: Not restricting who can call functions is dangerous.
  • Forgetting about oracle security: If a contract uses oracles, they must be trustworthy.
  • Not testing: Always test smart contracts thoroughly.

βœ… Best Practices

  • Always audit smart contracts before deploying them.
  • Use safe programming patterns (like the "checks-effects-interactions" pattern).
  • Implement strong access control (e.g., onlyOwner modifiers).
  • Test contracts thoroughly with automated tools.
  • Run bug bounty programs to incentivize (reward) bug finders.
  • Use secure oracles for external data.

πŸ“Š Illustrations

Smart Contract Structure

    +-------------------------------------------+
    |  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)  |
    +-------------------------------------------+
    

Reentrancy Attack Flow

    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 Comparison Table

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

πŸ“‹ Comparison: Secure vs Vulnerable Smart Contract

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

πŸ“ End‑of‑Module Summary

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!

❓ Frequently Asked Questions

  1. What is a smart contract? – A program that automatically executes when conditions are met.
  2. What is a vulnerability? – A bug that hackers can exploit.
  3. What is reentrancy? – A vulnerability where a hacker repeatedly calls a function to get more than they should.
  4. What is front-running? – Using information about a pending transaction to profit.
  5. What is access control? – Restricting who can perform certain actions.
  6. What is integer overflow? – Numbers wrapping around when they get too big or small.
  7. What is a DoS attack? – Making a contract unusable.
  8. What is an oracle? – A service that provides external data to a contract.
  9. What is an audit? – A security check that finds bugs in smart contracts.
  10. Why are audits important? – They prevent hacks and save money.

πŸ“ Review Questions

  1. What is a smart contract?
  2. How does a smart contract work?
  3. What are the main parts of a smart contract?
  4. What is the "IF-THEN" logic in smart contracts?
  5. What is a vulnerability?
  6. What is reentrancy?
  7. How does reentrancy work?
  8. What is front-running?
  9. What is access control?
  10. What is integer overflow?
  11. What is a DoS attack?
  12. What is a logic error?
  13. What is oracle manipulation?
  14. What is the audit process?
  15. Why are audits important?

πŸ“ Fill‑in‑the‑Blank Exercises

  1. A __________ is a program that automatically executes when conditions are met.
  2. __________ is a vulnerability where a hacker repeatedly calls a function to get more than they should.
  3. __________ means restricting who can perform certain actions in a contract.
  4. __________ happens when numbers wrap around when they get too big or too small.
  5. __________ is a vulnerability where a hacker makes a contract unusable.
  6. __________ are flaws in the design of a contract that can be exploited.
  7. __________ is a service that provides external data to a contract.
  8. __________ are security checks that find bugs in smart contracts.
  9. __________ is using information about a pending transaction to profit.
  10. The __________ hack in 2016 was caused by a reentrancy vulnerability.

βœ… True or False Exercises

  1. Smart contracts are always safe. (False)
  2. Reentrancy is a vulnerability that hackers can exploit. (True)
  3. Front-running is illegal in blockchain. (True)
  4. Access control is not important. (False)
  5. Audits find bugs before hackers do. (True)

πŸ”˜ Multiple Choice Questions

  1. What is a smart contract?
    A) A legal document
    B) A program that executes automatically βœ…
    C) A type of blockchain
    D) A hash function
  2. What is reentrancy?
    A) A type of hash
    B) A vulnerability where hackers repeatedly call a function βœ…
    C) A type of blockchain
    D) A smart contract
  3. What is front-running?
    A) A type of transaction
    B) Using information about a pending transaction to profit βœ…
    C) A type of hash
    D) A smart contract
  4. What is access control?
    A) Restricting who can perform actions βœ…
    B) A type of transaction
    C) A hash function
    D) A smart contract
  5. What is integer overflow?
    A) Numbers wrapping around when too big βœ…
    B) A type of transaction
    C) A hash function
    D) A smart contract
  6. What is a DoS attack?
    A) Making a contract unusable βœ…
    B) A type of transaction
    C) A hash function
    D) A smart contract
  7. What is a logic error?
    A) A coding bug
    B) A flaw in the design of a contract βœ…
    C) A type of transaction
    D) A hash function
  8. What is an oracle?
    A) A service that provides external data βœ…
    B) A type of transaction
    C) A hash function
    D) A smart contract
  9. What is an audit?
    A) A security check for smart contracts βœ…
    B) A type of transaction
    C) A hash function
    D) A smart contract
  10. Which hack was caused by reentrancy?
    A) The DAO hack βœ…
    B) The Bitcoin hack
    C) The Google hack
    D) The Facebook hack
  11. What is MEV?
    A) Maximal Extractable Value, from front-running βœ…
    B) A type of blockchain
    C) A smart contract
    D) A hash function
  12. Why are audits important?
    A) They prevent hacks and save money βœ…
    B) They make contracts faster
    C) They make contracts cheaper
    D) They make contracts more colorful
  13. What is a Nigerian example of a vulnerability?
    A) A DeFi hack due to reentrancy βœ…
    B) A bank robbery
    C) A school fire
    D) A car accident
  14. What is the best practice for security?
    A) Skipping audits
    B) Using safe programming patterns βœ…
    C) Ignoring access control
    D) Not testing
  15. What is immutability?
    A) Cannot be changed βœ…
    B) Can be changed
    C) A type of transaction
    D) A hash function

πŸ”— Matching Exercises

Match the term with its definition:

TermDefinition
Smart ContractProgram that executes automatically
ReentrancyRepeatedly calling a function to get more
Front-runningUsing information to profit
Access ControlRestricting who can perform actions
AuditSecurity check for smart contracts

✏️ Short Answer Questions

  1. What is a smart contract in your own words?
  2. Explain reentrancy with a simple example.
  3. Why is access control important in smart contracts?
  4. What is the audit process?
  5. Give a Nigerian example of a smart contract vulnerability.

🎭 Scenario‑based Exercises

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.

πŸ‘₯ Group Activity

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.

πŸ§‘β€πŸŽ“ Individual Activity

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.

πŸ’¬ Classroom Discussion Questions

  • Do you think smart contracts will replace lawyers and banks?
  • What problem in your community could be solved with a smart contract?
  • Is it better to have a bug bounty program or an audit?

πŸ› οΈ Mini Project

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.

πŸ“‹ Practical Assignment

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.

πŸ† Challenge Exercise

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.

πŸ”‘ Quiz Answers

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.

✨ Key Takeaways

  • Smart contracts are digital promises that execute automatically.
  • Vulnerabilities are bugs that hackers can exploit.
  • Reentrancy is the most dangerous vulnerability.
  • Front-running, access control, integer overflow, and DoS are also common.
  • Audits find bugs before hackers do and prevent expensive hacks.
  • Security should be a priority for every smart contract project.

πŸ”œ Preparation for Module Three

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! 🌟

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

πŸŽ“ Sign Up to Get Certified
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
β†’