// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {HashSig} from "./HashSig.sol"; /// @title QuantumVaultV2: the two-key vault plus scoped agent keys and sentinel (panic) keys. /// @notice Everything in v1 works the same. Added: /// - Agent keys: extra classical keys for AI agents or apps. Each one may only `agentSpend` tokens, up to its own daily /// limit per token, only to targets it is allowed to pay (or any target if set), and only until it expires. An agent /// key cannot change anything and cannot make arbitrary calls. /// - Sentinel keys: keys a watchdog can hold. A sentinel can only make the vault stricter: freeze all classical spending /// (daily key and agent keys) or revoke one agent. It can never move funds and can never unfreeze. /// - Unfreezing, adding agents, setting their limits and targets, and choosing sentinels all need the vault key. /// @notice /// - Daily key (classical, e.g. MetaMask): may only `spend` up to a per-token daily limit. It cannot change /// anything: not the limits, not the keys, not the guardians. If a quantum computer recovers this key from its /// public key, the most it can take is one day's limit. /// - Vault key (post-quantum, HashSig): authorises everything else through `execute`, including every setting. /// Anyone (a relayer, or the owner's own wallet) may submit an `execute`; the signature is checked here, on /// chain, so the submitter is never trusted. /// - Guardians: an optional M-of-N recovery that sets a new vault key after a delay. The vault key can cancel a /// pending recovery at any time during the delay. /// There is no upgrade path and no admin. The code at this address is the code forever. contract QuantumVaultV2 { struct Call { address target; uint256 value; bytes data; } struct Spent { uint64 day; uint192 amount; } bytes32 public constant OP_TYPEHASH = keccak256("PQVAULT_OP_V1"); uint8 public constant MAX_HEIGHT = 16; // daily key address public owner; mapping(address => uint256) public dailyLimit; // token => limit; address(0) = native ETH mapping(address => Spent) internal _spent; // vault key (post-quantum) bytes32 public root; bytes32 public pubSeed; uint32 public nextIndex; // lowest leaf that may still sign; every accepted signature moves it past its leaf uint32 public policyVersion; // bumped on every key change; part of every signed digest uint8 public height; bool private _initialized; // agent keys struct Agent { uint64 expiry; bool active; bool anyTarget; } mapping(address => Agent) public agents; mapping(address => mapping(address => uint256)) public agentLimit; // agent => token => daily limit mapping(address => mapping(address => Spent)) internal _agentSpent; // agent => token => spent today mapping(address => mapping(address => bool)) public agentTarget; // agent => target => allowed address[] internal _agentList; // sentinels and freeze mapping(address => bool) public sentinel; bool public frozen; // guardians address[] internal _guardians; uint8 public threshold; uint32 public recoveryDelay; uint32 public recoveryEpoch; // bumped to void every pending recovery mapping(bytes32 => uint256) public approvals; // recovery id => bitmask of guardian indices mapping(bytes32 => uint64) public readyAt; // recovery id => time it may execute (0 = threshold not met) event Initialized(address indexed owner, bytes32 root, uint8 height); event Executed(uint32 indexed policyVersion, uint32 leafIndex, bytes32 digest); event Spend(address indexed token, address indexed to, uint256 amount); event KeyRotated(uint32 indexed policyVersion, bytes32 root, uint8 height); event OwnerSet(address owner); event LimitSet(address indexed token, uint256 limit); event GuardiansSet(address[] guardians, uint8 threshold, uint32 delay); event RecoveryApproved(bytes32 indexed id, address indexed guardian, uint64 readyAt); event RecoveryExecuted(bytes32 indexed id); event RecoveryCancelled(uint32 epoch); event AgentSet(address indexed agent, uint64 expiry, bool anyTarget); event AgentRevoked(address indexed agent, address by); event AgentLimitSet(address indexed agent, address indexed token, uint256 limit); event AgentTargetSet(address indexed agent, address indexed target, bool allowed); event AgentSpend(address indexed agent, address indexed token, address indexed to, uint256 amount); event SentinelSet(address indexed sentinel, bool allowed); event Frozen(address by); event Unfrozen(); error AlreadyInitialized(); error NotSelf(); error NotOwner(); error NotGuardian(); error Expired(); error BadIndex(); error BadSignature(); error OverLimit(); error BadConfig(); error NotReady(); error CallFailed(uint256 index, bytes reason); error TransferFailed(); error NotAgent(); error AgentExpired(); error TargetNotAllowed(); error IsFrozen(); error NotSentinel(); constructor() { _initialized = true; // the implementation itself can never be initialised } modifier onlySelf() { if (msg.sender != address(this)) revert NotSelf(); _; } function initialize(address owner_, bytes32 root_, bytes32 pubSeed_, uint8 height_, uint256 ethLimit) external { if (_initialized) revert AlreadyInitialized(); _initialized = true; if (root_ == 0 || height_ == 0 || height_ > MAX_HEIGHT) revert BadConfig(); owner = owner_; root = root_; pubSeed = pubSeed_; height = height_; dailyLimit[address(0)] = ethLimit; emit Initialized(owner_, root_, height_); } // ---------------------------------------------------------------- vault key /// @notice The digest the vault key signs for a batch of calls. function opDigest(Call[] calldata calls, uint32 leafIndex, uint64 deadline) public view returns (bytes32) { return keccak256( abi.encode(OP_TYPEHASH, block.chainid, address(this), policyVersion, leafIndex, deadline, keccak256(abi.encode(calls))) ); } /// @notice Run a batch of calls authorised by a post-quantum signature. Callable by anyone. function execute(Call[] calldata calls, uint32 leafIndex, uint64 deadline, bytes32[67] calldata sig, bytes32[] calldata path) external returns (bytes[] memory results) { if (block.timestamp > deadline) revert Expired(); if (leafIndex < nextIndex || path.length != height || leafIndex >> height != 0) revert BadIndex(); bytes32 digest = opDigest(calls, leafIndex, deadline); if (HashSig.rootOf(pubSeed, leafIndex, digest, sig, path) != root) revert BadSignature(); nextIndex = leafIndex + 1; // this one-time key, and every lower one, is spent emit Executed(policyVersion, leafIndex, digest); results = new bytes[](calls.length); for (uint256 i; i < calls.length; ++i) { (bool ok, bytes memory r) = calls[i].target.call{value: calls[i].value}(calls[i].data); if (!ok) revert CallFailed(i, r); results[i] = r; } } /// @notice Replace the vault key: a new tree, a new policy version. The old key stops working in this block. function rotate(bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight) external onlySelf { _setKey(newRoot, newPubSeed, newHeight); } function setOwner(address newOwner) external onlySelf { owner = newOwner; emit OwnerSet(newOwner); } function setDailyLimit(address token, uint256 limit) external onlySelf { dailyLimit[token] = limit; emit LimitSet(token, limit); } function setGuardians(address[] calldata guardians_, uint8 threshold_, uint32 delay) external onlySelf { if (guardians_.length > 8 || threshold_ > guardians_.length || (guardians_.length > 0 && (threshold_ == 0 || delay < 1 days))) revert BadConfig(); _guardians = guardians_; threshold = threshold_; recoveryDelay = delay; unchecked { ++recoveryEpoch; } emit GuardiansSet(guardians_, threshold_, delay); } function cancelRecovery() external onlySelf { unchecked { ++recoveryEpoch; } emit RecoveryCancelled(recoveryEpoch); } // ---------------------------------------------------------------- daily key /// @notice Classical-key spending, capped per token per UTC day. function spend(address token, address to, uint256 amount) external { if (msg.sender != owner || msg.sender == address(0)) revert NotOwner(); if (frozen) revert IsFrozen(); uint64 day = uint64(block.timestamp / 1 days); Spent storage s = _spent[token]; uint256 used = (s.day == day ? s.amount : 0) + amount; if (used > dailyLimit[token]) revert OverLimit(); s.day = day; s.amount = uint192(used); _send(token, to, amount); emit Spend(token, to, amount); } function spentToday(address token) external view returns (uint256) { Spent storage s = _spent[token]; return s.day == uint64(block.timestamp / 1 days) ? s.amount : 0; } // ---------------------------------------------------------------- agent keys /// @notice Add or update an agent key. `expiry` is a unix time; `anyTarget` lets it pay any address. function setAgent(address agent, uint64 expiry, bool anyTarget) external onlySelf { if (agent == address(0) || expiry <= block.timestamp) revert BadConfig(); if (!agents[agent].active && agents[agent].expiry == 0) _agentList.push(agent); agents[agent] = Agent(expiry, true, anyTarget); emit AgentSet(agent, expiry, anyTarget); } function setAgentLimit(address agent, address token, uint256 limit) external onlySelf { agentLimit[agent][token] = limit; emit AgentLimitSet(agent, token, limit); } function setAgentTarget(address agent, address target, bool allowed) external onlySelf { agentTarget[agent][target] = allowed; emit AgentTargetSet(agent, target, allowed); } /// @notice The vault key, the daily key or a sentinel can switch an agent off. Turning it back on needs the vault key. function revokeAgent(address agent) external { if (msg.sender != address(this) && msg.sender != owner && !sentinel[msg.sender]) revert NotSentinel(); agents[agent].active = false; emit AgentRevoked(agent, msg.sender); } /// @notice An agent pays `amount` of `token` (address(0) = native coin) to `to`, inside its own daily limit. function agentSpend(address token, address to, uint256 amount) external { Agent memory a = agents[msg.sender]; if (!a.active) revert NotAgent(); if (block.timestamp > a.expiry) revert AgentExpired(); if (frozen) revert IsFrozen(); if (!a.anyTarget && !agentTarget[msg.sender][to]) revert TargetNotAllowed(); uint64 day = uint64(block.timestamp / 1 days); Spent storage s = _agentSpent[msg.sender][token]; uint256 used = (s.day == day ? s.amount : 0) + amount; if (used > agentLimit[msg.sender][token]) revert OverLimit(); s.day = day; s.amount = uint192(used); _send(token, to, amount); emit AgentSpend(msg.sender, token, to, amount); } function agentSpentToday(address agent, address token) external view returns (uint256) { Spent storage s = _agentSpent[agent][token]; return s.day == uint64(block.timestamp / 1 days) ? s.amount : 0; } function agentList() external view returns (address[] memory) { return _agentList; } // ---------------------------------------------------------------- sentinels function setSentinel(address who, bool allowed) external onlySelf { sentinel[who] = allowed; emit SentinelSet(who, allowed); } /// @notice Stops every classical spend (daily key and agents). The vault key still works. Only the vault key unfreezes. function freeze() external { if (msg.sender != address(this) && msg.sender != owner && !sentinel[msg.sender]) revert NotSentinel(); frozen = true; emit Frozen(msg.sender); } function unfreeze() external onlySelf { frozen = false; emit Unfrozen(); } // ---------------------------------------------------------------- guardians function recoveryId(address newOwner, bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight) public view returns (bytes32) { return keccak256(abi.encode(address(this), recoveryEpoch, newOwner, newRoot, newPubSeed, newHeight)); } function approveRecovery(address newOwner, bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight) external { uint256 n = _guardians.length; uint256 g = type(uint256).max; for (uint256 i; i < n; ++i) if (_guardians[i] == msg.sender) g = i; if (g == type(uint256).max) revert NotGuardian(); bytes32 id = recoveryId(newOwner, newRoot, newPubSeed, newHeight); uint256 mask = approvals[id] | (1 << g); approvals[id] = mask; if (readyAt[id] == 0 && _popcount(mask) >= threshold) readyAt[id] = uint64(block.timestamp) + recoveryDelay; emit RecoveryApproved(id, msg.sender, readyAt[id]); } function executeRecovery(address newOwner, bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight) external { bytes32 id = recoveryId(newOwner, newRoot, newPubSeed, newHeight); uint64 t = readyAt[id]; if (t == 0 || block.timestamp < t) revert NotReady(); unchecked { ++recoveryEpoch; } owner = newOwner; emit OwnerSet(newOwner); _setKey(newRoot, newPubSeed, newHeight); emit RecoveryExecuted(id); } function guardians() external view returns (address[] memory) { return _guardians; } // ---------------------------------------------------------------- internals function _setKey(bytes32 newRoot, bytes32 newPubSeed, uint8 newHeight) internal { if (newRoot == 0 || newHeight == 0 || newHeight > MAX_HEIGHT) revert BadConfig(); root = newRoot; pubSeed = newPubSeed; height = newHeight; nextIndex = 0; unchecked { ++policyVersion; } emit KeyRotated(policyVersion, newRoot, newHeight); } function _send(address token, address to, uint256 amount) internal { bool ok; if (token == address(0)) { (ok,) = to.call{value: amount}(""); } else { bytes memory r; (ok, r) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount)); ok = ok && (r.length == 0 ? token.code.length > 0 : abi.decode(r, (bool))); } if (!ok) revert TransferFailed(); } function _popcount(uint256 x) private pure returns (uint256 c) { for (; x != 0; x &= x - 1) ++c; } receive() external payable {} function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) { return 0x150b7a02; } function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) { return 0xf23a6e61; } function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) external pure returns (bytes4) { return 0xbc197c81; } function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x150b7a02 || id == 0x4e2312e0; } }