// SPDX-License-Identifier: MIT pragma solidity 0.8.39; /// @title PQRecoveryRegistry /// @notice A neutral, ownerless, immutable registry where any account (EOA, EIP-7702-delegated EOA or smart /// account) commits ahead of time to a post-quantum key, so its owner can later prove control of the account /// without secp256k1. /// /// What it is for: /// - A future quantum-freeze fork can import entries registered before its cutoff as recovery evidence. /// - Smart accounts and wallets can read it today and accept the committed PQ key. /// /// The registry records facts and leaves policy to its readers: /// - `registeredAt`: when the entry was first written. It never changes. /// - `keyAuthorized`: whether the account's own secp256k1 key authorized that write (a direct transaction from an /// account with no code, or its EIP-712 signature), as opposed to contract code (a contract account, an EIP-7702 /// delegate, a session key or a module acting for it). /// - `contestedAt`: when the account first tried to register a different commitment. That never replaces the /// entry; it records a dispute. A fork may honor first-wins, exclude contested entries (an order-independent /// rule), or ignore contests made after a date by which it presumes ECDSA forgeable. /// /// Commitment format: commitment = keccak256(abi.encodePacked(uint8 alg, bytes pk)). The key stays off chain. /// /// Changing an entry never uses ECDSA. Rotation needs the preimage of `rotationHash`, a 32-byte secret that is not /// derived from the secp256k1 key and is unique per chain, account and epoch, spent through seal-then-reveal: /// 1. `seal(sealOf(account, alg, commitment, nextRotationHash, secret))`. Anyone may submit it; it reveals nothing. /// 2. After `ROTATION_DELAY` (7 days), `rotate(...)` reveals the secret. Wallets should check with eth_call that /// the reveal will succeed and send it privately: a reverted reveal still makes the secret public. /// A zero `rotationHash` makes an entry permanent. A rotation hash once spent can never be used again. /// /// Registration: `register` from the account itself, or `registerFor` with the account's EIP-712 signature (or, /// for contract accounts other than EIP-7702 EOAs, ERC-1271 approval) so anyone can pay the gas. /// /// No owner, no upgrade, no pause, no fees. contract PQRecoveryRegistry { // `alg` is an EIP-7932 algorithm type (e.g. 0xD1 ML-DSA-44 per EIP-8051, 0xFA/0xFB Falcon-512 per EIP-8052), so // `commitment` = keccak256(ALG_TYPE || pubkey), the hash EIP-7932 derives an account address from. 0 is invalid // (it is secp256k1). The registry does not restrict the byte further, so schemes added later need no new registry. /// @notice Seconds a seal must age before it can be revealed: the window an owner has to get a reveal included /// if builders censor it. Timestamps, so the delay is the same on every chain. uint256 public constant ROTATION_DELAY = 7 days; /// @notice A `registerFor` deadline must be less than this far past its submission, so every signature expires /// before the earliest possible rotation and cannot be replayed afterwards as a dispute. uint256 public constant MAX_SIGNATURE_LIFETIME = 7 days; bytes32 public constant ROTATION_TAG = keccak256("PQRecoveryRegistry/rotation/v1"); bytes32 public constant SEAL_TAG = keccak256("PQRecoveryRegistry/seal/v1"); /// @notice EIP-712 type of a signed registration, for `registerFor`. bytes32 public constant REGISTER_TYPEHASH = keccak256("Register(address account,uint8 alg,bytes32 commitment,bytes32 rotationHash,uint256 deadline)"); bytes32 internal constant _DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 internal constant _NAME_HASH = keccak256("PQRecoveryRegistry"); bytes32 internal constant _VERSION_HASH = keccak256("1"); /// @dev secp256k1n / 2: signatures with a higher `s` are malleable copies and are refused. uint256 internal constant _HALF_N = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0; bytes4 internal constant _ERC1271_MAGIC = 0x1626ba7e; struct Entry { bytes32 commitment; // keccak256(alg || pk) of the current PQ key bytes32 rotationHash; // see rotationHashOf; 0 = permanent uint64 registeredAt; // timestamp of the first write; what a fork cutoff compares against uint64 updatedAt; // timestamp of the latest change (registration or rotation) uint32 nonce; // number of rotations uint8 alg; bool keyAuthorized; // the account's own secp256k1 key authorized the first write uint64 contestedAt; // timestamp of the first attempt to register a different commitment (0 = never) } /// @dev Slot 0. The layout is normative in the ERC so a fork can read entries straight from state. mapping(address account => Entry) internal _entries; /// @notice Slot 1. seal hash => timestamp it was first submitted (0 = never). mapping(bytes32 seal => uint256) public sealedAt; /// @notice Slot 2. Rotation hashes already revealed; they can never be used again. mapping(bytes32 rotationHash => bool) public spent; event Registered(address indexed account, uint8 alg, bytes32 commitment, bytes32 rotationHash, bool keyAuthorized); event Contested(address indexed account, uint8 alg, bytes32 commitment, bool keyAuthorized); event Sealed(bytes32 indexed seal); event Rotated(address indexed account, uint32 nonce, uint8 alg, bytes32 commitment, bytes32 rotationHash); error AlreadyRegistered(); error NotRegistered(); error BadInput(); error AlreadySealed(); error SealTooYoung(); error SealPredatesUpdate(); error WrongSecret(); error BadDeadline(); error BadSignature(); // ---------------------------------------------------------------- registration /// @notice Commit `msg.sender` to a post-quantum key. The first registration creates the entry; ECDSA can never /// change it afterwards. A later call with a different commitment only records a dispute (`contestedAt`). function register(uint8 alg, bytes32 commitment, bytes32 rotationHash) external { // The account's own key signed this transaction only if the account is the transaction's origin and has no // code: an EIP-7702 delegate (a hook or callback in any transaction the EOA sends) or a frame-validated // account also runs as its origin without the key approving this write. Those accounts can sign `registerFor`. _register(msg.sender, alg, commitment, rotationHash, tx.origin == msg.sender && msg.sender.code.length == 0); } /// @notice The same as `register`, authorized by `account`'s EIP-712 signature so anyone can pay the gas: a /// wallet, a relayer, or a batch for accounts that hold no ETH. Contract accounts other than EIP-7702 EOAs may /// approve through ERC-1271 instead. function registerFor( address account, uint8 alg, bytes32 commitment, bytes32 rotationHash, uint256 deadline, bytes calldata signature ) external { if (block.timestamp > deadline || deadline >= block.timestamp + MAX_SIGNATURE_LIFETIME) revert BadDeadline(); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator(), keccak256(abi.encode(REGISTER_TYPEHASH, account, alg, commitment, rotationHash, deadline)) ) ); if (account != address(0) && _ecdsaSigner(digest, signature) == account) { _register(account, alg, commitment, rotationHash, true); } else if (_approvedBy1271(account, digest, signature)) { _register(account, alg, commitment, rotationHash, false); } else { revert BadSignature(); } } function _register(address account, uint8 alg, bytes32 commitment, bytes32 rotationHash, bool keyAuthorized) internal { if (account == address(0) || alg == 0 || commitment == 0) revert BadInput(); Entry storage e = _entries[account]; if (e.registeredAt != 0) { // Same commitment: nothing to record. A different one is a dispute, recorded once and never applied. if (e.commitment == commitment && e.alg == alg) revert AlreadyRegistered(); if (e.contestedAt == 0) e.contestedAt = uint64(block.timestamp); emit Contested(account, alg, commitment, keyAuthorized); return; } e.commitment = commitment; e.rotationHash = rotationHash; e.alg = alg; e.keyAuthorized = keyAuthorized; e.registeredAt = uint64(block.timestamp); e.updatedAt = uint64(block.timestamp); emit Registered(account, alg, commitment, rotationHash, keyAuthorized); } /// @dev The secp256k1 signer of `digest`, or 0. Only 65-byte signatures with low `s` and v 27/28. function _ecdsaSigner(bytes32 digest, bytes calldata signature) internal pure returns (address) { if (signature.length != 65) return address(0); bytes32 r = bytes32(signature[0:32]); bytes32 s = bytes32(signature[32:64]); uint8 v = uint8(signature[64]); if (uint256(s) > _HALF_N || (v != 27 && v != 28)) return address(0); return ecrecover(digest, v, r, s); } /// @dev True if `account` is a contract (not an EIP-7702 EOA) that approves `digest` through ERC-1271. A 7702 /// EOA always has its own key, so its delegate never speaks for it here. Reads at most 32 bytes of the reply. function _approvedBy1271(address account, bytes32 digest, bytes calldata signature) internal view returns (bool) { bytes memory code = account.code; if (code.length == 0 || (code.length == 23 && bytes3(code) == 0xef0100)) return false; bytes memory data = abi.encodeWithSelector(_ERC1271_MAGIC, digest, signature); bool ok; bytes32 word; assembly ("memory-safe") { ok := staticcall(gas(), account, add(data, 32), mload(data), 0, 32) word := mload(0) ok := and(ok, gt(returndatasize(), 31)) } return ok && word == bytes32(_ERC1271_MAGIC); } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(_DOMAIN_TYPEHASH, _NAME_HASH, _VERSION_HASH, block.chainid, address(this))); } // ---------------------------------------------------------------- rotation /// @notice Step 1 of a rotation: record an opaque seal. Anyone may call it. function seal(bytes32 sealHash) external { if (sealHash == 0) revert BadInput(); if (sealedAt[sealHash] != 0) revert AlreadySealed(); sealedAt[sealHash] = block.timestamp; emit Sealed(sealHash); } /// @notice Step 2: reveal the secret and move the account to a new key and a new rotation hash (0 = make the /// entry permanent). Anyone may submit it, such as a sponsor paying gas for an account that can no longer send /// ECDSA transactions. function rotate(address account, uint8 alg, bytes32 commitment, bytes32 nextRotationHash, bytes32 secret) external { if (alg == 0 || commitment == 0 || secret == 0) revert BadInput(); Entry storage e = _entries[account]; if (e.registeredAt == 0) revert NotRegistered(); bytes32 current = e.rotationHash; if (rotationHashOf(account, secret) != current) revert WrongSecret(); // A revealed hash is public forever; reusing one (directly or as A -> B -> A) would hand the entry over. if (nextRotationHash != 0 && (nextRotationHash == current || spent[nextRotationHash])) revert BadInput(); uint256 sealTime = sealedAt[sealOf(account, alg, commitment, nextRotationHash, secret)]; if (sealTime == 0 || block.timestamp < sealTime + ROTATION_DELAY) revert SealTooYoung(); // A seal made before the last change belongs to an older epoch. if (sealTime < e.updatedAt) revert SealPredatesUpdate(); spent[current] = true; e.commitment = commitment; e.rotationHash = nextRotationHash; e.alg = alg; e.updatedAt = uint64(block.timestamp); unchecked { ++e.nonce; } emit Rotated(account, e.nonce, alg, commitment, nextRotationHash); } // ---------------------------------------------------------------- reads function entryOf(address account) external view returns (Entry memory) { return _entries[account]; } /// @notice Batch read for wallets, indexers and fork tooling. function entriesOf(address[] calldata accounts) external view returns (Entry[] memory out) { out = new Entry[](accounts.length); for (uint256 i; i < accounts.length; ++i) { out[i] = _entries[accounts[i]]; } } /// @notice True if `account` had an entry at or before timestamp `cutoff`. Readers apply their own policy to /// `keyAuthorized` and `contestedAt`. function registeredBy(address account, uint256 cutoff) external view returns (bool) { uint64 r = _entries[account].registeredAt; return r != 0 && r <= cutoff; } function commitmentOf(uint8 alg, bytes calldata pk) external pure returns (bytes32) { return keccak256(abi.encodePacked(alg, pk)); } function rotationHashOf(address account, bytes32 secret) public view returns (bytes32) { return keccak256(abi.encode(ROTATION_TAG, block.chainid, address(this), account, secret)); } function sealOf(address account, uint8 alg, bytes32 commitment, bytes32 nextRotationHash, bytes32 secret) public view returns (bytes32) { return keccak256( abi.encode(SEAL_TAG, block.chainid, address(this), account, alg, commitment, nextRotationHash, secret) ); } }