这是一个完整的区块链智能合约课程项目,包含一个安全的 ERC20 代币合约、部署脚本、安全检测脚本和多种攻击模拟测试。
- 重入攻击保护: 使用 ReentrancyGuard 防止重入攻击
- 整数溢出保护: 使用 SafeMath 和 Solidity 0.8+ 内置保护
- 访问控制: 基于 OpenZeppelin Ownable 的所有者权限管理
- 暂停功能: 紧急情况下可暂停合约操作
- 黑名单/白名单: 灵活的账户管理机制
- 费用机制: 可配置的转账费用系统
- 标准 ERC20: 完全兼容 ERC20 标准
- 燃烧功能: 支持代币燃烧减少供应量
- 供应量限制: 最大供应量和单次铸造限制
- 事件日志: 完整的事件记录系统
secure-token-project/
├── contracts/
│ └── SecureToken.sol # 主代币合约
├── scripts/
│ ├── deploy.ts # 部署脚本
│ ├── security-audit.ts # 安全检测脚本
│ └── run-all-tests.ts # 完整测试运行脚本
├── test/
│ ├── SecureToken.test.ts # 基础功能测试
│ ├── ReentrancyAttack.test.ts # 重入攻击模拟
│ └── IntegerOverflowAttack.test.ts # 整数溢出攻击模拟
├── ignition/
│ └── modules/
│ └── SecureToken.ts # Ignition 部署模块
└── hardhat.config.ts # Hardhat 配置
npm installnpx hardhat compile# 运行所有测试
npx hardhat test
# 运行特定测试
npx hardhat test test/SecureToken.test.ts
npx hardhat test test/ReentrancyAttack.test.ts
npx hardhat test test/IntegerOverflowAttack.test.ts# 使用脚本部署
npx hardhat run scripts/deploy.ts
# 使用 Ignition 部署
npx hardhat ignition deploy ignition/modules/SecureToken.tsnpx hardhat run scripts/security-audit.tsnpx hardhat run scripts/run-all-tests.tstransfer(address to, uint256 amount): 转账代币balanceOf(address account): 查询余额getBalance(address account): 公开的余额查询函数
mint(address to, uint256 amount): 铸造新代币(仅所有者)burn(uint256 amount): 燃烧代币burnFrom(address account, uint256 amount): 燃烧指定账户的代币
setTransferFeeRate(uint256 newRate): 设置转账费用率setFeeRecipient(address newRecipient): 设置费用接收者
updateWhitelist(address account, bool status): 更新白名单updateBlacklist(address account, bool status): 更新黑名单
pause(): 暂停合约unpause(): 恢复合约
modifier nonReentrant() {
// 防止重入攻击
}using SafeMath for uint256;
// Solidity 0.8+ 内置溢出保护modifier onlyOwner() {
// 仅所有者可调用
}modifier whenNotPaused() {
// 合约未暂停时才可执行
}- 部署和初始化测试
- 转账功能测试
- 铸造和燃烧测试
- 暂停功能测试
- 黑名单/白名单测试
- 访问控制测试
- 重入攻击合约部署
- 攻击尝试和防护验证
- ReentrancyGuard 有效性测试
- 转账整数溢出测试
- 铸造整数溢出测试
- 费用计算溢出测试
- SafeMath 保护验证
运行安全检测脚本后会生成详细的安全报告,包括:
- ✅ 访问控制检查
- ✅ 重入攻击保护检查
- ✅ 整数溢出保护检查
- ✅ 暂停功能检查
- ✅ 黑名单/白名单功能检查
- ✅ 费用机制检查
- ✅ 供应量限制检查
- ✅ 事件日志检查
- ✅ Gas 优化检查
项目支持以下网络部署:
- Hardhat 本地网络: 开发和测试
- Sepolia 测试网: 测试网部署
- 主网: 生产环境部署
创建 .env 文件并设置以下变量:
SEPOLIA_RPC_URL=your_sepolia_rpc_url
SEPOLIA_PRIVATE_KEY=your_private_key- 私钥安全: 永远不要在代码中硬编码私钥
- 测试网优先: 在主网部署前先在测试网充分测试
- 安全审计: 建议进行专业的安全审计
- Gas 优化: 考虑 Gas 消耗优化
- 升级机制: 考虑合约升级策略
MIT License
欢迎提交 Issue 和 Pull Request 来改进项目。
如有问题,请通过 GitHub Issues 联系。