問題一覧に戻る
上級セキュリティパターン
問題80: タイムロック
Solidityのタイムロックパターンを学習 - 重要操作に遅延を強制。タイムロックは、実行前に必須の待機期間を持つトランザクションをキューに入れ、透明性を提供し、ユーザーが変更に反応できるようにします。このパターンはガバナンスシステム、管理アクション、プロトコルアップグレードに不可欠。悪意のある即時変更を防ぎ、予測可能性を通じて信頼を構築。遅延期間はセキュリティと運用効率のバランスを取ります。タイムロックの理解は、DeFiプロトコルにおける分散型ガバナンスと安全な管理システムの構築に重要です。
pragma solidity ^0.8.0;
contract TimeLock {
uint256 public constant DELAY = 2 days;
struct Transaction {
address target;
uint256 value;
bytes data;
uint256 executeTime;
}
mapping(bytes32 => Transaction) public transactions;
// 遅延付きでトランザクションをキュー
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
bytes32 txHash = keccak256(abi.encode(target, value, data));
// タイムロック遅延を追加
uint256 executeTime = block.timestamp + ;
transactions[txHash] = Transaction({
target: target,
value: value,
data: data,
executeTime: executeTime
});
return txHash;
}
// 遅延後に実行
function executeTransaction(bytes32 txHash) public payable {
Transaction memory tx = transactions[txHash];
// タイムロック経過を確認
require(block.timestamp >= tx., "Too early");
require(tx.target != address(0), "Invalid tx");
// 実行済みトランザクションをクリア
delete transactions[];
(bool success, ) = tx.target.call{value: tx.value}(tx.data);
require(success, "Execution failed");
}
}