// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IMLDSA65Verifier { function verify(bytes calldata m, bytes calldata ctx, bytes calldata sig, address dataA, address dataB) external view returns (bool); } interface ISLHDSA128sVerifier { function verify(bytes calldata m, bytes calldata ctx, bytes calldata sig, bytes32 pk) external view returns (bool); } /// @title QuantumVaultV3: a vault whose keys are two NIST post-quantum signature standards. /// @notice /// - Primary key, ML-DSA-65 (FIPS 204): authorises every withdrawal and every setting through `execute`, with no limit /// on the number of signatures. Each operation carries a nonce, so a signature works once. Anyone may submit it; /// the signature is checked on chain by MLDSA65Verifier against the key data this vault was created with. /// - Recovery key, SLH-DSA-SHA2-128s (FIPS 205): a hash-based key meant to stay offline. It can only start replacing /// the primary key. The change waits `keyRecoveryDelay` (at least one day), during which the primary key can /// cancel it and a Sentinel can raise the alarm. /// - Daily key (classical): spends up to per-token daily limits and changes nothing, as in v1/v2. /// - Agent keys, Sentinels, freeze and guardian recovery: as in QuantumVaultV2. /// No admin, no upgrade path. The verifiers are fixed when the implementation is deployed. contract QuantumVaultV3 { struct Call { address target; uint256 value; bytes data; } struct Spent { uint64 day; uint192 amount; } struct Agent { uint64 expiry; bool active; bool anyTarget; } struct PrimaryKey { address dataA; // Â, ExpandA(ρ) in the NTT domain (MLDSA65Verifier layout) address dataB; // tr || NTT(t1·2^d) bytes32 pkHash; // keccak256 of the 1,952-byte public key, for audits (MLDSA65Verifier.checkExpansion) } bytes32 public constant OP_TYPEHASH = keccak256("HASHFORT_V3_OP"); bytes32 public constant RECOVERY_TYPEHASH = keccak256("HASHFORT_V3_RECOVERY"); bytes public constant OP_CONTEXT = "HASHFORT_V3_OP"; bytes public constant RECOVERY_CONTEXT = "HASHFORT_V3_RECOVERY"; uint256 internal constant A_CODE = 23041; // 1 + 30 * 768 uint256 internal constant B_CODE = 4673; // 1 + 64 + 6 * 768 IMLDSA65Verifier public immutable mldsa; ISLHDSA128sVerifier public immutable slhdsa; // daily key address public owner; mapping(address => uint256) public dailyLimit; mapping(address => Spent) internal _spent; // primary key (ML-DSA-65) and recovery key (SLH-DSA-SHA2-128s) PrimaryKey public primary; bytes32 public recoveryKey; // PK.seed || PK.root uint64 public nonce; // operations signed by the primary key so far uint64 public recoveryNonce; // key-recovery requests signed by the recovery key so far uint32 public policyVersion; // bumped on every key change; part of every signed digest uint32 public keyRecoveryDelay; PrimaryKey public pendingKey; uint64 public pendingKeyReadyAt; // 0 = nothing pending bool private _initialized; // agent keys mapping(address => Agent) public agents; mapping(address => mapping(address => uint256)) public agentLimit; mapping(address => mapping(address => Spent)) internal _agentSpent; mapping(address => mapping(address => bool)) public agentTarget; 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; mapping(bytes32 => uint256) public approvals; mapping(bytes32 => uint64) public readyAt; event Initialized(address indexed owner, bytes32 pkHash, bytes32 recoveryKey); event Executed(uint64 indexed nonce, bytes32 digest); event Spend(address indexed token, address indexed to, uint256 amount); event PrimaryKeySet(uint32 indexed policyVersion, address dataA, address dataB, bytes32 pkHash); event RecoveryKeySet(bytes32 recoveryKey); event KeyRecoveryStarted(bytes32 indexed pkHash, uint64 readyAt); event KeyRecoveryCancelled(); 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 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(); error NoRecoveryKey(); constructor(IMLDSA65Verifier mldsa_, ISLHDSA128sVerifier slhdsa_) { mldsa = mldsa_; slhdsa = slhdsa_; _initialized = true; // the implementation itself can never be initialised } modifier onlySelf() { if (msg.sender != address(this)) revert NotSelf(); _; } function initialize(address owner_, PrimaryKey calldata key, bytes32 recoveryKey_, uint256 ethLimit) external { if (_initialized) revert AlreadyInitialized(); _initialized = true; owner = owner_; _checkKey(key); primary = key; recoveryKey = recoveryKey_; keyRecoveryDelay = 2 days; dailyLimit[address(0)] = ethLimit; emit Initialized(owner_, key.pkHash, recoveryKey_); } // ---------------------------------------------------------------- primary key (ML-DSA-65) /// @notice The 32-byte digest the primary key signs (ML-DSA-65, context "HASHFORT_V3_OP") for a batch of calls. function opDigest(Call[] calldata calls, uint64 deadline) public view returns (bytes32) { return keccak256(abi.encode(OP_TYPEHASH, block.chainid, address(this), policyVersion, nonce, deadline, keccak256(abi.encode(calls)))); } /// @notice Run a batch of calls authorised by an ML-DSA-65 signature. Callable by anyone (a relayer, or the owner). function execute(Call[] calldata calls, uint64 deadline, bytes calldata sig) external returns (bytes[] memory results) { if (block.timestamp > deadline) revert Expired(); bytes32 digest = opDigest(calls, deadline); PrimaryKey memory k = primary; if (!mldsa.verify(abi.encodePacked(digest), OP_CONTEXT, sig, k.dataA, k.dataB)) revert BadSignature(); emit Executed(nonce, digest); unchecked { ++nonce; } 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 primary key (signed by the current primary key). Cancels any pending key recovery. function setPrimaryKey(PrimaryKey calldata key) external onlySelf { _setPrimary(key); } function setRecoveryKey(bytes32 recoveryKey_) external onlySelf { recoveryKey = recoveryKey_; _clearPending(); emit RecoveryKeySet(recoveryKey_); } function setKeyRecoveryDelay(uint32 delay) external onlySelf { if (delay < 1 days) revert BadConfig(); keyRecoveryDelay = delay; } // ---------------------------------------------------------------- recovery key (SLH-DSA-SHA2-128s) /// @notice The 32-byte digest the recovery key signs (SLH-DSA, context "HASHFORT_V3_RECOVERY") to propose a new primary key. function recoveryDigest(PrimaryKey calldata key, uint64 deadline) public view returns (bytes32) { return keccak256(abi.encode(RECOVERY_TYPEHASH, block.chainid, address(this), policyVersion, recoveryNonce, key.dataA, key.dataB, key.pkHash, deadline)); } /// @notice Start replacing the primary key with a recovery-key signature. Takes effect after keyRecoveryDelay /// unless the primary key cancels it. Callable by anyone. function startKeyRecovery(PrimaryKey calldata key, uint64 deadline, bytes calldata sig) external { if (recoveryKey == 0) revert NoRecoveryKey(); if (block.timestamp > deadline) revert Expired(); _checkKey(key); bytes32 digest = recoveryDigest(key, deadline); if (!slhdsa.verify(abi.encodePacked(digest), RECOVERY_CONTEXT, sig, recoveryKey)) revert BadSignature(); unchecked { ++recoveryNonce; } pendingKey = key; pendingKeyReadyAt = uint64(block.timestamp) + keyRecoveryDelay; emit KeyRecoveryStarted(key.pkHash, pendingKeyReadyAt); } /// @notice Complete a key recovery after its delay. Callable by anyone. function finishKeyRecovery() external { uint64 t = pendingKeyReadyAt; if (t == 0 || block.timestamp < t) revert NotReady(); PrimaryKey memory key = pendingKey; _setPrimary(key); } // ---------------------------------------------------------------- settings (primary key only) 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); } /// @notice Cancel every pending recovery: guardian requests and a recovery-key request. function cancelRecovery() external onlySelf { unchecked { ++recoveryEpoch; } _clearPending(); emit RecoveryCancelled(recoveryEpoch); } // ---------------------------------------------------------------- daily key 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 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); } 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); } 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); } 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 (replace daily, primary and recovery keys) function recoveryId(address newOwner, PrimaryKey calldata key, bytes32 newRecoveryKey) public view returns (bytes32) { return keccak256(abi.encode(address(this), recoveryEpoch, newOwner, key.dataA, key.dataB, key.pkHash, newRecoveryKey)); } function approveRecovery(address newOwner, PrimaryKey calldata key, bytes32 newRecoveryKey) 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, key, newRecoveryKey); 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, PrimaryKey calldata key, bytes32 newRecoveryKey) external { bytes32 id = recoveryId(newOwner, key, newRecoveryKey); uint64 t = readyAt[id]; if (t == 0 || block.timestamp < t) revert NotReady(); unchecked { ++recoveryEpoch; } owner = newOwner; emit OwnerSet(newOwner); recoveryKey = newRecoveryKey; emit RecoveryKeySet(newRecoveryKey); _setPrimary(key); emit RecoveryExecuted(id); } function guardians() external view returns (address[] memory) { return _guardians; } // ---------------------------------------------------------------- internals function _checkKey(PrimaryKey memory key) internal view { if (key.dataA.code.length != A_CODE || key.dataB.code.length != B_CODE || key.pkHash == 0) revert BadConfig(); } function _setPrimary(PrimaryKey memory key) internal { _checkKey(key); primary = key; _clearPending(); unchecked { ++policyVersion; } emit PrimaryKeySet(policyVersion, key.dataA, key.dataB, key.pkHash); } function _clearPending() internal { if (pendingKeyReadyAt != 0) { delete pendingKey; pendingKeyReadyAt = 0; emit KeyRecoveryCancelled(); } } 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; } }