乐闻世界logo
搜索文章和话题

What Are Smart Contracts? Explain Solidity Smart Contract Execution Principles and Common Security Vulnerabilities

3月6日 21:55

What Are Smart Contracts?

Smart Contracts are self-executing computer programs that run on blockchain, automatically executing operations when predefined conditions are met, without the need for third-party intermediaries.

Core Features

  1. Automatic Execution: Automatically runs when conditions are triggered, no manual intervention needed
  2. Immutability: Code cannot be modified after deployment, ensuring trustworthy execution results
  3. Transparent: Contract code is visible to all network participants
  4. Trustless: Executes agreements through code rather than trust

Solidity Smart Contract Execution Principles

1. Contract Deployment Process

solidity
// Example: Simple storage contract pragma solidity ^0.8.0; contract SimpleStorage { uint256 private storedData; event DataChanged(uint256 newValue); function set(uint256 x) public { storedData = x; emit DataChanged(x); } function get() public view returns (uint256) { return storedData; } }

Deployment Steps:

  1. Compilation: Solidity code compiled to EVM bytecode
  2. Transaction Creation: Create deployment transaction containing bytecode
  3. Miner Packaging: Transaction packaged into block by miners
  4. Contract Creation: EVM executes creation operation, allocates contract address
  5. State Storage: Contract code and initial state stored on blockchain

2. EVM Execution Model

shell
Transaction Initiation → Gas Fee Check → EVM Execution Stack Operations Memory Operations Storage Operations State Update or Rollback Transaction Receipt Generation

Gas Mechanism:

  • Each operation consumes Gas to prevent infinite loops
  • Gas Price × Gas Limit = Maximum Transaction Fee
  • If Gas is insufficient, transaction reverts but consumed Gas is not refunded

3. Contract Call Methods

Call MethodCharacteristicsUse Cases
callNo new context created, can specify GasCalling external contracts
delegatecallExecutes in current contract contextProxy contract pattern
staticcallRead-only call, no state modificationQuery operations

Common Security Vulnerabilities

1. Reentrancy Attack

Vulnerable Code:

solidity
function withdraw() public { uint256 amount = balances[msg.sender]; require(amount > 0); (bool success, ) = msg.sender.call{value: amount}(""); // External call require(success); balances[msg.sender] = 0; // State update after }

Attack Principle:

  • Attacker contract triggers fallback function when receiving ETH
  • Fallback function calls withdraw again
  • Forms recursive calls, repeatedly extracting funds

Protection Measures:

solidity
function withdraw() public { uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; // Update state first (bool success, ) = msg.sender.call{value: amount}(""); require(success); }

2. Integer Overflow/Underflow

Vulnerable Code:

solidity
function transfer(address to, uint256 amount) public { balances[msg.sender] -= amount; // May underflow balances[to] += amount; // May overflow }

Protection Measures:

  • Use Solidity 0.8.0+ (built-in overflow checks)
  • Or use SafeMath library
solidity
using SafeMath for uint256; function transfer(address to, uint256 amount) public { balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); }

3. Access Control Vulnerabilities

Vulnerable Code:

solidity
function destroy() public { selfdestruct(payable(msg.sender)); // Anyone can call }

Protection Measures:

solidity
address public owner; modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } function destroy() public onlyOwner { selfdestruct(payable(owner)); }

4. Front-running Attack

Attack Principle:

  • Attacker monitors pending transactions in mempool
  • Pays higher Gas Price to preemptively execute similar transactions
  • Common in DEX trading and auction scenarios

Protection Measures:

  • Submit hash commitments, delay revelation
  • Use commit-reveal pattern

Security Best Practices

  1. Use Mature Security Libraries: OpenZeppelin Contracts
  2. Code Audits: Professional security audit before deployment
  3. Formal Verification: Use tools to verify contract logic
  4. Test Coverage: Write comprehensive unit and integration tests
  5. Least Privilege: Follow principle of least privilege
  6. Emergency Pause: Implement pausable functionality for emergencies

Interview Key Points

  • Understand EVM execution model and Gas mechanism
  • Master principles and protection methods of reentrancy attacks
  • Understand common types of security vulnerabilities
  • Familiar with usage of security libraries like OpenZeppelin
  • Ability to design secure contract architectures
标签:Blockchain