Skip to content
Verified contractExactMIT

MultiChainFragmentsHubProxy

Address0xf86a11e2fa4e71f6351091250cf1d02487783c19
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,485,887
Creation transaction
0x9405b9490b…4b895b9367
Proxy implementation
0xe5db1a5b…f199d058MultiChainFragmentsHub

contracts/MultiChainFragmentsHubFactory_flat.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

// contracts/src/hub/MultiChainFragmentsHubProxy.sol

/**
 * @title MultiChainFragmentsHubProxy
 * @notice Minimal ERC-1967 proxy for a per-user hub. It has no admin functions of its own:
 *         upgrades are implemented (and timelocked, owner-only) in the hub implementation
 *         (UUPS), so there is no proxy admin that could override the user.
 */
contract MultiChainFragmentsHubProxy {
    // keccak256("eip1967.proxy.implementation") - 1
    bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    event Upgraded(address indexed implementation);

    constructor(address implementation_, bytes memory initData) payable {
        require(implementation_.code.length > 0, "Invalid implementation");
        assembly {
            sstore(_IMPLEMENTATION_SLOT, implementation_)
        }
        emit Upgraded(implementation_);
        if (initData.length > 0) {
            (bool ok, bytes memory ret) = implementation_.delegatecall(initData);
            if (!ok) {
                assembly {
                    revert(add(ret, 32), mload(ret))
                }
            }
        }
    }

    fallback() external payable {
        assembly {
            let impl := sload(_IMPLEMENTATION_SLOT)
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    receive() external payable {}
}

// contracts/src/p256/P256.sol

/**
 * @title P256
 * @notice secp256r1 (P-256 / passkey) signature verification.
 *
 * Order of attempts:
 *  1. The P256VERIFY precompile at 0x100 (RIP-7212 on rollups such as Base, Optimism,
 *     Arbitrum, Polygon, zkSync; EIP-7951 on Ethereum L1 since Fusaka). ~3.5k-6.9k gas.
 *  2. A deployed fallback verifier with the same calling convention
 *     (input = hash || r || s || x || y, output = 32-byte 1 / 0), e.g. src/P256Verifier.vy.
 *
 * The precompile returns empty data for an invalid signature, and an address without
 * code returns empty data too, so "not valid at 0x100" always falls through to the
 * fallback. On a chain where 0x100 is occupied by an unrelated contract, that contract
 * would be trusted for a "1" answer: check each chain before deploying.
 *
 * Low-s policy: P-256 ECDSA signatures are malleable ((r, s) and (r, n - s) both verify).
 * Passkey authenticators do NOT normalise s, so requiring low-s rejects about half of
 * real WebAuthn signatures unless the client normalises s first (see normalizeS).
 * Only require it when signatures are used as unique identifiers / replay keys.
 */
library P256 {
    address internal constant PRECOMPILE = address(0x100);

    /// Curve order n.
    uint256 internal constant N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551;
    /// floor(n / 2).
    uint256 internal constant N_HALF = 0x7FFFFFFF800000007FFFFFFFFFFFFFFFDE737D56D38BCF4279DCE5617E3192A8;

    function verify(
        bytes32 messageHash,
        uint256 r,
        uint256 s,
        uint256 x,
        uint256 y,
        address fallbackVerifier,
        bool requireLowS
    ) internal view returns (bool) {
        if (r == 0 || r >= N || s == 0 || s >= N) return false;
        if (requireLowS && s > N_HALF) return false;

        bytes memory input = abi.encodePacked(messageHash, r, s, x, y);
        if (_callVerifier(PRECOMPILE, input)) return true;
        if (fallbackVerifier == address(0) || fallbackVerifier.code.length == 0) return false;
        return _callVerifier(fallbackVerifier, input);
    }

    /// Precompile only (no fallback); false when the chain has no precompile.
    function verifyWithPrecompile(bytes32 messageHash, uint256 r, uint256 s, uint256 x, uint256 y)
        internal
        view
        returns (bool)
    {
        if (r == 0 || r >= N || s == 0 || s >= N) return false;
        return _callVerifier(PRECOMPILE, abi.encodePacked(messageHash, r, s, x, y));
    }

    /// Returns the low-s form of a signature's s value.
    function normalizeS(uint256 s) internal pure returns (uint256) {
        return s > N_HALF ? N - s : s;
    }

    function isLowS(uint256 s) internal pure returns (bool) {
        return s <= N_HALF;
    }

    function _callVerifier(address target, bytes memory input) private view returns (bool) {
        (bool success, bytes memory ret) = target.staticcall(input);
        return success && ret.length == 32 && abi.decode(ret, (uint256)) == 1;
    }
}

// contracts/src/p256/WebAuthn.sol

/**
 * @title WebAuthn
 * @notice Minimal on-chain check of a WebAuthn (passkey) assertion.
 *
 * Checks performed:
 *  - authenticatorData is at least 37 bytes; optional rpIdHash match (first 32 bytes);
 *  - flags: User Present (UP) always required, User Verified (UV) optional by policy;
 *  - clientDataJSON contains `"type":"webauthn.get"` at typeIndex;
 *  - clientDataJSON contains `"challenge":"<base64url(challenge)>"` at challengeIndex;
 *  - optional: keccak256 of the clientDataJSON `origin` value equals Policy.originHash
 *    (first `"origin":"` key; browsers serialise it as an origin, which cannot contain `"`);
 *  - P-256 signature over sha256(authenticatorData || sha256(clientDataJSON)).
 *
 * NOT checked here: `crossOrigin`/`topOrigin`, attestation, backup flags. signCount
 * monotonicity needs state, so the caller does it (see signCount(); the hub enforces it in
 * its state-changing passkey calls).
 * Indices are supplied by the caller; the check is that the expected bytes are at that
 * exact position, so a wrong index simply fails.
 */
library WebAuthn {
    bytes1 internal constant FLAG_UP = 0x01;
    bytes1 internal constant FLAG_UV = 0x04;

    struct Assertion {
        bytes authenticatorData;
        string clientDataJSON;
        uint256 challengeIndex;
        uint256 typeIndex;
        uint256 r;
        uint256 s;
    }

    struct Policy {
        bytes32 rpIdHash; // 0 = do not check
        bytes32 originHash; // keccak256(bytes(origin)), 0 = do not check
        bool requireUserVerification;
        bool requireLowS;
        address fallbackVerifier; // used when the 0x100 precompile is unavailable
    }

    function verify(bytes memory challenge, Assertion memory a, uint256 x, uint256 y, Policy memory p)
        internal
        view
        returns (bool)
    {
        bytes memory authData = a.authenticatorData;
        if (authData.length < 37) return false;

        if (p.rpIdHash != bytes32(0)) {
            bytes32 rp;
            assembly {
                rp := mload(add(authData, 32))
            }
            if (rp != p.rpIdHash) return false;
        }

        bytes1 flags = authData[32];
        if (flags & FLAG_UP != FLAG_UP) return false;
        if (p.requireUserVerification && flags & FLAG_UV != FLAG_UV) return false;

        bytes memory cd = bytes(a.clientDataJSON);
        if (!_matchesAt(cd, a.typeIndex, bytes('"type":"webauthn.get"'))) return false;
        if (!_matchesAt(cd, a.challengeIndex, abi.encodePacked('"challenge":"', base64Url(challenge), '"'))) {
            return false;
        }
        if (p.originHash != bytes32(0) && originHash(cd) != p.originHash) return false;

        bytes32 messageHash = sha256(abi.encodePacked(authData, sha256(cd)));
        return P256.verify(messageHash, a.r, a.s, x, y, p.fallbackVerifier, p.requireLowS);
    }

    /// keccak256 of the value of the first `"origin":"..."` member, or 0 if there is none.
    function originHash(bytes memory cd) internal pure returns (bytes32 h) {
        bytes memory key = bytes('"origin":"');
        uint256 n = cd.length;
        if (n < key.length) return bytes32(0);
        for (uint256 i = 0; i + key.length <= n; ++i) {
            if (cd[i] != '"' || !_matchesAt(cd, i, key)) continue;
            uint256 start = i + key.length;
            uint256 end = start;
            while (end < n && cd[end] != '"') ++end;
            if (end == n) return bytes32(0);
            assembly {
                h := keccak256(add(add(cd, 32), start), sub(end, start))
            }
            return h;
        }
        return bytes32(0);
    }

    /// Big-endian signature counter at authenticatorData[33:37] (0 if too short).
    function signCount(bytes memory authData) internal pure returns (uint32 c) {
        if (authData.length < 37) return 0;
        c = uint32(uint8(authData[33])) << 24 | uint32(uint8(authData[34])) << 16 | uint32(uint8(authData[35])) << 8
            | uint32(uint8(authData[36]));
    }

    function _matchesAt(bytes memory haystack, uint256 index, bytes memory needle) private pure returns (bool) {
        if (index > haystack.length || haystack.length - index < needle.length) return false;
        for (uint256 i = 0; i < needle.length; ++i) {
            if (haystack[index + i] != needle[i]) return false;
        }
        return true;
    }

    /// RFC 4648 section 5 base64url, no padding (what browsers put in clientDataJSON).
    function base64Url(bytes memory data) internal pure returns (string memory) {
        bytes memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        uint256 len = data.length;
        if (len == 0) return "";
        uint256 outLen = (len * 4 + 2) / 3;
        bytes memory out = new bytes(outLen);
        uint256 j;
        for (uint256 i = 0; i < len; i += 3) {
            uint256 b0 = uint8(data[i]);
            uint256 b1 = i + 1 < len ? uint8(data[i + 1]) : 0;
            uint256 b2 = i + 2 < len ? uint8(data[i + 2]) : 0;
            uint256 triple = (b0 << 16) | (b1 << 8) | b2;
            out[j++] = table[(triple >> 18) & 63];
            out[j++] = table[(triple >> 12) & 63];
            if (j < outLen) out[j++] = table[(triple >> 6) & 63];
            if (j < outLen) out[j++] = table[triple & 63];
        }
        return string(out);
    }
}

// contracts/src/p256/WebAuthnVerifier.sol

/**
 * @title WebAuthnVerifier
 * @notice Deployed (linked) wrapper around the internal WebAuthn library, so the hub
 *         implementation stays under the 24,576-byte EIP-170 limit. Stateless and pure
 *         apart from the P-256 precompile / fallback staticcall; one deployment per chain
 *         can serve every hub implementation.
 */
library WebAuthnVerifier {
    function verify(
        bytes memory challenge,
        WebAuthn.Assertion memory a,
        uint256 x,
        uint256 y,
        WebAuthn.Policy memory p
    ) public view returns (bool) {
        return WebAuthn.verify(challenge, a, x, y, p);
    }
}

// EIP hybrid/MultiChainFragmentsHub.sol

/**
 * @title MultiChainFragmentsHub (per-user mini hub)
 * @notice One hub per user. The user is `owner`; only they can point the hub at modules,
 *         move its assets or change its passkey. There is no global/admin setter: a
 *         factory (contracts/src/hub/MultiChainFragmentsHubFactory.sol) only deploys a
 *         hub owned by the caller and cannot touch it afterwards.
 *
 * Upgrades: each hub is an ERC-1967 proxy (MultiChainFragmentsHubProxy) pointing at this
 * implementation (UUPS). Only the hub's owner can schedule, cancel or execute an upgrade,
 * and only after a delay (default 48h, owner-configurable within 24h..30d). All state lives
 * in one ERC-7201 namespaced struct, so new implementations can append fields safely.
 *
 * Passkeys: the owner may register a P-256 passkey (WebAuthn). It is used for
 *  - ERC-1271 signatures (e.g. approving ERC1180 swaps initiated by this hub), and
 *  - authorising "mirror unlock" requests, which off-chain share holders watch before
 *    releasing encrypted fragments (see off-chain/src/fragments).
 */

struct SponsoredCallRequest {
    address to;
    address from;
    bytes data;
    uint256 value;
    uint256 gas;
    uint256 nonce;
    bytes signature;
}

interface ISponsoredExecutorProxy {
    function sponsoredCall(SponsoredCallRequest calldata req) external returns (bool success, bytes memory results);
    function scheduleUpgrade(address newImplementation) external returns (bytes32 upgradeId);
    function executeScheduledUpgrade(bytes32 upgradeId) external;
    function cancelScheduledUpgrade(bytes32 upgradeId) external;
    function changeAdmin(address newAdmin) external;
    function getImplementation() external view returns (address);
    function getAdmin() external view returns (address);
}

interface IERC1155Module {
    function balanceOf(address account, uint256 id) external view returns (uint256);
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
    function setApprovalForAll(address operator, bool approved) external;
    function isApprovedForAll(address account, address operator) external view returns (bool);
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
    function sponsoredBatchTransfer(address from, address to, uint256[] calldata ids, uint256[] calldata amounts) external;
    function sponsoredTransfer(address from, address to, uint256 id, uint256 amount) external;
}

/// Matches EIP hybrid/ERC1180WithSponsoredProxy.sol exactly.
interface IERC1180Module {
    function initiateSwap(
        address[] calldata tokensOffered,
        uint256[] calldata amountsOffered,
        address[] calldata tokensRequested,
        uint256[] calldata amountsRequested,
        address recipient,
        uint256 deadline
    ) external returns (bytes32 swapId);

    function cancelSwap(bytes32 swapId) external;

    function getSwapDetails(bytes32 swapId)
        external
        view
        returns (
            address initiator,
            address recipient,
            address[] memory tokensOffered,
            uint256[] memory amountsOffered,
            address[] memory tokensRequested,
            uint256[] memory amountsRequested,
            bool executed,
            bool cancelled,
            uint256 deadline
        );

    function getUserSwaps(address user) external view returns (bytes32[] memory);
    function isSwapExpired(bytes32 swapId) external view returns (bool);
    function setSwapCoordinator(address newCoordinator) external;
    function setMaxSwapDuration(uint256 newDuration) external;
}

interface IEIP196Module {
    function sponsoredModExp(bytes calldata base, bytes calldata exponent, bytes calldata modulus)
        external
        returns (bytes memory result);
    function sponsoredECAdd(uint256 ax, uint256 ay, uint256 bx, uint256 by) external returns (uint256 rx, uint256 ry);
    function sponsoredECMul(uint256 x, uint256 y, uint256 scalar) external returns (uint256 rx, uint256 ry);
    function sponsoredECPairing(uint256[] calldata input) external returns (uint256 result);
    function getPrecompileAddress(string calldata precompileName) external pure returns (uint256);
}

/// SPECK module (integrity helper). Not used for encryption of anything holding value.
interface ISPECK256Module {
    function registerEncryptionKey(bytes32 encryptionKey) external;
    function verifyDataIntegrity(bytes calldata data, bytes32 expectedHash) external returns (bool);
    function getDataHash(bytes calldata data) external pure returns (bytes32);
}

interface IFragmentCommitments {
    function setPolicy(uint8 threshold, uint8 shares) external returns (uint32 version);
    function setDefaultPolicy() external returns (uint32 version);
    function setThreshold(uint8 threshold) external returns (uint32 version);
    function commitFragments(uint256[] calldata chainIds, uint8[] calldata indexes, bytes32[] calldata commitments)
        external;
    function setMirrorRoot(bytes32 mirrorRoot) external;
}

interface IERC20Approve {
    function approve(address spender, uint256 amount) external returns (bool);
}

contract MultiChainFragmentsHub {
    struct Modules {
        address proxy; // SponsoredExecutorProxy (this hub must be its admin for upgrade calls)
        address erc1155;
        address erc1180;
        address eip196;
        address speck256; // optional, integrity only
        address fragments; // FragmentCommitments on this chain
    }

    struct Passkey {
        uint256 x;
        uint256 y;
        bytes32 rpIdHash; // sha256(rpId), 0 = not enforced
        // User verification (UV flag: PIN/biometric on the authenticator) is REQUIRED by
        // default. Set true only to also accept user-presence-only assertions.
        bool allowWithoutUserVerification;
        bool requireLowS;
    }

    struct PendingUpgrade {
        address implementation;
        uint64 executeAfter;
    }

    /// Passkey replacement without the current passkey (lost device): owner-scheduled,
    /// executable after the hub's upgrade delay, cancellable by the owner or the current passkey.
    struct PendingPasskey {
        Passkey passkey;
        bytes32 originHash;
        uint64 executeAfter;
    }

    /// @custom:storage-location erc7201:multichainfragments.storage.Hub
    /// Append new fields at the END only; never reorder or remove (upgrade safety).
    struct HubStorage {
        bool initialized;
        address factory;
        address p256Fallback;
        address owner;
        address pendingOwner;
        Modules modules;
        Passkey passkey;
        uint256 mirrorUnlockNonce;
        uint64 upgradeDelay;
        PendingUpgrade pendingUpgrade;
        bytes32 speckKey; // registerSpeckKey (PUBLIC, see warning there)
        // --- appended (passkey sign-up / recovery) ---
        bytes32 passkeyOriginHash; // keccak256(bytes(origin)) checked on chain; 0 = not enforced
        uint32 passkeySignCount; // last WebAuthn signCount seen by a state-changing passkey call
        bool passkeyInitialized; // true after the first setPasskey; later changes: rotate or recovery
        PendingPasskey pendingPasskey;
        uint256 passkeyChangeNonce; // binds rotation / cancel challenges, bumps on every change
    }

    // keccak256(abi.encode(uint256(keccak256("multichainfragments.storage.Hub")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _HUB_STORAGE = 0x781a427ae3cc0a15a2c3230e821c36077297f22cfd089ee4bfde5c9634304e00;
    // ERC-1967 implementation slot: keccak256("eip1967.proxy.implementation") - 1
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    uint64 public constant DEFAULT_UPGRADE_DELAY = 48 hours;
    uint64 public constant MIN_UPGRADE_DELAY = 24 hours;
    uint64 public constant MAX_UPGRADE_DELAY = 30 days;

    bytes4 internal constant ERC1271_MAGIC = 0x1626ba7e;
    bytes32 private constant _SECP256K1_N_HALF = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0;

    /// Address of this implementation contract (used to forbid direct calls to upgrade functions).
    address private immutable _self = address(this);

    event Initialized(address indexed owner, address indexed factory);
    event ModulesConfigured(
        address indexed owner,
        address proxy,
        address erc1155,
        address erc1180,
        address eip196,
        address speck256,
        address fragments
    );
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event PasskeySet(uint256 x, uint256 y, bytes32 rpIdHash, bool allowWithoutUserVerification, bool requireLowS);
    event PasskeyCleared();
    event PasskeyOriginSet(bytes32 originHash);
    event PasskeyRotated(uint256 x, uint256 y);
    event PasskeyRecoveryScheduled(uint256 x, uint256 y, uint256 executeAfter);
    event PasskeyRecoveryCancelled(bool byPasskey);
    event PasskeyRecovered(uint256 x, uint256 y);
    event PasskeySignCount(uint32 signCount);
    event MirrorUnlockAuthorized(bytes32 indexed requestId, uint256 indexed nonce, bytes32 challenge);
    event UpgradeScheduled(address indexed implementation, uint256 executeAfter);
    event UpgradeCancelled(address indexed implementation);
    event Upgraded(address indexed implementation); // ERC-1967
    event UpgradeDelayUpdated(uint256 previousDelay, uint256 newDelay);
    event SpeckKeyRegistered(address indexed owner, bytes32 value, bool forwardedToModule);

    modifier onlyOwner() {
        require(msg.sender == _s().owner, "Not owner");
        _;
    }

    modifier onlyProxy() {
        require(address(this) != _self, "Only via proxy");
        _;
    }

    /// The implementation itself can never be initialised or used as a hub.
    constructor() {
        _s().initialized = true;
    }

    function _s() private pure returns (HubStorage storage $) {
        assembly {
            $.slot := _HUB_STORAGE
        }
    }

    /// Called once, atomically, by MultiChainFragmentsHubProxy's constructor.
    function initialize(address owner_, Modules calldata modules_, address p256Fallback_) external {
        HubStorage storage $ = _s();
        require(!$.initialized, "Already initialized");
        require(owner_ != address(0), "Invalid owner");
        $.initialized = true;
        $.factory = msg.sender;
        $.p256Fallback = p256Fallback_;
        $.owner = owner_;
        $.upgradeDelay = DEFAULT_UPGRADE_DELAY;
        emit Initialized(owner_, msg.sender);
        emit OwnershipTransferred(address(0), owner_);
        _setModules(modules_);
    }

    // ---------------------------------------------------------------------
    // Views
    // ---------------------------------------------------------------------

    function owner() external view returns (address) {
        return _s().owner;
    }

    function pendingOwner() external view returns (address) {
        return _s().pendingOwner;
    }

    /// Deployer of this hub (a factory or the user). Has no rights after initialisation.
    function factory() external view returns (address) {
        return _s().factory;
    }

    /// Fallback P-256 verifier used when the chain has no 0x100 precompile.
    function p256Fallback() external view returns (address) {
        return _s().p256Fallback;
    }

    function mirrorUnlockNonce() external view returns (uint256) {
        return _s().mirrorUnlockNonce;
    }

    function modules() external view returns (Modules memory) {
        return _s().modules;
    }

    function passkey() external view returns (Passkey memory) {
        return _s().passkey;
    }

    function passkeyOriginHash() external view returns (bytes32) {
        return _s().passkeyOriginHash;
    }

    function passkeySignCount() external view returns (uint32) {
        return _s().passkeySignCount;
    }

    function passkeyInitialized() external view returns (bool) {
        return _s().passkeyInitialized;
    }

    function pendingPasskeyRecovery() external view returns (PendingPasskey memory) {
        return _s().pendingPasskey;
    }

    function passkeyChangeNonce() external view returns (uint256) {
        return _s().passkeyChangeNonce;
    }

    // ---------------------------------------------------------------------
    // Timelocked UUPS upgrades (owner only)
    // ---------------------------------------------------------------------

    /// ERC-1822: lets a hub check that a new implementation is a compatible UUPS hub.
    function proxiableUUID() external view returns (bytes32) {
        require(address(this) == _self, "Must not be called through delegatecall");
        return IMPLEMENTATION_SLOT;
    }

    function implementation() external view returns (address impl) {
        assembly {
            impl := sload(IMPLEMENTATION_SLOT)
        }
    }

    function upgradeDelay() external view returns (uint64) {
        return _s().upgradeDelay;
    }

    function pendingUpgrade() external view returns (PendingUpgrade memory) {
        return _s().pendingUpgrade;
    }

    function scheduleUpgrade(address newImplementation) external onlyOwner onlyProxy {
        require(newImplementation.code.length > 0, "Invalid implementation");
        try MultiChainFragmentsHub(newImplementation).proxiableUUID() returns (bytes32 uuid) {
            require(uuid == IMPLEMENTATION_SLOT, "Unsupported UUID");
        } catch {
            revert("Not a UUPS hub");
        }
        HubStorage storage $ = _s();
        uint64 executeAfter = uint64(block.timestamp) + $.upgradeDelay;
        $.pendingUpgrade = PendingUpgrade(newImplementation, executeAfter);
        emit UpgradeScheduled(newImplementation, executeAfter);
    }

    function cancelUpgrade() external onlyOwner onlyProxy {
        PendingUpgrade memory p = _s().pendingUpgrade;
        require(p.implementation != address(0), "No pending upgrade");
        delete _s().pendingUpgrade;
        emit UpgradeCancelled(p.implementation);
    }

    function executeUpgrade() external onlyOwner onlyProxy {
        PendingUpgrade memory p = _s().pendingUpgrade;
        require(p.implementation != address(0), "No pending upgrade");
        require(block.timestamp >= p.executeAfter, "Upgrade timelock active");
        delete _s().pendingUpgrade;
        address impl = p.implementation;
        assembly {
            sstore(IMPLEMENTATION_SLOT, impl)
        }
        emit Upgraded(impl);
    }

    /// Changes apply to upgrades scheduled afterwards; an already scheduled upgrade keeps its time.
    function setUpgradeDelay(uint64 newDelay) external onlyOwner {
        require(newDelay >= MIN_UPGRADE_DELAY, "Delay too short");
        require(newDelay <= MAX_UPGRADE_DELAY, "Delay too long");
        emit UpgradeDelayUpdated(_s().upgradeDelay, newDelay);
        _s().upgradeDelay = newDelay;
    }

    // ---------------------------------------------------------------------
    // Ownership (two-step) and per-user module configuration
    // ---------------------------------------------------------------------

    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "Invalid owner");
        _s().pendingOwner = newOwner;
        emit OwnershipTransferStarted(_s().owner, newOwner);
    }

    function acceptOwnership() external {
        HubStorage storage $ = _s();
        require(msg.sender == $.pendingOwner, "Not pending owner");
        emit OwnershipTransferred($.owner, msg.sender);
        $.owner = msg.sender;
        $.pendingOwner = address(0);
        // A new owner must register their own passkey; any pending upgrade is dropped.
        // passkeyInitialized stays true, so the new owner's passkey goes through the
        // timelocked recovery path (no instant swap after a takeover of the owner key).
        if ($.passkey.x != 0 || $.passkey.y != 0) {
            _clearPasskey();
        }
        if ($.pendingPasskey.executeAfter != 0) {
            delete $.pendingPasskey;
            emit PasskeyRecoveryCancelled(false);
        }
        if ($.pendingUpgrade.implementation != address(0)) {
            emit UpgradeCancelled($.pendingUpgrade.implementation);
            delete $.pendingUpgrade;
        }
    }

    /// Per-user setter: only this hub's owner, only this hub's storage.
    function setModuleAddresses(Modules calldata modules_) external onlyOwner {
        _setModules(modules_);
    }

    function _setModules(Modules memory m) internal {
        _s().modules = m;
        emit ModulesConfigured(_s().owner, m.proxy, m.erc1155, m.erc1180, m.eip196, m.speck256, m.fragments);
    }

    function _mod(address a) private pure returns (address) {
        require(a != address(0), "Module not set");
        return a;
    }

    // ---------------------------------------------------------------------
    // Passkey (P-256 / WebAuthn)
    // ---------------------------------------------------------------------

    /**
     * @notice Sign-up: registers the FIRST passkey of this hub, immediately. `originHash` =
     *         keccak256(bytes(origin)), e.g. keccak256("https://pump-vault.vercel.app"); 0 skips
     *         the on-chain origin check. Afterwards the passkey can only be replaced with
     *         rotatePasskey (signed by the current passkey) or the timelocked recovery path.
     */
    function setPasskey(Passkey calldata pk, bytes32 originHash) external onlyOwner {
        require(!_s().passkeyInitialized, "Passkey already set: rotate or recover");
        _s().passkeyInitialized = true;
        _installPasskey(pk, originHash);
    }

    /// Owner + current passkey: immediate replacement (e.g. moving to a new device).
    function rotatePasskey(Passkey calldata pk, bytes32 originHash, WebAuthn.Assertion calldata a)
        external
        onlyOwner
    {
        bytes32 challenge = passkeyRotationChallenge(pk, originHash);
        _usePasskey(challenge, a);
        _installPasskey(pk, originHash);
        emit PasskeyRotated(pk.x, pk.y);
    }

    function passkeyRotationChallenge(Passkey calldata pk, bytes32 originHash) public view returns (bytes32) {
        return keccak256(
            abi.encode(
                "MultiChainFragments.RotatePasskey.v1",
                block.chainid,
                address(this),
                pk,
                originHash,
                _s().passkeyChangeNonce
            )
        );
    }

    /**
     * @notice Recovery when the passkey is lost: the owner schedules a new passkey; it can be
     *         installed after the hub's upgrade delay (48h by default, same timelock as
     *         upgrades). The current passkey (if any) or the owner can cancel meanwhile.
     */
    function schedulePasskeyRecovery(Passkey calldata pk, bytes32 originHash) external onlyOwner {
        require(pk.x != 0 || pk.y != 0, "Invalid passkey");
        HubStorage storage $ = _s();
        uint64 executeAfter = uint64(block.timestamp) + $.upgradeDelay;
        $.pendingPasskey = PendingPasskey(pk, originHash, executeAfter);
        $.passkeyChangeNonce++;
        emit PasskeyRecoveryScheduled(pk.x, pk.y, executeAfter);
    }

    function executePasskeyRecovery() external onlyOwner {
        HubStorage storage $ = _s();
        PendingPasskey memory p = $.pendingPasskey;
        require(p.executeAfter != 0, "No pending recovery");
        require(block.timestamp >= p.executeAfter, "Recovery timelock active");
        delete $.pendingPasskey;
        $.passkeyInitialized = true;
        _installPasskey(p.passkey, p.originHash);
        emit PasskeyRecovered(p.passkey.x, p.passkey.y);
    }

    function cancelPasskeyRecovery() external onlyOwner {
        require(_s().pendingPasskey.executeAfter != 0, "No pending recovery");
        delete _s().pendingPasskey;
        _s().passkeyChangeNonce++;
        emit PasskeyRecoveryCancelled(false);
    }

    /// Anyone may relay; the CURRENT passkey's signature is the authorisation.
    function cancelPasskeyRecoveryWithPasskey(WebAuthn.Assertion calldata a) external {
        require(_s().pendingPasskey.executeAfter != 0, "No pending recovery");
        _usePasskey(passkeyRecoveryCancelChallenge(), a);
        delete _s().pendingPasskey;
        _s().passkeyChangeNonce++;
        emit PasskeyRecoveryCancelled(true);
    }

    function passkeyRecoveryCancelChallenge() public view returns (bytes32) {
        return keccak256(
            abi.encode(
                "MultiChainFragments.CancelPasskeyRecovery.v1",
                block.chainid,
                address(this),
                _s().pendingPasskey.executeAfter,
                _s().passkeyChangeNonce
            )
        );
    }

    /// Removing the passkey only removes capability; a new one then needs the recovery path.
    function clearPasskey() external onlyOwner {
        _clearPasskey();
    }

    function _clearPasskey() private {
        HubStorage storage $ = _s();
        delete $.passkey;
        $.passkeyOriginHash = bytes32(0);
        $.passkeySignCount = 0;
        $.passkeyChangeNonce++;
        emit PasskeyCleared();
    }

    function _installPasskey(Passkey memory pk, bytes32 originHash) private {
        require(pk.x != 0 || pk.y != 0, "Invalid passkey");
        HubStorage storage $ = _s();
        $.passkey = pk;
        $.passkeyOriginHash = originHash;
        $.passkeySignCount = 0;
        $.passkeyChangeNonce++;
        emit PasskeySet(pk.x, pk.y, pk.rpIdHash, pk.allowWithoutUserVerification, pk.requireLowS);
        emit PasskeyOriginSet(originHash);
    }

    /// Verifies and consumes an assertion: signCount must grow unless the authenticator
    /// reports 0 both times (many synced passkeys do), which defeats replay of a captured
    /// assertion on calls whose challenge does not change.
    function _usePasskey(bytes32 challenge, WebAuthn.Assertion calldata a) private {
        require(verifyPasskey(abi.encodePacked(challenge), a), "Invalid passkey assertion");
        uint32 c = WebAuthn.signCount(a.authenticatorData);
        uint32 prev = _s().passkeySignCount;
        require(c > prev || (c == 0 && prev == 0), "Passkey signCount did not increase");
        _s().passkeySignCount = c;
        emit PasskeySignCount(c);
    }

    function verifyPasskey(bytes memory challenge, WebAuthn.Assertion memory a) public view returns (bool) {
        Passkey storage pk = _s().passkey;
        if (pk.x == 0 && pk.y == 0) return false;
        WebAuthn.Policy memory p = WebAuthn.Policy({
            rpIdHash: pk.rpIdHash,
            originHash: _s().passkeyOriginHash,
            requireUserVerification: !pk.allowWithoutUserVerification,
            requireLowS: pk.requireLowS,
            fallbackVerifier: _s().p256Fallback
        });
        return WebAuthnVerifier.verify(challenge, a, pk.x, pk.y, p);
    }

    /**
     * @notice ERC-1271. `signature` is either a 65-byte secp256k1 signature by `owner`,
     *         or abi.encode(WebAuthn.Assertion) signed by the registered passkey with
     *         challenge = hash (32 bytes).
     */
    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4) {
        if (signature.length == 65) {
            return _recover(hash, signature) == _s().owner ? ERC1271_MAGIC : bytes4(0xffffffff);
        }
        WebAuthn.Assertion memory a = abi.decode(signature, (WebAuthn.Assertion));
        return verifyPasskey(abi.encodePacked(hash), a) ? ERC1271_MAGIC : bytes4(0xffffffff);
    }

    function _recover(bytes32 digest, bytes calldata sig) private pure returns (address) {
        bytes32 r = bytes32(sig[0:32]);
        bytes32 s = bytes32(sig[32:64]);
        uint8 v = uint8(sig[64]);
        if (v < 27) v += 27;
        if (uint256(s) > uint256(_SECP256K1_N_HALF) || (v != 27 && v != 28)) return address(0);
        return ecrecover(digest, v, r, s);
    }

    // ---------------------------------------------------------------------
    // Mirror unlock (gated by passkey)
    // ---------------------------------------------------------------------

    /// Challenge the passkey must sign for the next mirror unlock of `requestId`.
    function mirrorUnlockChallenge(bytes32 requestId) public view returns (bytes32) {
        return keccak256(
            abi.encode("MultiChainFragments.MirrorUnlock.v1", block.chainid, address(this), requestId, _s().mirrorUnlockNonce)
        );
    }

    /**
     * @notice Anyone may relay this; the passkey signature is the authorisation. Emits an
     *         event that share holders / the mirror service wait for before releasing
     *         encrypted shares. Nothing secret is revealed on chain.
     */
    function authorizeMirrorUnlock(bytes32 requestId, WebAuthn.Assertion calldata a) external returns (uint256 nonce) {
        bytes32 challenge = mirrorUnlockChallenge(requestId);
        _usePasskey(challenge, a);
        nonce = _s().mirrorUnlockNonce++;
        emit MirrorUnlockAuthorized(requestId, nonce, challenge);
    }

    // ---------------------------------------------------------------------
    // Encrypted fragment commitments (hub acts as the user in the registry)
    // ---------------------------------------------------------------------

    function setFragmentPolicy(uint8 threshold, uint8 shares) external onlyOwner returns (uint32) {
        return IFragmentCommitments(_mod(_s().modules.fragments)).setPolicy(threshold, shares);
    }

    /// 30-of-59 across all registry chains (CMC top 58 + Bitcoin).
    function setDefaultFragmentPolicy() external onlyOwner returns (uint32) {
        return IFragmentCommitments(_mod(_s().modules.fragments)).setDefaultPolicy();
    }

    function setFragmentThreshold(uint8 threshold) external onlyOwner returns (uint32) {
        return IFragmentCommitments(_mod(_s().modules.fragments)).setThreshold(threshold);
    }

    function commitFragments(uint256[] calldata chainIds, uint8[] calldata indexes, bytes32[] calldata commitments)
        external
        onlyOwner
    {
        IFragmentCommitments(_mod(_s().modules.fragments)).commitFragments(chainIds, indexes, commitments);
    }

    function setMirrorRoot(bytes32 mirrorRoot) external onlyOwner {
        IFragmentCommitments(_mod(_s().modules.fragments)).setMirrorRoot(mirrorRoot);
    }

    // ---------------------------------------------------------------------
    // Sponsored executor proxy (hub must be the proxy admin)
    // ---------------------------------------------------------------------

    function proxySponsoredCall(SponsoredCallRequest calldata req)
        external
        onlyOwner
        returns (bool success, bytes memory results)
    {
        return ISponsoredExecutorProxy(_mod(_s().modules.proxy)).sponsoredCall(req);
    }

    function scheduleProxyUpgrade(address newImplementation) external onlyOwner returns (bytes32) {
        return ISponsoredExecutorProxy(_mod(_s().modules.proxy)).scheduleUpgrade(newImplementation);
    }

    function executeProxyUpgrade(bytes32 upgradeId) external onlyOwner {
        ISponsoredExecutorProxy(_mod(_s().modules.proxy)).executeScheduledUpgrade(upgradeId);
    }

    function cancelProxyUpgrade(bytes32 upgradeId) external onlyOwner {
        ISponsoredExecutorProxy(_mod(_s().modules.proxy)).cancelScheduledUpgrade(upgradeId);
    }

    function changeProxyAdmin(address newAdmin) external onlyOwner {
        ISponsoredExecutorProxy(_mod(_s().modules.proxy)).changeAdmin(newAdmin);
    }

    function getProxyImplementation() external view returns (address) {
        return ISponsoredExecutorProxy(_mod(_s().modules.proxy)).getImplementation();
    }

    function getProxyAdmin() external view returns (address) {
        return ISponsoredExecutorProxy(_mod(_s().modules.proxy)).getAdmin();
    }

    // ---------------------------------------------------------------------
    // ERC-1155 (the hub holds the user's tokens)
    // ---------------------------------------------------------------------

    function erc1155BalanceOf(address account, uint256 id) external view returns (uint256) {
        return IERC1155Module(_mod(_s().modules.erc1155)).balanceOf(account, id);
    }

    function erc1155BalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory)
    {
        return IERC1155Module(_mod(_s().modules.erc1155)).balanceOfBatch(accounts, ids);
    }

    function setErc1155ApprovalForAll(address operator, bool approved) external onlyOwner {
        IERC1155Module(_mod(_s().modules.erc1155)).setApprovalForAll(operator, approved);
    }

    function isErc1155Approved(address account, address operator) external view returns (bool) {
        return IERC1155Module(_mod(_s().modules.erc1155)).isApprovedForAll(account, operator);
    }

    function transferErc1155(address to, uint256 id, uint256 amount, bytes calldata data) external onlyOwner {
        IERC1155Module(_mod(_s().modules.erc1155)).safeTransferFrom(address(this), to, id, amount, data);
    }

    function batchTransferErc1155(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data)
        external
        onlyOwner
    {
        IERC1155Module(_mod(_s().modules.erc1155)).safeBatchTransferFrom(address(this), to, ids, amounts, data);
    }

    // ---------------------------------------------------------------------
    // ERC-1180 swaps. Execution is done by an authorised executor calling
    // executeSponsoredSwap on the module with this hub's ERC-1271 signature.
    // ---------------------------------------------------------------------

    function approveErc20(address token, address spender, uint256 amount) external onlyOwner {
        require(IERC20Approve(token).approve(spender, amount), "Approve failed");
    }

    function initiateErc1180Swap(
        address[] calldata tokensOffered,
        uint256[] calldata amountsOffered,
        address[] calldata tokensRequested,
        uint256[] calldata amountsRequested,
        address recipient,
        uint256 deadline
    ) external onlyOwner returns (bytes32 swapId) {
        return IERC1180Module(_mod(_s().modules.erc1180)).initiateSwap(
            tokensOffered, amountsOffered, tokensRequested, amountsRequested, recipient, deadline
        );
    }

    function cancelErc1180Swap(bytes32 swapId) external onlyOwner {
        IERC1180Module(_mod(_s().modules.erc1180)).cancelSwap(swapId);
    }

    function getErc1180SwapDetails(bytes32 swapId)
        external
        view
        returns (
            address initiator,
            address recipient,
            address[] memory tokensOffered,
            uint256[] memory amountsOffered,
            address[] memory tokensRequested,
            uint256[] memory amountsRequested,
            bool executed,
            bool cancelled,
            uint256 deadline
        )
    {
        return IERC1180Module(_mod(_s().modules.erc1180)).getSwapDetails(swapId);
    }

    function getErc1180UserSwaps(address user) external view returns (bytes32[] memory) {
        return IERC1180Module(_mod(_s().modules.erc1180)).getUserSwaps(user);
    }

    function isErc1180SwapExpired(bytes32 swapId) external view returns (bool) {
        return IERC1180Module(_mod(_s().modules.erc1180)).isSwapExpired(swapId);
    }

    /// Only works if this hub is the module's swap coordinator.
    function setErc1180MaxSwapDuration(uint256 newDuration) external onlyOwner {
        IERC1180Module(_mod(_s().modules.erc1180)).setMaxSwapDuration(newDuration);
    }

    /// Only works if this hub is the module's swap coordinator.
    function setErc1180SwapCoordinator(address newCoordinator) external onlyOwner {
        IERC1180Module(_mod(_s().modules.erc1180)).setSwapCoordinator(newCoordinator);
    }

    // ---------------------------------------------------------------------
    // EIP-196 precompile helpers and SPECK integrity helper
    // ---------------------------------------------------------------------

    function runEip196ModExp(bytes calldata base, bytes calldata exponent, bytes calldata modulus)
        external
        onlyOwner
        returns (bytes memory)
    {
        return IEIP196Module(_mod(_s().modules.eip196)).sponsoredModExp(base, exponent, modulus);
    }

    function runEip196EcAdd(uint256 ax, uint256 ay, uint256 bx, uint256 by)
        external
        onlyOwner
        returns (uint256, uint256)
    {
        return IEIP196Module(_mod(_s().modules.eip196)).sponsoredECAdd(ax, ay, bx, by);
    }

    function runEip196EcMul(uint256 x, uint256 y, uint256 scalar) external onlyOwner returns (uint256, uint256) {
        return IEIP196Module(_mod(_s().modules.eip196)).sponsoredECMul(x, y, scalar);
    }

    function runEip196Pairing(uint256[] calldata input) external onlyOwner returns (uint256) {
        return IEIP196Module(_mod(_s().modules.eip196)).sponsoredECPairing(input);
    }

    function getPrecompileAddress(string calldata precompileName) external view returns (uint256) {
        return IEIP196Module(_mod(_s().modules.eip196)).getPrecompileAddress(precompileName);
    }

    /**
     * @notice Stores `encryptionKey` for this hub's user and, if a SPECK module is
     *         configured, forwards it to the module's registerEncryptionKey (original behaviour).
     * @dev WARNING: everything stored on chain is PUBLICLY READABLE (storage slots, calldata,
     *      events), by anyone, forever, on every chain this is called on. Do not register a
     *      real secret or private key here. Use it for a public identifier/tag only; keep real
     *      keys in the encrypted fragments (FragmentCommitments + off-chain/src/fragments).
     */
    function registerSpeckKey(bytes32 encryptionKey) external onlyOwner {
        HubStorage storage $ = _s();
        $.speckKey = encryptionKey;
        bool forwarded = $.modules.speck256 != address(0);
        if (forwarded) ISPECK256Module($.modules.speck256).registerEncryptionKey(encryptionKey);
        emit SpeckKeyRegistered($.owner, encryptionKey, forwarded);
    }

    /// @notice Value last stored by registerSpeckKey. Public data (see warning above).
    function speckKey() external view returns (bytes32) {
        return _s().speckKey;
    }

    function verifySpeckIntegrity(bytes calldata data, bytes32 expectedHash) external onlyOwner returns (bool) {
        return ISPECK256Module(_mod(_s().modules.speck256)).verifyDataIntegrity(data, expectedHash);
    }

    function getSpeckHash(bytes calldata data) external view returns (bytes32) {
        return ISPECK256Module(_mod(_s().modules.speck256)).getDataHash(data);
    }

    // Branch list kept from the original hub, now pure (no storage writes).
    function getBranches() external pure returns (string[] memory b) {
        b = new string[](5);
        (b[0], b[1], b[2], b[3], b[4]) = ("404-solved", "auto118", "main", "multichain-libraries", "speck-256");
    }

    function getBranchCount() external pure returns (uint256) {
        return 5;
    }
}

// contracts/src/hub/MultiChainFragmentsHubFactory.sol

/**
 * @title MultiChainFragmentsHubFactory
 * @notice Deploys one upgradeable hub (ERC-1967 proxy -> MultiChainFragmentsHub) per user,
 *         owned and initialised for msg.sender in the same transaction. The factory has no
 *         owner, no admin and no setter: it cannot change, pause or upgrade any hub; only
 *         each hub's owner can upgrade it, after the hub's timelock.
 *         CREATE2 salt = user address, so the hub address is predictable.
 */
contract MultiChainFragmentsHubFactory {
    address public immutable hubImplementation;
    address public immutable p256Fallback;
    mapping(address => address) public hubOf;

    event HubCreated(address indexed user, address indexed hub, address implementation);

    constructor(address hubImplementation_, address p256Fallback_) {
        require(hubImplementation_.code.length > 0, "Invalid implementation");
        hubImplementation = hubImplementation_;
        p256Fallback = p256Fallback_;
    }

    function createHub(MultiChainFragmentsHub.Modules calldata modules_) external returns (address hub) {
        require(hubOf[msg.sender] == address(0), "Hub exists");
        hub = address(
            new MultiChainFragmentsHubProxy{salt: _salt(msg.sender)}(hubImplementation, _initData(msg.sender, modules_))
        );
        hubOf[msg.sender] = hub;
        emit HubCreated(msg.sender, hub, hubImplementation);
    }

    function predictHub(address user, MultiChainFragmentsHub.Modules calldata modules_) external view returns (address) {
        bytes32 initHash = keccak256(
            abi.encodePacked(
                type(MultiChainFragmentsHubProxy).creationCode, abi.encode(hubImplementation, _initData(user, modules_))
            )
        );
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), _salt(user), initHash)))));
    }

    function _salt(address user) private pure returns (bytes32) {
        return bytes32(uint256(uint160(user)));
    }

    function _initData(address user, MultiChainFragmentsHub.Modules calldata modules_) private view returns (bytes memory) {
        return abi.encodeCall(MultiChainFragmentsHub.initialize, (user, modules_, p256Fallback));
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.