Skip to content
Verified contractExactMIT

AlcorWithdrawals

Address0xb0a50dd6d0be3bfc089e0f92fa4605bb495584cd
Balance

0 ETH

 

Transactions

170

 

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
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,235,118
Creation transaction
0x7baa260899…88dfff2d13

src/AlcorWithdrawals.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;

import {TelosLightClient} from "./TelosLightClient.sol";

/**
 * Release locked assets against a proof they were burned on Telos.
 *
 * The expensive BLS check already happened once in `TelosLightClient.submitRoot`,
 * so a withdrawal here only folds two merkle branches and hashes a few dozen
 * bytes. That split is the whole economy of it: one 785k proof serves every
 * withdrawal that arrives under the same root.
 *
 * The chain of custody a withdrawal establishes:
 *
 *   wdlog fields -> act_digest -> action receipt digest -> action_mroot
 *   action_mroot -> finality leaf -> finalityMroot (already trusted)
 *
 * Nothing in the payload is taken on trust. The digest is rebuilt from the
 * fields, so inflating an amount or redirecting a recipient breaks the fold.
 *
 * ## Three guards that are not in the original
 *
 * **Domain.** The payload carries the destination chain id and this contract
 * requires its own. Withdrawal ids are global on the settlement chain, so
 * without it withdrawal 42 bound for one rollup would be presentable to another
 * chain's vault, where the same token address may be something else entirely.
 *
 * **Vault.** The payload names the vault that pays it, and the digest is rebuilt
 * with this contract's `vault`, so it is not a field anyone supplies. Replay
 * protection is a bitmap inside one vault; a second vault on the same chain — a
 * successor, or a predecessor not yet emptied — starts with its own, and without
 * this every proof ever made would be payable there again. Named in the payload,
 * a withdrawal belongs to one vault from the moment it is burned, and a new
 * vault needs no floor, no cut-over, and no knowledge of the old one. The domain
 * stays too: the same deployer can land the same vault address on two chains.
 *
 * **Deadline.** A withdrawal can only be released before its deadline. After it,
 * the settlement chain is entitled to refund the burned tokens, and both sides
 * cannot be allowed to happen. The bound is `<=` here and strictly `>` on the
 * expiry path, so no timestamp is legal for both.
 *
 * ## Who pays for the delivery
 *
 * The recipient may have nothing on this chain to pay gas with — that is the
 * usual case for someone arriving from Telos. So the payload carries a `fee`,
 * chosen by the owner when they burned and signed into the same digest as the
 * amount: whoever delivers the proof is paid that much out of the withdrawal,
 * and the recipient gets the rest. Zero means the recipient delivers it
 * themselves, which is what it was before.
 *
 * `submitAndRelease` exists for the same courier. Paid only on `release`, a
 * courier who first sent `submitRoot` on its own would be racing anyone who
 * watched the root land and sent `release` ahead of them; one transaction
 * leaves nothing to race. `submitAndExpire` is its twin for the expiry path,
 * where nobody is paid and the root for the burn block may never have been
 * submitted at all.
 *
 * ## Where replay protection lives
 *
 * In the vault, not here. This contract is the part expected to change; if it
 * owned the `released` map, deploying a fix would silently reset replay
 * protection to empty while the trusted roots stayed in the light client, making
 * every historical proof replayable.
 */
interface IAlcorVault {
    function release(uint64 id, address token, address to, uint64 amount, address feeTo, uint64 fee)
        external;
    function voidWithdrawal(uint64 id) external;
}

contract AlcorWithdrawals {
    TelosLightClient public immutable lightClient;
    IAlcorVault public immutable vault;

    /// Antelope names packed as uint64, fixed at deployment.
    uint64 public immutable bridgeAccount; // "ethbridge111"
    uint64 public immutable logAction; // "wdlog"
    uint64 public immutable activePerm; // "active"

    /// This chain's id, which the payload must name.
    uint64 public immutable domain;

    /// @param amount canonical units paid to `to`, the fee taken out; the
    ///               vault's own `Released` carries the raw figures
    /// @param memo   what the owner on Telos attached for the recipient, proved
    ///               with the amount; empty for a plain withdrawal
    event Released(uint64 indexed id, address indexed token, address indexed to, uint64 amount, bytes memo);
    event Expired(uint64 indexed id);

    error WrongDomain();
    error PastDeadline();
    error BeforeDeadline();
    error UntrustedRoot();
    error ActionNotInBlock();
    error BlockNotInRoot();
    error AmountOverflow();
    error BranchTooLong();
    error FeeExceedsAmount();

    struct Proof {
        // --- the wdlog payload, which is what gets paid out ---
        uint64 id;
        uint64 domain;
        address token;
        address recipient;
        /// Canonical units burned, as the settlement chain counts them — the
        /// fee included.
        uint64 amount;
        uint64 deadline;
        /// Canonical units of `amount` that go to whoever delivers the proof.
        uint64 fee;
        /// Up to a kilobyte the owner attached on Telos, for the recipient.
        bytes memo;
        // --- receipt parts not derivable from the payload ---
        uint64 recvSequence;
        bytes32 witness; // folded sequence numbers
        // --- branch to the block's action_mroot ---
        bytes32[] actionSiblings;
        /// Bit i set: the node is on the LEFT at step i. A mask rather than a
        /// bool[], which the ABI pads to a whole word per step.
        uint256 actionPath;
        bytes32 actionMroot;
        // --- the finality leaf this block contributes ---
        uint32 majorVersion;
        uint32 minorVersion;
        uint32 blockNum;
        uint32 timestamp;
        uint32 parentTimestamp;
        bytes32 finalityDigest;
        // --- branch to a root the light client already trusts ---
        bytes32[] treeSiblings;
        uint256 treePath;
        bytes32 finalityMroot;
    }

    constructor(
        TelosLightClient _lightClient,
        IAlcorVault _vault,
        uint64 _bridge,
        uint64 _log,
        uint64 _active
    ) {
        lightClient = _lightClient;
        vault = _vault;
        bridgeAccount = _bridge;
        logAction = _log;
        activePerm = _active;
        domain = uint64(block.chainid);
    }

    /**
     * Settle one withdrawal.
     *
     * Anyone may submit. The submitter is a courier and is not trusted: every
     * field they supply is either rebuilt into a digest that must fold to a
     * signed root, or checked against this contract's own immutables.
     */
    function release(Proof calldata p) external {
        _release(p);
    }

    /**
     * Trust the root a withdrawal needs and settle it, in one transaction.
     *
     * The root is submitted only if it is not trusted already, so a courier
     * who lost the race to another withdrawal under the same root pays for the
     * cheap half alone.
     */
    function submitAndRelease(
        TelosLightClient.FinalityInputs calldata f,
        bytes calldata bits,
        bytes calldata signature,
        bytes32[] calldata policyKeys,
        TelosLightClient.PendingQc calldata pending,
        Proof calldata p
    ) external {
        if (!lightClient.trustedRoots(p.finalityMroot)) {
            lightClient.submitRoot(f, bits, signature, policyKeys, pending);
        }
        _release(p);
    }

    /**
     * Retire a withdrawal nobody claimed, so the settlement chain can reissue it.
     *
     * A withdrawal burns tokens on Telos before anything happens here. If it is
     * never released, those tokens are gone and the collateral behind them is
     * locked forever — so there has to be a way to declare one abandoned. The
     * only honest way is a rule decided in advance by the contract that burned
     * them, which is why `deadline` is in the signed payload and not in a memo.
     *
     * Permissionless, and it pays out nothing: it marks the id settled and emits
     * a log. Telos proves that log with the same receipt machinery it already
     * runs for deposits, and reissues the burned amount to its owner.
     *
     * Marking it settled in the vault is what closes the race. `release` and this
     * compete for one flag on one chain, so a withdrawal cannot be both paid out
     * here and reissued there.
     *
     * Proving *non*-release instead — a storage proof that `released[id]` is
     * false — was the alternative, and it would need two secure tries, inlined
     * node handling, three separate absence cases, and a storage layout that
     * shifts whenever a state variable moves. A log costs one event.
     */
    function expire(Proof calldata p) external {
        _expire(p);
    }

    /// Trust the root an expiry needs and retire the withdrawal, in one transaction.
    function submitAndExpire(
        TelosLightClient.FinalityInputs calldata f,
        bytes calldata bits,
        bytes calldata signature,
        bytes32[] calldata policyKeys,
        TelosLightClient.PendingQc calldata pending,
        Proof calldata p
    ) external {
        if (!lightClient.trustedRoots(p.finalityMroot)) {
            lightClient.submitRoot(f, bits, signature, policyKeys, pending);
        }
        _expire(p);
    }

    function _expire(Proof calldata p) internal {
        if (block.timestamp <= p.deadline) revert BeforeDeadline();
        _verify(p);

        vault.voidWithdrawal(p.id);
        emit Expired(p.id);
    }

    /**
     * Everything both paths need: that the payload is for this chain, and that it
     * really was burned on the settlement chain.
     *
     * Nothing in the payload is taken on trust. The action digest is rebuilt from
     * the fields, so inflating an amount or redirecting a recipient breaks the
     * fold before any of it is used.
     */
    function _release(Proof calldata p) internal {
        // `<=` here and strictly `>` in `expire`, so no timestamp is legal for
        // both. That, plus the two paths competing for the same `released` flag
        // in the vault, is what makes paying out and refunding mutually
        // exclusive — by construction rather than by check ordering.
        if (block.timestamp > p.deadline) revert PastDeadline();
        // Strictly less, as the settlement chain requires: a fee equal to the
        // amount would pay the recipient nothing.
        if (p.fee >= p.amount) revert FeeExceedsAmount();
        _verify(p);

        // Canonical units, as the settlement chain counts them; the vault turns
        // them into the token's with its own scale, the one source of truth for
        // it. It also records the id, so replay protection survives replacing
        // this contract.
        uint64 paid = p.amount - p.fee;
        vault.release(p.id, p.token, p.recipient, paid, msg.sender, p.fee);
        emit Released(p.id, p.token, p.recipient, paid, p.memo);
    }

    function _verify(Proof calldata p) internal view {
        if (p.domain != domain) revert WrongDomain();
        if (!lightClient.trustedRoots(p.finalityMroot)) revert UntrustedRoot();

        // 1. The action digest is derived from the payload, not supplied. That is
        //    what binds the amount and the recipient to a signed root.
        if (_fold(_actionDigest(p), p.actionSiblings, p.actionPath) != p.actionMroot) {
            revert ActionNotInBlock();
        }

        // 2. The block's finality leaf commits to that action_mroot, and folds to
        //    the root. Field order is finality_leaf_node_t's, and the two
        //    timestamps are half-second slots rather than unix seconds.
        bytes32 leaf = sha256(
            abi.encodePacked(
                _le32(p.majorVersion),
                _le32(p.minorVersion),
                _le32(p.blockNum),
                _le32(p.timestamp),
                _le32(p.parentTimestamp),
                p.finalityDigest,
                p.actionMroot
            )
        );
        if (_fold(leaf, p.treeSiblings, p.treePath) != p.finalityMroot) revert BlockNotInRoot();
    }

    /**
     * The Savanna action receipt digest.
     *
     * `act_digest` is a two-level hash, not a flat one:
     *
     *   sha256( sha256(pack(action_base)) || sha256(pack(data) || pack(return_value)) )
     *
     * The return value is empty for `wdlog`, so it packs as a single zero length.
     * The payload order is the action's own argument order — id, domain, vault,
     * token, recipient, amount, deadline, fee, memo — and each `bytes` field
     * carries its LEB128 length: the single byte 0x14 for a 20-byte address, and
     * whatever the memo's length encodes to for the memo.
     */
    function _actionDigest(Proof calldata p) internal view returns (bytes32) {
        bytes memory data = abi.encodePacked(
            _le64(p.id),
            _le64(p.domain),
            bytes1(0x14),
            bytes20(address(vault)),
            bytes1(0x14),
            bytes20(p.token),
            bytes1(0x14),
            bytes20(p.recipient),
            _le64(p.amount),
            _le64(p.deadline),
            _le64(p.fee),
            _varuint32(p.memo.length),
            p.memo
        );
        bytes32 baseHash = sha256(
            abi.encodePacked(
                _le64(bridgeAccount),
                _le64(logAction),
                bytes1(0x01), // one authorization
                _le64(bridgeAccount),
                _le64(activePerm)
            )
        );
        bytes32 dataHash = sha256(abi.encodePacked(_varuint32(data.length), data, bytes1(0x00)));
        bytes32 actDigest = sha256(abi.encodePacked(baseHash, dataHash));
        return sha256(
            abi.encodePacked(
                _le64(bridgeAccount), // receiver
                _le64(p.recvSequence),
                _le64(bridgeAccount), // act.account
                _le64(logAction), // act.name
                actDigest,
                p.witness
            )
        );
    }

    /// Fold `node` up a branch: bit i of `path` set means `node` is the left child at step i.
    function _fold(bytes32 node, bytes32[] calldata siblings, uint256 path)
        internal
        pure
        returns (bytes32)
    {
        if (siblings.length > 256) revert BranchTooLong();
        for (uint256 i = 0; i < siblings.length; i++) {
            node = (path >> i) & 1 == 1
                ? sha256(abi.encodePacked(node, siblings[i]))
                : sha256(abi.encodePacked(siblings[i], node));
        }
        return node;
    }

    /** LEB128, which is how `fc::raw::pack` writes a length. */
    function _varuint32(uint256 v) internal pure returns (bytes memory out) {
        while (true) {
            // Masked to seven bits.
            // forge-lint: disable-next-line(unsafe-typecast)
            uint8 b = uint8(v & 0x7f);
            v >>= 7;
            if (v != 0) b |= 0x80;
            out = abi.encodePacked(out, bytes1(b));
            if (v == 0) break;
        }
    }

    function _le32(uint32 v) internal pure returns (bytes4) {
        return bytes4(
            uint32(
                ((v & 0xff) << 24) | (((v >> 8) & 0xff) << 16) | (((v >> 16) & 0xff) << 8)
                    | ((v >> 24) & 0xff)
            )
        );
    }

    /// Byte-reverse in three swaps — bytes, pairs, halves — rather than a loop of eight.
    function _le64(uint64 v) internal pure returns (bytes8) {
        v = ((v & 0xFF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF) << 8);
        v = ((v & 0xFFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF) << 16);
        v = (v >> 32) | (v << 32);
        return bytes8(v);
    }
}

src/BLS.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;

/// @title BLS12-381 helpers over the EIP-2537 precompiles (Pectra).
/// @notice Minimal pieces needed to verify a Savanna finalizer aggregate
///         signature on Ethereum: G1 aggregation, hash-to-G2 (RFC 9380), and the
///         pairing check. Points are EIP-2537 encoded (field element = 16 zero
///         bytes + 48-byte big-endian; G1 = 128 bytes, G2 = 256 bytes).
library BLS {
    // EIP-2537 precompile addresses (Pectra)
    address constant G1ADD = address(0x0b);
    address constant G1MSM = address(0x0c);
    address constant G2ADD = address(0x0d);
    address constant MAP_FP2_TO_G2 = address(0x11);
    address constant PAIRING = address(0x0f);
    address constant MODEXP = address(0x05);

    // BLS12-381 base field modulus p (48 bytes)
    bytes constant P =
        hex"1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab";

    /**
     * Savanna finalizer DST (basic/NUL ciphersuite) — what finalizers sign under.
     *
     * The basic scheme is only safe when signers sign distinct messages, or when
     * their keys are registered with a proof of possession. A quorum certificate
     * has every finalizer sign the SAME digest, so all of its safety rests on
     * registration — which is why a key accepted without a proof of possession
     * reopens the rogue-key attack even though the signature maths is unchanged.
     */
    bytes constant DST = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_";

    /// Proof-of-possession DST, as `eosio::bls_pop_verify` uses it.
    bytes constant POP_DST = "BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";

    /**
     * Call an EIP-2537 precompile, insisting on the output length it promises.
     *
     * The failure message names gas first because that is overwhelmingly what it
     * is. A `staticcall` that runs out of gas returns `ok = false` exactly like a
     * rejected input does, so "the precompile failed" reads as "this chain
     * cannot do BLS" when it almost always means "the caller could not pay for
     * it" — an `eth_estimateGas` from an account too poor to cover the call
     * produces precisely this revert. That misreading cost an hour and a wrong
     * conclusion about a chain that was fine.
     *
     * A genuinely bad input is possible and would look the same, so the message
     * says both, in the order of likelihood.
     */
    function _call(address to, bytes memory input, uint256 outLen) private view returns (bytes memory out) {
        (bool ok, bytes memory ret) = to.staticcall(input);
        require(ok && ret.length == outLen, "bls precompile: out of gas, or malformed input");
        return ret;
    }

    /// @dev Aggregate G1 public keys via a single G1MSM call with all scalars = 1.
    /// @param msmInput concatenation of (point[128] || scalar[32]) for each key.
    function aggregateG1(bytes memory msmInput) internal view returns (bytes memory) {
        return _call(G1MSM, msmInput, 128);
    }

    /// @dev RFC 9380 expand_message_xmd with SHA-256, 256-byte output (ell = 8).
    function expandMessageXmd(bytes memory message) internal pure returns (bytes memory) {
        return expandMessageXmd(message, DST);
    }

    function expandMessageXmd(bytes memory message, bytes memory dst)
        internal
        pure
        returns (bytes memory out)
    {
        bytes memory dstPrime = abi.encodePacked(dst, uint8(dst.length));
        bytes memory zPad = new bytes(64); // s_in_bytes for SHA-256
        bytes32 b0 = sha256(abi.encodePacked(zPad, message, uint16(256), uint8(0), dstPrime));
        out = new bytes(256);
        bytes32 bi = sha256(abi.encodePacked(b0, uint8(1), dstPrime));
        assembly { mstore(add(out, 32), bi) }
        for (uint8 i = 2; i <= 8; i++) {
            bi = sha256(abi.encodePacked(b0 ^ bi, i, dstPrime));
            assembly { mstore(add(out, mul(i, 32)), bi) }
        }
    }

    /// @dev Reduce a 64-byte chunk of expand output to an Fp element (16-zero + 48 BE).
    function _reduceFp(bytes memory u, uint256 off) private view returns (bytes memory) {
        // One copy rather than 64 checked single-byte ones — about 5,000 gas
        // each time, four times per hash.
        require(off + 64 <= u.length, "bls: reduce past the end");
        bytes memory base = new bytes(64);
        assembly {
            mcopy(add(base, 32), add(add(u, 32), off), 64)
        }
        bytes memory input = abi.encodePacked(uint256(64), uint256(1), uint256(48), base, uint8(1), P);
        bytes memory r = _call(MODEXP, input, 48);
        return abi.encodePacked(bytes16(0), r); // left-pad to the 64-byte field encoding
    }

    /// @dev Hash a message to G2 (RFC 9380 RO): hash_to_field -> 2x map -> add.
    ///      Cofactor clearing in MAP_FP2_TO_G2 is a homomorphism, so mapping each
    ///      point then summing equals clearing the cofactor of the sum.
    function hashToG2(bytes memory message) internal view returns (bytes memory) {
        return hashToG2(message, DST);
    }

    function hashToG2(bytes memory message, bytes memory dst) internal view returns (bytes memory) {
        bytes memory u = expandMessageXmd(message, dst);
        bytes memory q0 = _call(MAP_FP2_TO_G2, abi.encodePacked(_reduceFp(u, 0), _reduceFp(u, 64)), 256);
        bytes memory q1 = _call(MAP_FP2_TO_G2, abi.encodePacked(_reduceFp(u, 128), _reduceFp(u, 192)), 256);
        return _call(G2ADD, abi.encodePacked(q0, q1), 256);
    }

    /// @dev Pairing check e(aggPk, H) * e(negG1, sig) == 1.
    function pairingCheck(bytes memory aggPk, bytes memory hPoint, bytes memory negG1, bytes memory sig)
        internal
        view
        returns (bool)
    {
        bytes memory ret = _call(PAIRING, abi.encodePacked(aggPk, hPoint, negG1, sig), 32);
        // The precompile returns exactly one word, and `_call` asked for 32 bytes.
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint256(bytes32(ret)) == 1;
    }
}

src/SavannaVerifier.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;

import {BLS} from "./BLS.sol";

/// @title SavannaVerifier — verify Vaulta/Antelope (Savanna) finality on Ethereum.
/// @notice On-chain twin of the Antelope-side verifier, mirrored to the EVM: it
///         stores a finalizer policy and checks a Quorum Certificate (aggregate
///         BLS signature over a finality digest) using the EIP-2537 precompiles.
///         Finality requires BOTH the signed weight reaching the threshold AND a
///         valid aggregate signature.
contract SavannaVerifier {
    // Negated G1 generator (EIP-2537), for the pairing check e(-G1, sig)·e(pk,H)==1.
    bytes constant NEG_G1 =
        hex"0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb00000000000000000000000000000000114d1d6855d545a8aa7d76c8cf2e21f267816aef1db507c96655b9d5caac42364e6f38ba0ecb751bad54dcd6b939c2ca";

    /**
     * A finalizer's seat in the current policy: `generation << 64 | weight`.
     *
     * The generation stamp is what makes installing a policy cheap. Clearing the
     * outgoing seats before writing the incoming ones would cost twenty-one
     * writes to zero and twenty-one back from zero; stamping instead means a
     * seat simply stops counting the moment `policyGeneration` moves past it, so
     * an installation writes only the incoming twenty-one and the swap is atomic.
     *
     * Keyed by the keccak of the public key as *Antelope* packs it, never by
     * position. A rotation inserts a finalizer wherever the chain's ordering puts
     * it: between generations 120 and 121 nineteen of twenty-one finalizers were
     * unchanged and only SEVEN kept their position, so anything positional
     * rewrites almost the whole set to change two of it.
     */
    mapping(bytes32 => uint96) public coreEntry;

    /**
     * The EIP-2537 form of every finalizer key ever seen, by its Antelope hash.
     *
     * Write-once and never cleared, and deliberately separate from `coreEntry`:
     * knowing a key is not the same as it carrying weight. A key here can be
     * aggregated so the signature maths closes over signers this contract does
     * not otherwise care about, while only `coreEntry` decides what counts
     * toward the threshold. That separation is what lets the policy lag behind
     * the chain without the verifier losing the ability to check a certificate.
     */
    mapping(bytes32 => bytes) public pubkeyOf;

    /**
     * Aggregate public keys already computed, by the exact set that produced them.
     *
     * Measured on Amoy 2026-09-23: a `submitRoot` costs 2,395,047 gas, and
     * `verifyFinality` is 2,336,588 of it. Only ~317k of that is BLS the
     * precompiles charge for — the rest is reading twenty-one 128-byte keys out
     * of storage and packing them for the multi-scalar multiplication. And it
     * recomputes the same sum every time, because a quorum's membership barely
     * moves: between generations 120 and 121, nineteen of twenty-one finalizers
     * were unchanged.
     *
     * So the sum is remembered. A repeat of the same signer set skips the loop
     * and the MSM entirely and pays for `hashToG2` and one pairing.
     *
     * The generation is in the key, and that is not tidiness. Weight and
     * threshold are properties of a policy — `coreWeightOf` returns zero for a
     * seat from another generation — so a set that cleared the bar under one
     * policy need not clear it under the next. Caching without the generation
     * would skip the loop and the threshold check with it.
     *
     * Everything else that decides the answer is in the key too: change a key,
     * change a bit, and it is a different entry that gets computed from scratch.
     */
    mapping(bytes32 => bytes) public aggregateOf;

    uint64 public threshold;

    /// Summed weight of the current policy, for the threshold sanity check.
    uint64 public coreTotalWeight;

    /**
     * Which Telos finalizer generation the seats belong to.
     *
     * Generations are monotonic on the settlement chain, so this makes policy
     * replacement directional: an installation may only move forward, and a
     * replay of an older policy — even a correctly proven one — is refused.
     */
    uint32 public policyGeneration;

    /// The weight a key carries right now, or zero if its seat is stale.
    function coreWeightOf(bytes32 key) public view returns (uint64) {
        uint96 e = coreEntry[key];
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint32(e >> 64) == policyGeneration ? uint64(e) : 0;
    }

    /**
     * Who may install a finalizer policy.
     *
     * The contract this was ported from had `setPolicy` wide open — anyone could
     * overwrite the finalizer set with their own key and release the entire
     * vault. That was survivable on a testnet with nothing in it. It is not an
     * oversight to carry forward.
     */
    address public policyAdmin;
    address public pendingPolicyAdmin;

    event PolicySet(uint32 indexed generation, uint256 finalizers, uint64 threshold);
    event KeyRegistered(bytes32 indexed key);
    event PolicyAdminOffered(address indexed to);
    event PolicyAdminSet(address indexed admin);

    error NotPolicyAdmin();
    error NotPendingPolicyAdmin();

    constructor() {
        policyAdmin = msg.sender;
        emit PolicyAdminSet(msg.sender);
    }

    /**
     * Offer the role. Two steps, because losing it is worse than losing the vault
     * key: if the generation chain ever breaks — a long outage, pruned handover
     * blocks — `setPolicy` is the only way to re-bootstrap the light client, and
     * without it every future root is unverifiable and the bridge is over.
     */
    function offerPolicyAdmin(address to) external {
        if (msg.sender != policyAdmin) revert NotPolicyAdmin();
        pendingPolicyAdmin = to;
        emit PolicyAdminOffered(to);
    }

    function acceptPolicyAdmin() external {
        if (msg.sender != pendingPolicyAdmin) revert NotPendingPolicyAdmin();
        policyAdmin = msg.sender;
        pendingPolicyAdmin = address(0);
        emit PolicyAdminSet(msg.sender);
    }

    /**
     * Install the active finalizer policy — the trusted bootstrap.
     *
     * A light client cannot start from nothing, so this path exists and is
     * admin-only. What should replace it for ongoing rotation is a proved
     * transition: the settlement chain publishes a policy diff inside a header
     * its own finalizers signed, so one generation step can be verified against
     * the policy already on file rather than asserted by a key.
     *
     * That matters more here than it looks. Mirroring every generation costs a
     * full rewrite of the policy, and a settlement chain that rotates twice a day
     * makes that expensive enough to tempt the shortcut of installing a superset
     * of all registered validators and never updating it. A superset is strictly
     * weaker than the chain it follows: with the standby keys included, an
     * attacker needs fewer of the genuinely active validators than the chain's own
     * threshold requires, and no threshold choice fixes it — matching the chain
     * would need more signatures than a real certificate ever carries.
     */
    function setPolicy(
        bytes[] calldata rawKeys,
        uint64[] calldata weights,
        uint64 _threshold,
        uint32 generation
    ) external {
        if (msg.sender != policyAdmin) revert NotPolicyAdmin();
        require(rawKeys.length == weights.length, "length mismatch");
        // Checked again in `_finishPolicy`; here so a replayed generation is
        // refused as that, not as the "seated twice" it would look like to `_seat`.
        require(generation > policyGeneration, "policy must move forward");
        uint64 total;
        for (uint256 i = 0; i < rawKeys.length; i++) {
            total += _seat(_rememberKey(rawKeys[i]), weights[i], generation);
        }
        _finishPolicy(_threshold, generation, total, rawKeys.length);
    }

    /**
     * Convert and remember a key if it is new; either way return its identity.
     *
     * The conversion is the expensive part of installing a policy, so it happens
     * once per distinct key rather than once per installation.
     *
     * No proof of possession is asked for here, and none is needed: a key only
     * reaches this path from a policy the chain's own signatures vouched for, so
     * the settlement chain already checked it at registration.
     */
    function _rememberKey(bytes calldata raw96) internal returns (bytes32 key) {
        require(raw96.length == 96, "pubkey must be 96 raw bytes");
        key = keccak256(raw96);
        if (pubkeyOf[key].length == 0) pubkeyOf[key] = _rawG1ToEip2537(raw96);
    }

    /**
     * Learn a finalizer key from its proof of possession, without a policy.
     *
     * Permissionless, because a proof of possession is self-validating: it is a
     * signature by the key over itself, and nothing about where it came from
     * matters. Telos verifies one at `regfinkey` and then discards it, but the
     * historical action still carries it, so any copy will do.
     *
     * **This is the guard against rogue keys, and it is not optional.** A key
     * accepted on a caller's word can be chosen as
     *
     *     pk = X − (sum of the keys the caller claims also signed)
     *
     * which is plain point arithmetic on public values — no search, no luck. The
     * aggregate then collapses to `X`, whose private key the attacker picked, and
     * a signature they produced alone verifies against the whole set. Demanding
     * possession blocks it: the discrete log of that `pk` is exactly what they
     * cannot know.
     *
     * A key learned here can be aggregated but carries no weight of its own —
     * `coreWeight` decides what counts toward the threshold, and only a policy
     * sets that. So registering a key, even a hostile one, grants nothing.
     */
    function registerKey(bytes calldata raw96, bytes calldata pop192) external {
        require(raw96.length == 96, "pubkey must be 96 raw bytes");
        require(pop192.length == 192, "proof must be 192 raw bytes");
        // The point at infinity: a zero key with a zero proof passes the pairing,
        // since both sides are one. It would carry no weight, but it is not a key.
        require(keccak256(raw96) != keccak256(new bytes(96)), "the zero key is not a key");
        bytes32 key = keccak256(raw96);
        if (pubkeyOf[key].length != 0) return; // already known; nothing to prove

        bytes memory pk = _rawG1ToEip2537(raw96);
        // The message is the key's own Antelope bytes, under the proof-of-
        // possession ciphersuite — `eosio::bls_pop_verify`, transcribed.
        bytes memory h = BLS.hashToG2(raw96, BLS.POP_DST);
        require(BLS.pairingCheck(pk, h, NEG_G1, _rawG2ToEip2537(pop192)), "proof of possession rejected");

        pubkeyOf[key] = pk;
        emit KeyRegistered(key);
    }

    /// An Antelope 192-byte affine G2 signature in the precompile's encoding.
    function _rawG2ToEip2537(bytes calldata raw) internal pure returns (bytes memory out) {
        out = new bytes(256);
        for (uint256 c = 0; c < 4; c++) {
            uint256 src = c * 48;
            uint256 dst = c * 64 + 63;
            for (uint256 i = 0; i < 48; i++) out[dst - i] = raw[src + i];
        }
    }

    /**
     * Give `key` a seat in `generation`, and return the weight it carries.
     *
     * A key seated twice would add its weight to the total twice and hold only
     * one seat, so the threshold check would pass a threshold below half the
     * real weight. `generation` is strictly newer than any installed one, so a
     * seat already stamped with it can only come from earlier in this same call.
     *
     * Weight zero is a seat: Spring's `set_finalizers` allows it, and refusing a
     * policy the chain activated would leave this client unable to follow it
     * (ETH-Telos audit B-07). It counts toward nothing — `coreWeightOf` returns
     * the zero — and is still stamped, so it cannot be seated twice either.
     */
    function _seat(bytes32 key, uint64 weight, uint32 generation) internal returns (uint64) {
        require(uint32(coreEntry[key] >> 64) != generation, "key seated twice");
        coreEntry[key] = (uint96(generation) << 64) | uint96(weight);
        return weight;
    }

    /**
     * An Antelope 96-byte affine G1 key as the EIP-2537 precompiles want it.
     *
     * Antelope writes each 48-byte coordinate little-endian and unpadded;
     * EIP-2537 wants big-endian left-padded to 64. Feeding one to the other is
     * not an error anywhere — it is simply a different point, which verifies
     * nothing.
     */
    function _rawG1ToEip2537(bytes calldata raw) internal pure returns (bytes memory out) {
        out = new bytes(128);
        for (uint256 i = 0; i < 48; i++) {
            out[63 - i] = raw[i]; // x
            out[127 - i] = raw[48 + i]; // y
        }
    }

    /**
     * Shared tail of every policy installation: the checks that must hold however
     * the keys arrived, admin-supplied or proven.
     *
     * Kept separate rather than duplicated because the proven path is the one
     * meant to be used, and a check that guards only the admin path guards the
     * path that matters least.
     */
    function _finishPolicy(uint64 _threshold, uint32 generation, uint64 total, uint256 count)
        internal
    {
        require(count > 0, "empty policy");
        require(_threshold > 0, "threshold must be positive");
        require(generation > policyGeneration, "policy must move forward");
        // The chain's own safety bound: a threshold at or below half the weight
        // would let two disjoint quorums finalize conflicting blocks.
        require(_threshold > total / 2 && _threshold <= total, "threshold outside the safe range");

        threshold = _threshold;
        coreTotalWeight = total;
        // Last, because the seats written above only start counting once this
        // moves — which is what makes the swap atomic and the old seats stale.
        policyGeneration = generation;
        emit PolicySet(generation, count, _threshold);
    }

    /// @notice Verify a Savanna QC over `digest`.
    /// @param digest the 32-byte finality digest the finalizers signed
    /// @param bits   participation bitset, LSB-first per byte (finalizer i = bit i)
    /// @param signature the 256-byte aggregate G2 signature
    // public rather than external: WireLightClient calls it internally, and an
    // external self-call would pay call overhead for nothing.
    /**
     * Verify a Savanna quorum certificate over `digest`.
     *
     * `policyKeys` is the chain's actual finalizer policy in its own order — one
     * key identity per bit of the certificate's bitset. It is supplied rather
     * than stored because the two need not be the same set: this contract's
     * policy may lag the chain, and a certificate still has to be checkable
     * against whoever really signed it.
     *
     * Supplying it grants nothing. Every key named must already be known, so an
     * unregistered one cannot be slipped in; weight comes only from
     * `coreWeightOf`, so a signer outside the policy contributes to the
     * aggregate and to nothing else; and a caller who mislabels which bit is
     * which key simply produces an aggregate the signature does not match. The
     * pairing is the check — the list is only how the contract is told where to
     * look.
     *
     * Except for one thing the pairing cannot see: a key named twice. Its weight
     * would count twice, and the aggregate would hold it twice — `k·pk` — which
     * `k` times one finalizer's own signature satisfies. One key would pass for
     * a quorum. A real policy never repeats a key, so a signer's key may not
     * appear earlier in the list; checked pairwise, which for a policy of
     * twenty-one is cheaper than any structure that would avoid it.
     *
     * And nothing verifies before a policy exists. The threshold is zero until
     * one is installed, and every weight counts toward zero.
     *
     * Finality needs BOTH: the signed weight reaching the threshold, and a valid
     * aggregate signature. Either alone is worthless.
     */
    function verifyFinality(
        bytes memory digest,
        bytes calldata bits,
        bytes calldata signature,
        bytes32[] calldata policyKeys
    ) public returns (bool) {
        require(signature.length == 256, "sig must be 256 bytes");
        require(threshold != 0, "no finalizer policy installed");

        // `abi.encode`, not packed: packed, the keys' tail and the bitset's head
        // run together, and two different sets can share an id.
        bytes32 setId = keccak256(abi.encode(policyGeneration, policyKeys, bits));
        bytes memory aggPk = aggregateOf[setId];

        if (aggPk.length == 0) {
            bytes memory msmInput;
            uint256 signedWeight;
            uint256 signers;
            for (uint256 i = 0; i < policyKeys.length; i++) {
                if (!_signed(bits, i)) continue;
                for (uint256 j = 0; j < i; j++) {
                    require(policyKeys[j] != policyKeys[i], "key named twice");
                }
                bytes memory pk = pubkeyOf[policyKeys[i]];
                require(pk.length == 128, "signer key not registered");
                msmInput = abi.encodePacked(msmInput, pk, uint256(1));
                signedWeight += coreWeightOf(policyKeys[i]);
                signers++;
            }
            require(signers > 0, "no signers");
            require(signedWeight >= threshold, "below quorum threshold");

            aggPk = BLS.aggregateG1(msmInput);
            aggregateOf[setId] = aggPk;
        }

        bytes memory h = BLS.hashToG2(digest);
        return BLS.pairingCheck(aggPk, h, NEG_G1, signature);
    }

    /// Whether bit `i` of the LSB-first bitset is set; bits past its end are not.
    function _signed(bytes calldata bits, uint256 i) internal pure returns (bool) {
        return (i >> 3) < bits.length && ((uint8(bits[i >> 3]) >> (i & 7)) & 1) == 1;
    }

    function hashToG2(bytes calldata message) external view returns (bytes memory) {
        return BLS.hashToG2(message);
    }
}

src/TelosLightClient.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;

import {BLS} from "./BLS.sol";
import {SavannaVerifier} from "./SavannaVerifier.sol";

/**
 * TelosLightClient — verify Telos finality once, then settle many withdrawals
 * against it cheaply.
 *
 * A BLS check costs ~785k gas over a 21-key policy. Paying that per withdrawal
 * would be absurd, so it
 * happens once per root: someone submits the components of a block's finality
 * digest together with the finalizers' quorum certificate, this contract rebuilds
 * the digest, checks the signature, and remembers the `finalityMroot`. Afterwards
 * a withdrawal only folds a merkle branch, which is tens of thousands of gas.
 *
 * ## The digest layout
 *
 * Three nested SHA-256 commitments, transcribed from
 * `block_header_state::compute_finality_digest` and the `FC_REFLECT` declarations
 * beside it. Integers are little-endian because that is how `fc::raw::pack`
 * writes them; getting any of it wrong yields a digest that is perfectly
 * well-formed and simply never verifies, with nothing to point at.
 *
 * This layout is not assumed. The same computation in `src/savanna/finality.ts`
 * was checked against 5,999 consecutive Telos blocks by comparing it to the
 * digest the chain itself reports in `latest_qc_claim_finality_digest` — the
 * value the finalizers actually signed.
 *
 * ## The two fields that are not constants here
 *
 * `lastPendingPolicyDigest` and `lastPendingPolicyStart` describe the finalizer
 * policy that is pending when the block is produced. On a chain with one
 * finalizer since genesis they never move, and the contract this was ported from
 * treats them as fixed. Telos rotates its finalizer set twice a day, so they
 * change constantly and the submitter has to supply the right pair — which the
 * off-chain side tracks by applying the policy diffs carried in signed block
 * headers.
 *
 * ## Transition blocks need both halves of the certificate
 *
 * While a policy is pending — `activeGeneration != lastPendingGeneration` — a
 * Spring certificate carries two signatures over the same digest, one per
 * policy, and the block is final only if BOTH reach their own threshold
 * (`qc_t::verify_basic`, `qc_t::is_strong`). The active half alone is a claim
 * the chain itself does not accept: if the incoming finalizers never reach
 * quorum, the chain's LIB stops right there, and a restart from the last final
 * block would discard exactly the blocks such a root vouches for.
 *
 * So on a transition block the pending half is checked too, against the policy
 * the digest names — its own keys, its own weights, its own threshold. Anywhere
 * else the pending half must be empty.
 *
 * Spring also demands that a finalizer seated in both policies votes the same
 * way in both halves. That is not checked here, and need not be: only strong
 * votes are accepted, so each half on its own proves a quorum of its policy
 * signed this digest strongly — which is the fact finality rests on. Which of
 * a dual finalizer's signatures went into which aggregate changes nothing about
 * it. Nor could it be enforced: the active policy's key order is supplied by the
 * caller and committed nowhere in the digest.
 */
contract TelosLightClient is SavannaVerifier {
    /// Components of one block's finality digest, as the indexer serves them.
    struct FinalityInputs {
        uint32 majorVersion;
        uint32 minorVersion;
        uint32 activeGeneration;
        uint32 lastPendingGeneration;
        bytes32 finalityMroot;
        // level 2
        bytes32 lastPendingPolicyDigest;
        uint32 lastPendingPolicyStart;
        // level 3
        bytes32 reversibleBlocksMroot;
        uint32 qcClaimBlockNum;
        bytes32 qcClaimFinalityDigest;
        uint32 qcClaimTimestamp;
        uint32 timestamp;
        bytes32 baseDigest;
    }

    /**
     * The pending policy's half of a transition block's certificate.
     *
     * `policy` is the pending policy exactly as `fc::raw::pack` writes it; the
     * digest commits to its `sha256`, so it is authenticated by the active half's
     * signature over that digest. `bits` indexes that policy's own order, and
     * `signature` is the 256-byte EIP-2537 aggregate of its strong votes.
     *
     * All three empty on any block that is not a transition.
     */
    struct PendingQc {
        bytes policy;
        bytes bits;
        bytes signature;
    }

    /// finalityMroot values proven to be signed by the finalizer policy.
    mapping(bytes32 => bool) public trustedRoots;

    /**
     * Finalizer policy digests the chain's own signatures have vouched for.
     *
     * Every finality digest commits, at level 2, to `sha256` of the policy that
     * was last pending when the block was produced. So a verified certificate
     * does not only establish a tree root — it also establishes, for free, what
     * the next finalizer policy hashes to. Recording that here turns the
     * expensive part of following the chain's rotation into an ordinary hash
     * comparison later.
     *
     * Only ever written after a certificate verifies, so an entry cannot be
     * invented.
     */
    mapping(uint32 => bytes32) public provenPolicyDigest;

    event RootAccepted(bytes32 indexed finalityMroot, bytes32 finalityDigest, uint32 timestamp);

    error PolicyNotProven();
    error PolicyDigestMismatch();
    error PolicyNotNewer();
    error BadPublicKeyLength();
    error PolicyTrailingBytes();
    error VaruintTooLong();
    error PendingQcRequired();
    error PendingQcOutsideTransition();
    error PendingGenerationMismatch();
    error PendingBelowThreshold();
    error PendingQcRejected();
    error UnknownDigestVersion();

    /**
     * Rebuild a block's finality digest and remember its root if the QC signs it.
     *
     * Permissionless on purpose. Whoever submits it is a courier: they cannot
     * change what the digest commits to, and a wrong one simply fails the pairing
     * check. Requiring an authorized relayer here would put a liveness dependency
     * in the one place the design is supposed to have none.
     *
     * `pending` is the second half of a transition block's certificate, and
     * empty for every other block. See the contract notes.
     */
    function submitRoot(
        FinalityInputs calldata f,
        bytes calldata bits,
        bytes calldata signature,
        bytes32[] calldata policyKeys,
        PendingQc calldata pending
    ) external {
        // The layout rebuilt below is version 1's; a new major version may mean
        // the same bytes say something else.
        if (f.majorVersion != 1) revert UnknownDigestVersion();
        bytes32 l3 = sha256(
            abi.encodePacked(
                f.reversibleBlocksMroot,
                _le32(f.qcClaimBlockNum),
                f.qcClaimFinalityDigest,
                _le32(f.qcClaimTimestamp),
                _le32(f.timestamp),
                f.baseDigest
            )
        );
        bytes32 l2 = sha256(
            abi.encodePacked(f.lastPendingPolicyDigest, _le32(f.lastPendingPolicyStart), l3)
        );
        bytes32 digest = sha256(
            abi.encodePacked(
                _le32(f.majorVersion),
                _le32(f.minorVersion),
                _le32(f.activeGeneration),
                _le32(f.lastPendingGeneration),
                f.finalityMroot,
                l2
            )
        );

        require(
            verifyFinality(abi.encodePacked(digest), bits, signature, policyKeys),
            "finality proof rejected"
        );

        // After the active half, not before: its signature over the digest is
        // what authenticates the pending policy the digest names.
        if (f.activeGeneration != f.lastPendingGeneration) {
            _verifyPendingHalf(f, digest, pending);
        } else if (pending.policy.length != 0 || pending.bits.length != 0 || pending.signature.length != 0) {
            revert PendingQcOutsideTransition();
        }

        trustedRoots[f.finalityMroot] = true;
        // The certificate just vouched for this pairing too, and recording it is
        // what `installPolicy` later stands on — but only once the pending policy
        // is final. A strong certificate on this digest makes final the block it
        // CLAIMS; until that claim reaches the block that proposed the policy, a
        // fork may still replace it, and installing it would strand this client
        // on finalizers the chain never activates (ETH-Telos audit B-03). The
        // root itself is final either way.
        if (f.activeGeneration == f.lastPendingGeneration || f.qcClaimTimestamp >= f.lastPendingPolicyStart) {
            provenPolicyDigest[f.lastPendingGeneration] = f.lastPendingPolicyDigest;
        }
        emit RootAccepted(f.finalityMroot, digest, f.timestamp);
    }

    /**
     * The pending policy's half of a transition certificate, checked on its own terms.
     *
     * The policy must be the one the digest commits to, of the generation the
     * digest names; its signers are counted with its own weights against its own
     * threshold, and their aggregate must sign the same digest. Nothing is
     * stored — the keys come straight from the authenticated bytes, so no key
     * without a seat in this policy can take part.
     */
    function _verifyPendingHalf(FinalityInputs calldata f, bytes32 digest, PendingQc calldata q)
        internal
        view
    {
        if (q.policy.length == 0) revert PendingQcRequired();
        if (sha256(q.policy) != f.lastPendingPolicyDigest) revert PolicyDigestMismatch();
        require(q.signature.length == 256, "sig must be 256 bytes");

        (uint32 generation, uint64 policyThreshold, uint32 count, uint256 o) = _policyHeader(q.policy);
        if (generation != f.lastPendingGeneration) revert PendingGenerationMismatch();

        bytes memory msmInput;
        uint256 signedWeight;
        for (uint256 i = 0; i < count; i++) {
            uint64 weight;
            bytes calldata key;
            (weight, key, o) = _finalizerAt(q.policy, o);
            if (!_signed(q.bits, i)) continue;
            msmInput = abi.encodePacked(msmInput, _rawG1ToEip2537(key), uint256(1));
            signedWeight += weight;
        }
        if (o != q.policy.length) revert PolicyTrailingBytes();
        if (signedWeight == 0 || signedWeight < policyThreshold) revert PendingBelowThreshold();

        bytes memory h = BLS.hashToG2(abi.encodePacked(digest));
        if (!BLS.pairingCheck(BLS.aggregateG1(msmInput), h, NEG_G1, q.signature)) revert PendingQcRejected();
    }

    /**
     * Install a finalizer policy the chain's own signatures already vouched for.
     *
     * Permissionless, and that is the point: this is what replaces the admin
     * bootstrap. The caller supplies the policy exactly as `fc::raw::pack` writes
     * it, and the only thing that makes it acceptable is that its `sha256` equals
     * a digest recorded by a verified certificate. A wrong byte anywhere — a
     * substituted key, a reordered finalizer, an edited description — changes the
     * hash and the call reverts.
     *
     * ## Why this needs no signature check of its own
     *
     * A block's finality digest commits at level 2 to the digest of the policy
     * that was *last pending* when it was produced. Between a policy becoming
     * pending and becoming active there is a window — two blocks on Telos — where
     * the active policy is still the previous generation. A certificate from that
     * window is signed by both policies and commits to the digest of the next
     * one, and `submitRoot` checks both halves before recording it — from a block
     * of the window whose claim reaches the one that proposed the policy, the
     * point where the policy is final. So one such `submitRoot` carries the whole
     * handover, and this function is the cheap half that follows.
     *
     * That is also why there is no policy *diff* anywhere in this contract. The
     * chain publishes the successor in full; reconstructing it from an ordered
     * diff would be a second, harder way to learn the same thing.
     */
    function installPolicy(bytes calldata packedPolicy) external {
        (uint32 generation, uint64 policyThreshold, uint32 count, uint256 o) = _policyHeader(packedPolicy);

        bytes32 proven = provenPolicyDigest[generation];
        if (proven == bytes32(0)) revert PolicyNotProven();
        if (sha256(packedPolicy) != proven) revert PolicyDigestMismatch();
        // Generations only move forward on the settlement chain, so an older
        // policy is a replay even when its digest is genuine.
        if (generation <= policyGeneration) revert PolicyNotNewer();

        uint64 total;
        for (uint256 i = 0; i < count; i++) {
            uint64 weight;
            bytes calldata key;
            (weight, key, o) = _finalizerAt(packedPolicy, o);
            total += _seat(_rememberKey(key), weight, generation);
        }
        // Trailing bytes would still have changed the digest, so this cannot be
        // an attack — but it would mean the parser has drifted from the chain's
        // packing, which is worth failing loudly for.
        if (o != packedPolicy.length) revert PolicyTrailingBytes();

        _finishPolicy(policyThreshold, generation, total, count);
    }

    /**
     * The fixed head of a packed `finalizer_policy`: generation, threshold, and
     * the number of finalizers, with the offset of the first one.
     */
    function _policyHeader(bytes calldata policy)
        internal
        pure
        returns (uint32 generation, uint64 policyThreshold, uint32 count, uint256 o)
    {
        generation = _u32(policy, 0);
        policyThreshold = _u64(policy, 4);
        (count, o) = _varuint32(policy, 12);
    }

    /**
     * One packed `finalizer_authority` at `o`: its weight, its 96-byte key, and
     * the offset of the next one.
     */
    function _finalizerAt(bytes calldata policy, uint256 o)
        internal
        pure
        returns (uint64 weight, bytes calldata key, uint256 next)
    {
        // description: hashed into the digest, but nothing on this chain
        // needs to read it.
        uint32 descLen;
        (descLen, o) = _varuint32(policy, o);
        o += descLen;

        weight = _u64(policy, o);
        o += 8;

        uint32 keyLen;
        (keyLen, o) = _varuint32(policy, o);
        if (keyLen != 96) revert BadPublicKeyLength();
        key = policy[o:o + 96];
        next = o + 96;
    }

    function _u32(bytes calldata b, uint256 o) internal pure returns (uint32 v) {
        for (uint256 i = 4; i > 0; i--) v = (v << 8) | uint8(b[o + i - 1]);
    }

    function _u64(bytes calldata b, uint256 o) internal pure returns (uint64 v) {
        for (uint256 i = 8; i > 0; i--) v = (v << 8) | uint8(b[o + i - 1]);
    }

    /** LEB128, which is how `fc::raw::pack` writes a length. */
    function _varuint32(bytes calldata b, uint256 o) internal pure returns (uint32 v, uint256 next) {
        uint256 shift;
        while (true) {
            uint8 byteValue = uint8(b[o]);
            o++;
            v |= uint32(byteValue & 0x7f) << shift;
            if (byteValue & 0x80 == 0) break;
            shift += 7;
            if (shift > 28) revert VaruintTooLong();
        }
        return (v, o);
    }

    /** A uint32 as the four little-endian bytes `fc::raw::pack` would write. */
    function _le32(uint32 v) internal pure returns (bytes4) {
        return bytes4(
            uint32(
                ((v & 0xff) << 24) | (((v >> 8) & 0xff) << 16) | (((v >> 16) & 0xff) << 8)
                    | ((v >> 24) & 0xff)
            )
        );
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.