// SPDX-License-Identifier: MIT pragma solidity 0.8.28; /// @title QuantumVault /// @notice A vault that only obeys hash-based one-time signatures (WOTS+ w=16, Merkle h=10, keccak256). /// No ECDSA key has any authority over the funds. Any address may relay a signed operation /// and pay gas. Tightening a rule is immediate; loosening it waits DELAY. /// @dev Signature format is byte-identical to the Quantum Wallet browser signer (pq.js). /// UNAUDITED. Use small amounts until a professional audit is complete. contract QuantumVault { // ---------- constants ---------- uint256 public constant LEAVES = 1024; uint256 public constant HEIGHT = 10; uint256 public constant LEN = 67; uint256 public constant DELAY = 1 days; uint256 public constant RECOVERY_DELAY = 3 days; uint8 public constant OP_TRANSFER = 0; uint8 public constant OP_CANCEL = 1; uint8 public constant OP_SET_POLICY = 2; uint8 public constant OP_ALLOW = 3; uint8 public constant OP_FREEZE = 4; uint8 public constant OP_ADD_GUARDIAN = 5; uint8 public constant OP_ROTATE = 6; uint8 public constant OP_CANCEL_RECOVERY = 7; // ---------- key state ---------- bytes32 public root; bytes32 public pubSeed; uint8 public tree; uint16 public nextLeaf; // ---------- policy ---------- uint256 public dailyCap; // native HYPE wei per UTC day, 0 = off uint256 public lockThreshold; // native transfers above this wait DELAY, 0 = off (tokens always wait when on) bool public whitelistOn; bool public frozen; mapping(address => bool) public allowed; uint256 public spentDay; uint256 public spentAmount; // ---------- guardians / recovery ---------- address[] public guardians; mapping(address => bytes32) public recoveryVote; bytes32 public recoveryRoot; bytes32 public recoveryPub; uint64 public recoveryEta; // ---------- delayed operations ---------- struct Op { uint8 kind; address a; address t; uint256 x; uint256 y; bool f; } struct Pending { uint8 kind; address a; address t; uint256 x; uint256 y; bool f; uint64 eta; bool done; } Pending[] public pending; uint256 private _lock = 1; // ---------- events ---------- event Received(address indexed from, uint256 amount); event Signed(uint8 indexed tree, uint16 indexed leaf, uint8 kind); event Sent(address indexed token, address indexed to, uint256 amount); event Queued(uint256 indexed id, uint8 kind, uint64 eta); event Released(uint256 indexed id); event Cancelled(uint256 indexed id); event PolicyChanged(uint256 dailyCap, uint256 lockThreshold, bool whitelistOn); event Allowed(address indexed who, bool ok); event Frozen(bool frozen); event GuardianAdded(address indexed g); event Rotated(uint8 tree, bytes32 root); event RecoveryStarted(bytes32 root, bytes32 pub, uint64 eta); event RecoveryCancelled(); event Recovered(bytes32 root, bytes32 pub); error BadLeaf(); error BadSignature(); error IsFrozen(); error NotAllowed(); error OverCap(); error NotReady(); error Done(); error SendFailed(); error NotGuardian(); error TooMany(); error Locked(); modifier nonReentrant() { if (_lock != 1) revert Locked(); _lock = 2; _; _lock = 1; } constructor(bytes32 root_, bytes32 pubSeed_, uint256 dailyCap_, uint256 lockThreshold_) payable { root = root_; pubSeed = pubSeed_; dailyCap = dailyCap_; lockThreshold = lockThreshold_; } receive() external payable { emit Received(msg.sender, msg.value); } // ===================================================================== // Signed entry point // ===================================================================== /// @notice Hash that the owner signs for `op` with leaf `leaf`. function digest(Op calldata op, uint16 leaf) public view returns (bytes32) { bytes memory m = abi.encode(block.chainid, address(this), tree, leaf, op.kind, op.a, op.t, op.x, op.y, op.f); return keccak256(abi.encodePacked("qw-msg", m)); } function execute(Op calldata op, uint16 leaf, bytes32[67] calldata sig, bytes32[10] calldata auth) external nonReentrant { if (leaf < nextLeaf || leaf >= LEAVES) revert BadLeaf(); // skipping exposed leaves is allowed, reuse never is if (!_verify(digest(op, leaf), leaf, sig, auth)) revert BadSignature(); nextLeaf = leaf + 1; emit Signed(tree, leaf, op.kind); _apply(op); } // ===================================================================== // Delayed operations (anyone may release once ready) // ===================================================================== function release(uint256 id) external nonReentrant { Pending storage p = pending[id]; if (p.done) revert Done(); if (block.timestamp < p.eta) revert NotReady(); if (p.kind == OP_TRANSFER && frozen) revert IsFrozen(); p.done = true; emit Released(id); if (p.kind == OP_TRANSFER) { if (whitelistOn && !allowed[p.a]) revert NotAllowed(); _send(p.t, p.a, p.x); } else if (p.kind == OP_SET_POLICY) { _setPolicy(p.x, p.y, p.f); } else if (p.kind == OP_ALLOW) { allowed[p.a] = true; emit Allowed(p.a, true); } else if (p.kind == OP_FREEZE) { frozen = false; emit Frozen(false); } else if (p.kind == OP_ADD_GUARDIAN) { _addGuardian(p.a); } } // ===================================================================== // Guardian recovery: 2 matching votes, then RECOVERY_DELAY. Owner can cancel. // ===================================================================== function proposeRecovery(bytes32 newRoot, bytes32 newPub) external { if (!isGuardian(msg.sender)) revert NotGuardian(); bytes32 h = keccak256(abi.encode(newRoot, newPub)); recoveryVote[msg.sender] = h; uint256 votes; for (uint256 i; i < guardians.length; i++) if (recoveryVote[guardians[i]] == h) votes++; if (votes >= 2 && recoveryEta == 0) { recoveryRoot = newRoot; recoveryPub = newPub; recoveryEta = uint64(block.timestamp + RECOVERY_DELAY); emit RecoveryStarted(newRoot, newPub, recoveryEta); } } function finishRecovery() external { if (recoveryEta == 0 || block.timestamp < recoveryEta) revert NotReady(); root = recoveryRoot; pubSeed = recoveryPub; tree = 0; nextLeaf = 0; frozen = false; _clearRecovery(); emit Recovered(root, pubSeed); } // ===================================================================== // Views // ===================================================================== function isGuardian(address g) public view returns (bool) { for (uint256 i; i < guardians.length; i++) if (guardians[i] == g) return true; return false; } function guardianList() external view returns (address[] memory) { return guardians; } function pendingCount() external view returns (uint256) { return pending.length; } function spentToday() public view returns (uint256) { return spentDay == block.timestamp / 1 days ? spentAmount : 0; } function state() external view returns ( bytes32 root_, bytes32 pub_, uint8 tree_, uint16 nextLeaf_, uint256 dailyCap_, uint256 lockThreshold_, bool whitelistOn_, bool frozen_, uint256 spentToday_, uint256 balance_, uint256 pending_, uint256 guardians_, uint64 recoveryEta_ ) { return (root, pubSeed, tree, nextLeaf, dailyCap, lockThreshold, whitelistOn, frozen, spentToday(), address(this).balance, pending.length, guardians.length, recoveryEta); } // ===================================================================== // Internals // ===================================================================== function _apply(Op calldata op) internal { uint8 k = op.kind; if (k == OP_TRANSFER) { if (frozen) revert IsFrozen(); if (whitelistOn && !allowed[op.a]) revert NotAllowed(); bool delayed; if (op.t == address(0)) { if (dailyCap != 0) { uint256 day = block.timestamp / 1 days; if (day != spentDay) { spentDay = day; spentAmount = 0; } if (spentAmount + op.x > dailyCap) revert OverCap(); spentAmount += op.x; } delayed = lockThreshold != 0 && op.x > lockThreshold; } else { delayed = lockThreshold != 0; } if (delayed) _queue(op); else _send(op.t, op.a, op.x); } else if (k == OP_CANCEL) { Pending storage p = pending[op.x]; if (p.done) revert Done(); p.done = true; emit Cancelled(op.x); } else if (k == OP_SET_POLICY) { bool loosen = (dailyCap != 0 && (op.x == 0 || op.x > dailyCap)) || (lockThreshold != 0 && (op.y == 0 || op.y > lockThreshold)) || (whitelistOn && !op.f); if (loosen) _queue(op); else _setPolicy(op.x, op.y, op.f); } else if (k == OP_ALLOW) { if (op.f) { if (whitelistOn) _queue(op); else { allowed[op.a] = true; emit Allowed(op.a, true); } } else { allowed[op.a] = false; emit Allowed(op.a, false); } } else if (k == OP_FREEZE) { if (op.f) { frozen = true; emit Frozen(true); } else _queue(op); } else if (k == OP_ADD_GUARDIAN) { if (guardians.length >= 3) revert TooMany(); _queue(op); } else if (k == OP_ROTATE) { root = bytes32(op.y); tree += 1; nextLeaf = 0; emit Rotated(tree, root); } else if (k == OP_CANCEL_RECOVERY) { _clearRecovery(); emit RecoveryCancelled(); } } function _queue(Op calldata op) internal { uint64 eta = uint64(block.timestamp + DELAY); pending.push(Pending(op.kind, op.a, op.t, op.x, op.y, op.f, eta, false)); emit Queued(pending.length - 1, op.kind, eta); } function _setPolicy(uint256 cap, uint256 thr, bool wl) internal { dailyCap = cap; lockThreshold = thr; whitelistOn = wl; emit PolicyChanged(cap, thr, wl); } function _addGuardian(address g) internal { if (guardians.length >= 3) revert TooMany(); if (g == address(0) || isGuardian(g)) return; guardians.push(g); emit GuardianAdded(g); } function _clearRecovery() internal { for (uint256 i; i < guardians.length; i++) delete recoveryVote[guardians[i]]; recoveryRoot = 0; recoveryPub = 0; recoveryEta = 0; } function _send(address token, address to, uint256 amount) internal { bool ok; if (token == address(0)) { (ok, ) = to.call{value: amount}(""); } else { bytes memory ret; (ok, ret) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount)); ok = ok && (ret.length == 0 || abi.decode(ret, (bool))); } if (!ok) revert SendFailed(); emit Sent(token, to, amount); } /// @dev WOTS+ (w=16, 64+3 digits) public key reconstruction, then Merkle path up to `root`. function _verify(bytes32 m, uint16 leaf, bytes32[67] calldata sig, bytes32[10] calldata auth) internal view returns (bool) { bytes32 pub = pubSeed; uint256 tr = tree; bytes memory pk = new bytes(LEN * 32); uint256 cs; for (uint256 c; c < LEN; c++) { uint256 d; if (c < 64) { uint256 b = uint8(m[c >> 1]); d = (c & 1) == 0 ? b >> 4 : b & 15; cs += 15 - d; } else if (c == 64) d = (cs >> 8) & 15; else if (c == 65) d = (cs >> 4) & 15; else d = cs & 15; bytes32 v = sig[c]; assembly { let p := mload(0x40) mstore(p, pub) mstore8(add(p, 32), tr) mstore8(add(p, 33), and(shr(16, leaf), 0xff)) mstore8(add(p, 34), and(shr(8, leaf), 0xff)) mstore8(add(p, 35), and(leaf, 0xff)) mstore8(add(p, 36), c) mstore8(add(p, 38), 0x51) mstore8(add(p, 39), 0) for { let s := d } lt(s, 15) { s := add(s, 1) } { mstore8(add(p, 37), s) mstore(add(p, 40), v) v := keccak256(p, 72) } mstore(add(add(pk, 32), mul(c, 32)), v) } } bytes32 node = keccak256(abi.encodePacked(pub, "leaf", pk)); uint256 idx = leaf; for (uint256 h; h < HEIGHT; h++) { node = (idx & 1) == 1 ? keccak256(abi.encodePacked(pub, uint8(h + 1), auth[h], node)) : keccak256(abi.encodePacked(pub, uint8(h + 1), node, auth[h])); idx >>= 1; } return node == root; } }