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
- Automatic Execution: Automatically runs when conditions are triggered, no manual intervention needed
- Immutability: Code cannot be modified after deployment, ensuring trustworthy execution results
- Transparent: Contract code is visible to all network participants
- 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:
- Compilation: Solidity code compiled to EVM bytecode
- Transaction Creation: Create deployment transaction containing bytecode
- Miner Packaging: Transaction packaged into block by miners
- Contract Creation: EVM executes creation operation, allocates contract address
- State Storage: Contract code and initial state stored on blockchain
2. EVM Execution Model
shellTransaction 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 Method | Characteristics | Use Cases |
|---|---|---|
call | No new context created, can specify Gas | Calling external contracts |
delegatecall | Executes in current contract context | Proxy contract pattern |
staticcall | Read-only call, no state modification | Query operations |
Common Security Vulnerabilities
1. Reentrancy Attack
Vulnerable Code:
solidityfunction 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:
solidityfunction 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:
solidityfunction 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
solidityusing 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:
solidityfunction destroy() public { selfdestruct(payable(msg.sender)); // Anyone can call }
Protection Measures:
solidityaddress 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
- Use Mature Security Libraries: OpenZeppelin Contracts
- Code Audits: Professional security audit before deployment
- Formal Verification: Use tools to verify contract logic
- Test Coverage: Write comprehensive unit and integration tests
- Least Privilege: Follow principle of least privilege
- 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