// ❌ 不安全:多次调用外部函数 contract VulnerableElevator { function goTo(uint _floor) public { Building building = Building(msg.sender); if (!building.isLastFloor(_floor)) { // 第一次调用 floor = _floor; top = building.isLastFloor(floor); // 第二次调用! } } }
// ✅ 安全:只调用一次并缓存结果 contract SecureElevator { function goTo(uint _floor) public { Building building = Building(msg.sender); bool isLast = building.isLastFloor(_floor); // 只调用一次 if (!isLast) { floor = _floor; top = isLast; // 使用缓存的结果 } } }
2. 使用 view 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// ✅ 使用 view 函数防止状态改变 interface Building { function isLastFloor(uint) external view returns (bool); // view 修饰符 }
contract SecureElevator { function goTo(uint _floor) public { Building building = Building(msg.sender); if (!building.isLastFloor(_floor)) { floor = _floor; top = building.isLastFloor(floor); // view 函数保证一致性 } } }
3. 使用白名单机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
contract SecureElevator { mapping(address => bool) public approvedBuildings; address public owner; modifier onlyApprovedBuilding() { require(approvedBuildings[msg.sender], "Unauthorized building"); _; } function addApprovedBuilding(address building) public { require(msg.sender == owner); approvedBuildings[building] = true; } function goTo(uint _floor) public onlyApprovedBuilding { // 安全逻辑 } }
4. 实现内部逻辑
1 2 3 4 5 6 7 8 9 10 11 12
contract SecureElevator { uint public floor; bool public top; uint public topFloor = 10; // 定义最高层 function goTo(uint _floor) public { require(_floor <= topFloor, "Floor too high"); floor = _floor; top = (_floor == topFloor); // 内部判断逻辑 } }
🔧 相关工具和技术
接口安全检测
1 2 3 4 5 6 7 8 9 10 11 12
// 检测接口实现的一致性 contract InterfaceChecker { function checkConsistency(address building, uint floor) public { Building b = Building(building); // 多次调用检查一致性 bool result1 = b.isLastFloor(floor); bool result2 = b.isLastFloor(floor); require(result1 == result2, "Inconsistent interface implementation"); } }