// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {HashSig} from "./HashSig.sol"; /// @title QuantumVault: a smart account with two keys. /// @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 QuantumVault { 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; // 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); 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(); 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(); 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; } // ---------------------------------------------------------------- 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; } }