0Pricing
Blockchain Smart Contracts with Solidity · 강의

일반적인 취약점(재진입 등)

재진입, 정수 오버플로 및 언더플로, 선행 매매 공격과 같은 주요 스마트 계약 취약점을 이해하고 완화합니다.

일반적인 취약점(재진입 등)은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Smart Contract Security: Overview

Welcome to this crucial lesson on smart contract security! Unlike traditional software, bugs in smart contracts can lead to irreversible loss of funds.

Because contracts on the blockchain are often immutable, fixing vulnerabilities after deployment is incredibly difficult, if not impossible. Security must be a top priority from day one.

Understanding Reentrancy Attacks

Reentrancy is a critical vulnerability where an external call to an untrusted contract can 're-enter' the original contract before the first function call has completed its execution.

This allows the attacker to repeatedly drain funds or manipulate state by calling the vulnerable function multiple times.

Reentrancy: A Vulnerable Example

Consider this simplified withdrawal contract. Can you spot the potential issue?

The state (balances[msg.sender]) is updated *after* the external call to msg.sender.call. This delay creates a window for attack.

pragma solidity ^0.8.0;

contract VulnerableWithdraw {
  mapping(address => uint) public balances;

  constructor() payable {
    // Fund contract for demo purposes
  }

  function deposit() public payable {
    balances[msg.sender] += msg.value;
  }

  function withdraw(uint _amount) public {
    require(balances[msg.sender] >= _amount, "Insufficient balance");

    // External call FIRST, state update LATER
    (bool success, ) = msg.sender.call{value: _amount}("");
    require(success, "Transfer failed");

    balances[msg.sender] -= _amount; // This line is vulnerable!
  }

  function getBalance() public view returns (uint) {
    return address(this).balance;
  }
}

The Reentrancy Attack Flow

Here's how an attacker exploits the previous contract:

  • 1. Deposit: Attacker deposits funds into VulnerableWithdraw.
  • 2. Withdraw: Attacker calls withdraw(amount).
  • 3. Re-enter: When msg.sender.call transfers Ether to the attacker, their malicious fallback function is triggered.
  • 4. Repeat: The fallback function immediately calls withdraw(amount) again, before the original call updates the balance. This repeats until funds are drained.

Mitigating Reentrancy: The Fix

The most effective way to prevent reentrancy is to follow the Checks-Effects-Interactions (CEI) pattern:

  • 1. Checks: Verify all conditions (e.g., require statements).
  • 2. Effects: Update all state variables (e.g., balances[msg.sender] -= _amount).
  • 3. Interactions: Make external calls (e.g., msg.sender.call).

This ensures state is updated *before* any untrusted external code can execute.

Reentrancy: The Fixed Contract

Here's the corrected version of the withdrawal contract, applying the CEI pattern. Notice the order of operations.

Now, the balance is decremented *before* the external call, closing the reentrancy window.

pragma solidity ^0.8.0;

contract SafeWithdraw {
  mapping(address => uint) public balances;

  constructor() payable {
    // Fund contract for demo purposes
  }

  function deposit() public payable {
    balances[msg.sender] += msg.value;
  }

  function withdraw(uint _amount) public {
    // 1. Checks
    require(balances[msg.sender] >= _amount, "Insufficient balance");

    // 2. Effects: Update state BEFORE external call
    balances[msg.sender] -= _amount;

    // 3. Interactions: Make external call LAST
    (bool success, ) = msg.sender.call{value: _amount}("");
    require(success, "Transfer failed");
  }

  function getBalance() public view returns (uint) {
    return address(this).balance;
  }
}

Integer Overflows & Underflows

Integer overflows occur when an arithmetic operation results in a value larger than the maximum that the variable type can hold. It 'wraps around' to its minimum value.

Integer underflows are the opposite: when a result is smaller than the minimum value, wrapping around to the maximum.

For example, a uint8 can hold values from 0 to 255. If it's 255 and you add 1, it becomes 0 (overflow). If it's 0 and you subtract 1, it becomes 255 (underflow).

Overflow/Underflow Example

Prior to Solidity 0.8.0, these operations would silently wrap around. Since Solidity 0.8.0, arithmetic operations default to checking for overflows/underflows and will revert if one occurs.

However, understanding the concept is vital, especially when working with older codebases or using unchecked blocks for gas optimization.

pragma solidity ^0.8.0;

contract MathVulnerabilities {
  uint8 public smallNumber = 255; // Max for uint8

  function triggerOverflow() public {
    // In Solidity 0.8.0+, this transaction will revert.
    // In older versions, smallNumber would become 0.
    smallNumber = smallNumber + 1;
  }

  function triggerUnderflow() public {
    smallNumber = 0; // Reset for demo
    // In Solidity 0.8.0+, this transaction will revert.
    // In older versions, smallNumber would become 255.
    smallNumber = smallNumber - 1;
  }
}

Front-Running Attacks

Front-running is an attack where a malicious actor observes a pending transaction and submits their own transaction with a higher gas fee to have it executed first.

This is common in DeFi (Decentralized Finance) where transactions like large swaps or liquidations can be anticipated and exploited for profit.

Mitigating Front-Running

Preventing front-running is challenging due to the public nature of the mempool (pending transaction pool). However, some strategies exist:

  • Commit-Reveal Schemes: Users submit a hashed version of their intent (commit), then later reveal the actual data.
  • Batching: Grouping transactions together to reduce individual transaction visibility.
  • Decentralized Sequencers/L2s: Using solutions that offer more private or controlled transaction ordering.
  • Slippage Control: Users setting maximum acceptable price slippage for swaps.

Vulnerability Check

You've learned about three major smart contract vulnerabilities. Let's test your understanding!

Recap: Security First

In this lesson, we explored critical smart contract vulnerabilities: reentrancy, integer overflows/underflows, and front-running.

  • We saw how reentrancy exploits external calls and how the Checks-Effects-Interactions pattern provides a robust defense.
  • We understood how integer arithmetic can lead to unexpected values and the importance of compiler checks (Solidity 0.8.0+).
  • Finally, we discussed front-running and methods like commit-reveal to mitigate it.

Always prioritize security in your smart contract development!

자주 묻는 질문

“일반적인 취약점(재진입 등)” 강의는 무료인가요?

네 — “일반적인 취약점(재진입 등)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

“일반적인 취약점(재진입 등)”에서 뭘 배우나요?

재진입, 정수 오버플로 및 언더플로, 선행 매매 공격과 같은 주요 스마트 계약 취약점을 이해하고 완화합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“일반적인 취약점(재진입 등)” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 일반적인 취약점(재진입 등)
  2. 접근 제어 패턴
  3. SafeMath를 활용한 보안 코딩
  4. 감사, 테스트, 버그 바운티
← Blockchain Smart Contracts with Solidity(으)로 돌아가기