Skip to content
Verified contractPartialMIT

WormholeOracle

Address0x940a87f18ceb24e58c447851cbb3a57c6fa8d52c
Balance

0 ETH

 

Transactions

21

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 100,000,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,175,815
Creation transaction
0x2c5229153a…624e0276d0

src/integrations/oracles/wormhole/WormholeOracle.sol

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

import { IAttester } from "../../../interfaces/IAttester.sol";

import { LibAddress } from "../../../libs/LibAddress.sol";
import { MessageEncodingLib } from "../../../libs/MessageEncodingLib.sol";

import { BaseInputOracle } from "../../../oracles/BaseInputOracle.sol";
import { ChainMap } from "../../../oracles/ChainMap.sol";

import { WormholeVerifier } from "./external/callworm/WormholeVerifier.sol";
import { IWormhole } from "./interfaces/IWormhole.sol";

/**
 * @notice Wormhole Oracle.
 * Implements a transparent oracle that allows both sending and receiving messages along with
 * exposing the hash of received messages.
 * @dev The contract is mostly trustless but requires someone to translate Wormhole chainIds into
 * proper chainIds. These maps once set are immutable and trustless.
 */
contract WormholeOracle is ChainMap, BaseInputOracle, WormholeVerifier {
    using LibAddress for address;

    error NotAllPayloadsValid();
    error RefundFailed();

    /// @dev Wormhole generally defines 15 to be equal to Finality
    uint8 constant WORMHOLE_CONSISTENCY = 15;

    IWormhole public immutable WORMHOLE;

    constructor(
        address _owner,
        address _wormhole
    ) payable ChainMap(_owner) WormholeVerifier(_wormhole) {
        WORMHOLE = IWormhole(_wormhole);
    }

    // --- Sending Proofs --- //

    /**
     * @notice Takes proofs that have been marked as valid by a source and submits them to Wormhole for broadcast.
     * @param source Application that has payloads that are marked as valid.
     * @param payloads List of payloads to broadcast.
     * @return refund If too much value has been sent, the excess will be returned to msg.sender.
     */
    function submit(
        address source,
        bytes[] calldata payloads
    ) public payable returns (uint256 refund) {
        if (!IAttester(source).hasAttested(payloads)) revert NotAllPayloadsValid();
        return _submit(source, payloads);
    }

    // --- Wormhole Logic --- //

    /**
     * @notice Submits packaged payloads to Wormhole.
     * @param source Application that has payloads that are marked as valid.
     * @param payloads List of payloads that have been checked for validity and are to be broadcasted.
     * @return refund If too much value has been sent, the excess will be returned to msg.sender.
     */
    function _submit(
        address source,
        bytes[] calldata payloads
    ) internal returns (uint256 refund) {
        bytes memory message = MessageEncodingLib.encodeMessage(source.toIdentifier(), payloads);

        uint256 packageCost = WORMHOLE.messageFee();
        WORMHOLE.publishMessage{ value: packageCost }(0, message, WORMHOLE_CONSISTENCY);

        // Refund excess value if any.
        if (msg.value > packageCost) {
            refund = msg.value - packageCost;
            (bool success,) = msg.sender.call{ value: refund }("");
            if (!success) revert RefundFailed();
        }
    }

    /**
     * @notice Takes a wormhole VAA and stores attestations of the contained payloads.
     * @param rawMessage Wormhole VAA
     */
    function receiveMessage(
        bytes calldata rawMessage
    ) external {
        (uint16 remoteMessagingProtocolChainIdentifier, bytes32 remoteSenderIdentifier, bytes calldata message) =
            _verifyPacket(rawMessage);
        (bytes32 application, bytes32[] memory payloadHashes) = MessageEncodingLib.getHashesOfEncodedPayloads(message);

        uint256 remoteChainId = _getMappedChainId(uint256(remoteMessagingProtocolChainIdentifier));

        uint256 numPayloads = payloadHashes.length;
        for (uint256 i; i < numPayloads; ++i) {
            bytes32 payloadHash = payloadHashes[i];
            _attestations[remoteChainId][remoteSenderIdentifier][application][payloadHash] = true;

            emit OutputProven(remoteChainId, remoteSenderIdentifier, application, payloadHash);
        }
    }

    /**
     * @param _message Wormhole VAA.
     * @return sourceIdentifier Wormhole chainId of the chain the message was emitted from.
     * @return implementationIdentifier Emitter of the message.
     * @return message_ Sent message contained within the VAA as a slice.
     */
    function _verifyPacket(
        bytes calldata _message
    ) internal view returns (uint16 sourceIdentifier, bytes32 implementationIdentifier, bytes calldata message_) {
        // This uses the custom verification logic found in ./external/callworm/WormholeVerifier.sol.
        (sourceIdentifier, implementationIdentifier, message_) = parseAndVerifyVM(_message);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

src/integrations/oracles/wormhole/external/callworm/GettersGetter.sol

// contracts/Getters.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

import "../wormhole/Getters.sol";

contract GettersGetter {
    error WormholeStateAddressZero();

    Getters internal immutable WORMHOLE_STATE;

    constructor(
        address wormholeState
    ) payable {
        if (wormholeState == address(0)) revert WormholeStateAddressZero();
        WORMHOLE_STATE = Getters(wormholeState);
    }

    function getGuardianSet(
        uint32 index
    ) public view returns (Structs.GuardianSet memory) {
        return WORMHOLE_STATE.getGuardianSet(index);
    }

    function getCurrentGuardianSetIndex() public view returns (uint32) {
        return WORMHOLE_STATE.getCurrentGuardianSetIndex();
    }

    function getGuardianSetExpiry() public view returns (uint32) {
        return WORMHOLE_STATE.getGuardianSetExpiry();
    }

    function governanceActionIsConsumed(
        bytes32 hash
    ) public view returns (bool) {
        return WORMHOLE_STATE.governanceActionIsConsumed(hash);
    }

    function isInitialized(
        address impl
    ) public view returns (bool) {
        return WORMHOLE_STATE.isInitialized(impl);
    }

    function chainId() public view returns (uint16) {
        return WORMHOLE_STATE.chainId();
    }

    function evmChainId() public view returns (uint256) {
        return WORMHOLE_STATE.evmChainId();
    }

    function isFork() public view returns (bool) {
        return WORMHOLE_STATE.isFork();
    }

    function governanceChainId() public view returns (uint16) {
        return WORMHOLE_STATE.governanceChainId();
    }

    function governanceContract() public view returns (bytes32) {
        return WORMHOLE_STATE.governanceContract();
    }

    function messageFee() public view returns (uint256) {
        return WORMHOLE_STATE.messageFee();
    }

    function nextSequence(
        address emitter
    ) public view returns (uint64) {
        return WORMHOLE_STATE.nextSequence(emitter);
    }
}

src/integrations/oracles/wormhole/external/callworm/WormholeVerifier.sol

// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

import "../wormhole/Structs.sol";
import "../wormhole/libraries/external/BytesLib.sol";
import "./GettersGetter.sol";

/**
 * @notice Optimised message verifier for Wormhole
 * @dev Is based on the Wormhole verification library.
 */
contract WormholeVerifier is GettersGetter {
    using BytesLib for bytes;

    error InvalidSignatory();
    error SignatureIndicesNotAscending();
    error GuardianIndexOutOfBounds();
    error VMVersionIncompatible();
    error TooManyGuardians();
    error VMSignatureInvalid();
    error InvalidGuardianSet();
    error GuardianSetExpired();
    error NoQuorum();

    constructor(
        address wormholeState
    ) payable GettersGetter(wormholeState) { }

    /// @dev parseAndVerifyVM serves to parse an encodedVM and wholly validate it for consumption
    function parseAndVerifyVM(
        bytes calldata encodedVM
    ) public view returns (uint16 emitterChainId, bytes32 emitterAddress, bytes calldata payload) {
        bytes calldata signatures;
        bytes32 bodyHash;
        uint32 guardianSetIndex;
        (emitterChainId, emitterAddress, guardianSetIndex, signatures, bodyHash, payload) = parseVM(encodedVM);
        /// setting checkHash to false as we can trust the hash field in this case given that parseVM computes and then
        /// sets the hash field above
        verifyVMInternal(guardianSetIndex, signatures, bodyHash);
    }

    /**
     * @dev `verifyVMInternal` serves to validate an arbitrary vm against a valid Guardian set
     * if checkHash is set then the hash field of the vm is verified against the hash of its contents
     * in the case that the vm is securely parsed and the hash field can be trusted, checkHash can be set to false
     * as the check would be redundant
     */
    function verifyVMInternal(
        uint32 guardianSetIndex,
        bytes calldata signatures,
        bytes32 bodyHash
    ) internal view {
        /// @dev Obtain the current guardianSet for the guardianSetIndex provided
        Structs.GuardianSet memory guardianSet = getGuardianSet(guardianSetIndex);

        /**
         * @dev Checks whether the guardianSet has zero keys
         * WARNING: This keys check is critical to ensure the guardianSet has keys present AND to ensure
         * that guardianSet key size doesn't fall to zero and negatively impact quorum assessment.  If guardianSet
         * key length is 0 and vm.signatures length is 0, this could compromise the integrity of both vm and
         * signature verification.
         */
        if (guardianSet.keys.length == 0) revert InvalidGuardianSet();

        /// @dev Checks if VM guardian set index matches the current index (unless the current set is expired).
        if (guardianSet.expirationTime < block.timestamp) {
            if (guardianSetIndex != getCurrentGuardianSetIndex()) revert GuardianSetExpired();
        }

        /**
         * @dev We're using a fixed point number transformation with 1 decimal to deal with rounding.
         *   WARNING: This quorum check is critical to assessing whether we have enough Guardian signatures to validate
         * a VM
         *   if making any changes to this, obtain additional peer review. If guardianSet key length is 0 and
         *   vm.signatures length is 0, this could compromise the integrity of both vm and signature verification.
         */
        if (uint8(signatures[0]) < quorum(guardianSet.keys.length)) revert NoQuorum();

        /// @dev Verify the proposed vm.signatures against the guardianSet
        verifySignatures(bodyHash, signatures, guardianSet);

        /// If we are here, we've validated the VM is a valid multi-sig that matches the guardianSet.
    }

    /**
     * @dev verifySignatures serves to validate arbitrary signatures against an arbitrary guardianSet
     *  - it intentionally does not solve for expectations within guardianSet (you should use verifyVM if you need these
     * protections)
     *  - it intentioanlly does not solve for quorum (you should use verifyVM if you need these protections)
     *  - it intentionally returns true when signatures is an empty set (you should use verifyVM if you need these
     * protections)
     */
    function verifySignatures(
        bytes32 hash,
        bytes calldata signatures,
        Structs.GuardianSet memory guardianSet
    ) public pure {
        uint8 lastIndex = 0;
        uint256 guardianCount = guardianSet.keys.length;
        uint256 signersLen = uint8(bytes1(signatures[0]));
        uint256 index = 1;
        unchecked {
            for (uint256 i = 0; i < signersLen; ++i) {
                uint8 guardianIndex = uint8(bytes1(signatures[index]));
                index += 1;

                bytes32 r;
                bytes32 s;
                bytes1 v1;
                assembly {
                    // Load r, s via assembly to save gas.
                    // bytes32 r = bytes32(signatures[index: index + 32]);
                    r := calldataload(add(signatures.offset, index))
                    index := add(index, 0x20) // index += 32;
                    // bytes32 s = bytes32(signatures[index: index + 32]);
                    s := calldataload(add(signatures.offset, index))
                    index := add(index, 0x20) // index += 32;
                    // bytes1(signatures[index:index + 1])
                    v1 := calldataload(add(signatures.offset, index))
                    index := add(index, 0x01) // index += 1;
                }
                uint8 v = uint8(v1) + 27;
                address signatory = ecrecover(hash, v, r, s);
                // ecrecover returns 0 for invalid signatures. We explicitly require valid signatures to avoid
                // unexpected
                // behaviour due to the default storage slot value also being 0.
                if (signatory == address(0)) revert InvalidSignatory();

                /// Ensure that provided signature indices are ascending only
                if (!(i == 0 || guardianIndex > lastIndex)) revert SignatureIndicesNotAscending();
                lastIndex = guardianIndex;

                /// @dev Ensure that the provided signature index is within the
                /// bounds of the guardianSet. This is implicitly checked by the array
                /// index operation below, so this check is technically redundant.
                /// However, reverting explicitly here ensures that a bug is not
                /// introduced accidentally later due to the nontrivial storage
                /// semantics of solidity.
                if (guardianIndex >= guardianCount) revert GuardianIndexOutOfBounds();

                /// Check to see if the signer of the signature does not match a specific Guardian key at the provided
                /// index
                if (signatory != guardianSet.keys[guardianIndex]) revert VMSignatureInvalid();
            }

            /// If we are here, we've validated that the provided signatures are valid for the provided guardianSet
        }
    }

    /**
     * @dev parseVM serves to parse an encodedVM into a vm struct
     *  - it intentionally performs no validation functions, it simply parses raw into a struct
     */
    function parseVM(
        bytes calldata encodedVM
    )
        public
        view
        virtual
        returns (
            uint16 emitterChainId,
            bytes32 emitterAddress,
            uint32 guardianSetIndex,
            bytes calldata signatures,
            bytes32 bodyHash,
            bytes calldata payload
        )
    {
        unchecked {
            uint256 index = 0;

            uint8 version = uint8(bytes1(encodedVM[0:1]));

            index += 1;

            // SECURITY: Note that currently the VM.version is not part of the hash
            // and for reasons described below it cannot be made part of the hash.
            // This means that this field's integrity is not protected and cannot be trusted.
            // This is not a problem today since there is only one accepted version, but it
            // could be a problem if we wanted to allow other versions in the future.
            if (version != 1) revert VMVersionIncompatible();

            guardianSetIndex = uint32(bytes4(encodedVM[1:4 + 1]));
            index += 4;

            // Parse Signatures
            uint256 signersLen = uint8(bytes1(encodedVM[5:5 + 1]));
            signatures = encodedVM[5:5 + 1 + signersLen * (1 + 32 + 32 + 1)];
            index += 1 + signersLen * (1 + 32 + 32 + 1);
            // signatures = new Structs.Signature[](signersLen);
            // for (uint i = 0; i < signersLen; ++i) {
            //     signatures[i].guardianIndex = uint8(bytes1(encodedVM[index:index+1]));
            //     index += 1;

            //     signatures[i].r = bytes32(encodedVM[index:index+32]);
            //     index += 32;
            //     signatures[i].s = bytes32(encodedVM[index:index+32]);
            //     index += 32;
            //     signatures[i].v = uint8(bytes1(encodedVM[index:index+1])) + 27;
            //     index += 1;
            // }

            /*
            Hash the body

            SECURITY: Do not change the way the hash of a VM is computed!
            Changing it could result into two different hashes for the same observation.
            But xDapps rely on the hash of an observation for replay protection.
            */
            bytes calldata body = encodedVM[index:];
            bodyHash = keccak256(abi.encodePacked(keccak256(body)));

            // Parse the body
            // vm.timestamp = uint32(bytes4(encodedVM[index:index+4]));
            // index += 4;

            // vm.nonce = uint32(bytes4(encodedVM[index:index+4]));
            // index += 4;
            index += 8;

            emitterChainId = uint16(bytes2(encodedVM[index:index += 2]));

            assembly ("memory-safe") {
                // emitterAddress = bytes32(encodedVM[index:index+32]);
                emitterAddress := calldataload(add(encodedVM.offset, index))
            }
            // index += 32;

            // vm.sequence = uint64(bytes8(encodedVM[index:index+8]));
            // index += 8;

            // vm.consistencyLevel = uint8(bytes1(encodedVM[index:index+1]));
            // index += 1;

            index += 32 + 8 + 1;
            payload = encodedVM[index:];
        }
    }

    /**
     * @dev quorum serves solely to determine the number of signatures required to achieve quorum
     */
    function quorum(
        uint256 numGuardians
    ) public pure virtual returns (uint256 numSignaturesRequiredForQuorum) {
        unchecked {
            // The max number of guardians is 255
            if (numGuardians >= 256) revert TooManyGuardians();
            return ((numGuardians * 2) / 3) + 1;
        }
    }
}

src/integrations/oracles/wormhole/external/wormhole/Getters.sol

// contracts/Getters.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

import "./State.sol";

contract Getters is State {
    function getGuardianSet(
        uint32 index
    ) public view returns (Structs.GuardianSet memory) {
        return _state.guardianSets[index];
    }

    function getCurrentGuardianSetIndex() public view returns (uint32) {
        return _state.guardianSetIndex;
    }

    function getGuardianSetExpiry() public view returns (uint32) {
        return _state.guardianSetExpiry;
    }

    function governanceActionIsConsumed(
        bytes32 hash
    ) public view returns (bool) {
        return _state.consumedGovernanceActions[hash];
    }

    function isInitialized(
        address impl
    ) public view returns (bool) {
        return _state.initializedImplementations[impl];
    }

    function chainId() public view returns (uint16) {
        return _state.provider.chainId;
    }

    function evmChainId() public view returns (uint256) {
        return _state.evmChainId;
    }

    function isFork() public view returns (bool) {
        return evmChainId() != block.chainid;
    }

    function governanceChainId() public view returns (uint16) {
        return _state.provider.governanceChainId;
    }

    function governanceContract() public view returns (bytes32) {
        return _state.provider.governanceContract;
    }

    function messageFee() public view returns (uint256) {
        return _state.messageFee;
    }

    function nextSequence(
        address emitter
    ) public view returns (uint64) {
        return _state.sequences[emitter];
    }
}

src/integrations/oracles/wormhole/external/wormhole/State.sol

// contracts/State.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

import "./Structs.sol";

contract Events {
    event LogGuardianSetChanged(uint32 oldGuardianIndex, uint32 newGuardianIndex);

    event LogMessagePublished(address emitter_address, uint32 nonce, bytes payload);
}

contract Storage {
    struct WormholeState {
        Structs.Provider provider;
        // Mapping of guardian_set_index => guardian set
        mapping(uint32 => Structs.GuardianSet) guardianSets;
        // Current active guardian set index
        uint32 guardianSetIndex;
        // Period for which a guardian set stays active after it has been replaced
        uint32 guardianSetExpiry;
        // Sequence numbers per emitter
        mapping(address => uint64) sequences;
        // Mapping of consumed governance actions
        mapping(bytes32 => bool) consumedGovernanceActions;
        // Mapping of initialized implementations
        mapping(address => bool) initializedImplementations;
        uint256 messageFee;
        // EIP-155 Chain ID
        uint256 evmChainId;
    }
}

contract State {
    Storage.WormholeState _state;
}

src/integrations/oracles/wormhole/external/wormhole/Structs.sol

// contracts/Structs.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

interface Structs {
    struct Provider {
        uint16 chainId;
        uint16 governanceChainId;
        bytes32 governanceContract;
    }

    struct GuardianSet {
        address[] keys;
        uint32 expirationTime;
    }

    struct Signature {
        bytes32 r;
        bytes32 s;
        uint8 v;
        uint8 guardianIndex;
    }

    struct VM {
        uint8 version;
        uint32 timestamp;
        uint32 nonce;
        uint16 emitterChainId;
        bytes32 emitterAddress;
        uint64 sequence;
        uint8 consistencyLevel;
        bytes payload;
        uint32 guardianSetIndex;
        Signature[] signatures;
        bytes32 hash;
    }
}

src/integrations/oracles/wormhole/external/wormhole/libraries/external/BytesLib.sol

// SPDX-License-Identifier: Unlicense
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.8.0 <0.9.0;

library BytesLib {
    function concat(
        bytes memory _preBytes,
        bytes memory _postBytes
    ) internal pure returns (bytes memory) {
        bytes memory tempBytes;

        assembly {
            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Store the length of the first bytes array at the beginning of
            // the memory for tempBytes.
            let length := mload(_preBytes)
            mstore(tempBytes, length)

            // Maintain a memory counter for the current write location in the
            // temp bytes array by adding the 32 bytes for the array length to
            // the starting location.
            let mc := add(tempBytes, 0x20)
            // Stop copying when the memory counter reaches the length of the
            // first bytes array.
            let end := add(mc, length)

            for {
                // Initialize a copy counter to the start of the _preBytes data,
                // 32 bytes into its memory.
                let cc := add(_preBytes, 0x20)
            } lt(mc, end) {
                // Increase both counters by 32 bytes each iteration.
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                // Write the _preBytes data into the tempBytes memory 32 bytes
                // at a time.
                mstore(mc, mload(cc))
            }

            // Add the length of _postBytes to the current length of tempBytes
            // and store it as the new length in the first 32 bytes of the
            // tempBytes memory.
            length := mload(_postBytes)
            mstore(tempBytes, add(length, mload(tempBytes)))

            // Move the memory counter back from a multiple of 0x20 to the
            // actual end of the _preBytes data.
            mc := end
            // Stop copying when the memory counter reaches the new combined
            // length of the arrays.
            end := add(mc, length)

            for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } { mstore(mc, mload(cc)) }

            // Update the free-memory pointer by padding our last write location
            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
            // next 32 byte block, then round down to the nearest multiple of
            // 32. If the sum of the length of the two arrays is zero then add
            // one before rounding down to leave a blank 32 bytes (the length block with 0).
            mstore(
                0x40,
                and(
                    add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                    not(31) // Round down to the nearest 32 bytes.
                )
            )
        }

        return tempBytes;
    }

    function concatStorage(
        bytes storage _preBytes,
        bytes memory _postBytes
    ) internal {
        assembly {
            // Read the first 32 bytes of _preBytes storage, which is the length
            // of the array. (We don't need to use the offset into the slot
            // because arrays use the entire slot.)
            let fslot := sload(_preBytes.slot)
            // Arrays of 31 bytes or less have an even value in their slot,
            // while longer arrays have an odd value. The actual length is
            // the slot divided by two for odd values, and the lowest order
            // byte divided by two for even values.
            // If the slot is even, bitwise and the slot with 255 and divide by
            // two to get the length. If the slot is odd, bitwise and the slot
            // with -1 and divide by two.
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)
            let newlength := add(slength, mlength)
            // slength can contain both the length and contents of the array
            // if length < 32 bytes so let's prepare for that
            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
            switch add(lt(slength, 32), lt(newlength, 32))
            case 2 {
                // Since the new array still fits in the slot, we just need to
                // update the contents of the slot.
                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                sstore(
                    _preBytes.slot,
                    // all the modifications to the slot are inside this
                    // next block
                    add(
                        // we can just add to the slot contents because the
                        // bytes we want to change are the LSBs
                        fslot,
                        add(
                            mul(
                                div(
                                    // load the bytes from memory
                                    mload(add(_postBytes, 0x20)),
                                    // zero all bytes to the right
                                    exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                            ),
                            // increase length by the double of the memory
                            // bytes length
                            mul(mlength, 2)
                        )
                    )
                )
            }
            case 1 {
                // The stored value fits in the slot, but the combined value
                // will exceed it.
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // The contents of the _postBytes array start 32 bytes into
                // the structure. Our first read should obtain the `submod`
                // bytes that can fit into the unused space in the last word
                // of the stored array. To get this, we read 32 bytes starting
                // from `submod`, so the data we read overlaps with the array
                // contents by `submod` bytes. Masking the lowest-order
                // `submod` bytes allows us to add that value directly to the
                // stored value.

                let submod := sub(32, slength)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(
                    sc,
                    add(
                        and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
                        and(mload(mc), mask)
                    )
                )

                for {
                    mc := add(mc, 0x20)
                    sc := add(sc, 1)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } { sstore(sc, mload(mc)) }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
            default {
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                // Start copying to the last used word of the stored array.
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // Copy over the first `submod` bytes of the new data as in
                // case 1 above.
                let slengthmod := mod(slength, 32)
                let mlengthmod := mod(mlength, 32)
                let submod := sub(32, slengthmod)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(sc, add(sload(sc), and(mload(mc), mask)))

                for {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } { sstore(sc, mload(mc)) }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
        }
    }

    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, "slice_overflow");
        require(_bytes.length >= _start + _length, "slice_outOfBounds");

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } { mstore(mc, mload(cc)) }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (address) {
        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint8(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint8) {
        require(_bytes.length >= _start + 1, "toUint8_outOfBounds");
        uint8 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    function toUint16(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint16) {
        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
        uint16 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x2), _start))
        }

        return tempUint;
    }

    function toUint32(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint32) {
        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
        uint32 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    function toUint64(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint64) {
        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
        uint64 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x8), _start))
        }

        return tempUint;
    }

    function toUint96(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint96) {
        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
        uint96 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0xc), _start))
        }

        return tempUint;
    }

    function toUint128(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint128) {
        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
        uint128 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x10), _start))
        }

        return tempUint;
    }

    function toUint256(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint256) {
        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
        uint256 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    function toBytes32(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (bytes32) {
        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
        bytes32 tempBytes32;

        assembly {
            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes32;
    }

    function equal(
        bytes memory _preBytes,
        bytes memory _postBytes
    ) internal pure returns (bool) {
        bool success = true;

        assembly {
            let length := mload(_preBytes)

            // if lengths don't match the arrays are not equal
            switch eq(length, mload(_postBytes))
            case 1 {
                // cb is a circuit breaker in the for loop since there's
                //  no said feature for inline assembly loops
                // cb = 1 - don't breaker
                // cb = 0 - break
                let cb := 1

                let mc := add(_preBytes, 0x20)
                let end := add(mc, length)

                for { let cc := add(_postBytes, 0x20) }
                // the next line is the loop condition:
                // while(uint256(mc < end) + cb == 2)
                eq(add(lt(mc, end), cb), 2) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // if any of these checks fails then arrays are not equal
                    if iszero(eq(mload(mc), mload(cc))) {
                        // unsuccessful:
                        success := 0
                        cb := 0
                    }
                }
            }
            default {
                // unsuccessful:
                success := 0
            }
        }

        return success;
    }

    function equalStorage(
        bytes storage _preBytes,
        bytes memory _postBytes
    ) internal view returns (bool) {
        bool success = true;

        assembly {
            // we know _preBytes_offset is 0
            let fslot := sload(_preBytes.slot)
            // Decode the length of the stored array like in concatStorage().
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)

            // if lengths don't match the arrays are not equal
            switch eq(slength, mlength)
            case 1 {
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                if iszero(iszero(slength)) {
                    switch lt(slength, 32)
                    case 1 {
                        // blank the last byte which is the length
                        fslot := mul(div(fslot, 0x100), 0x100)

                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                            // unsuccessful:
                            success := 0
                        }
                    }
                    default {
                        // cb is a circuit breaker in the for loop since there's
                        //  no said feature for inline assembly loops
                        // cb = 1 - don't breaker
                        // cb = 0 - break
                        let cb := 1

                        // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                        let sc := keccak256(0x0, 0x20)

                        let mc := add(_postBytes, 0x20)
                        let end := add(mc, mlength)

                        // the next line is the loop condition:
                        // while(uint256(mc < end) + cb == 2)
                        for { } eq(add(lt(mc, end), cb), 2) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            if iszero(eq(sload(sc), mload(mc))) {
                                // unsuccessful:
                                success := 0
                                cb := 0
                            }
                        }
                    }
                }
            }
            default {
                // unsuccessful:
                success := 0
            }
        }

        return success;
    }
}

src/integrations/oracles/wormhole/interfaces/IWormhole.sol

// contracts/Messages.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

interface IWormhole {
    struct GuardianSet {
        address[] keys;
        uint32 expirationTime;
    }

    struct Signature {
        bytes32 r;
        bytes32 s;
        uint8 v;
        uint8 guardianIndex;
    }

    struct VM {
        uint8 version;
        uint32 timestamp;
        uint32 nonce;
        uint16 emitterChainId;
        bytes32 emitterAddress;
        uint64 sequence;
        uint8 consistencyLevel;
        bytes payload;
        uint32 guardianSetIndex;
        Signature[] signatures;
        bytes32 hash;
    }

    struct ContractUpgrade {
        bytes32 module;
        uint8 action;
        uint16 chain;
        address newContract;
    }

    struct GuardianSetUpgrade {
        bytes32 module;
        uint8 action;
        uint16 chain;
        GuardianSet newGuardianSet;
        uint32 newGuardianSetIndex;
    }

    struct SetMessageFee {
        bytes32 module;
        uint8 action;
        uint16 chain;
        uint256 messageFee;
    }

    struct TransferFees {
        bytes32 module;
        uint8 action;
        uint16 chain;
        uint256 amount;
        bytes32 recipient;
    }

    struct RecoverChainId {
        bytes32 module;
        uint8 action;
        uint256 evmChainId;
        uint16 newChainId;
    }

    event LogMessagePublished(
        address indexed sender, uint64 sequence, uint32 nonce, bytes payload, uint8 consistencyLevel
    );
    event ContractUpgraded(address indexed oldContract, address indexed newContract);
    event GuardianSetAdded(uint32 indexed index);

    function publishMessage(
        uint32 nonce,
        bytes memory payload,
        uint8 consistencyLevel
    ) external payable returns (uint64 sequence);

    function initialize() external;

    function parseAndVerifyVM(
        bytes calldata encodedVM
    ) external view returns (VM memory vm, bool valid, string memory reason);

    function verifyVM(
        VM memory vm
    ) external view returns (bool valid, string memory reason);

    function verifySignatures(
        bytes32 hash,
        Signature[] memory signatures,
        GuardianSet memory guardianSet
    ) external pure returns (bool valid, string memory reason);

    function parseVM(
        bytes memory encodedVM
    ) external pure returns (VM memory vm);

    function quorum(
        uint256 numGuardians
    ) external pure returns (uint256 numSignaturesRequiredForQuorum);

    function getGuardianSet(
        uint32 index
    ) external view returns (GuardianSet memory);

    function getCurrentGuardianSetIndex() external view returns (uint32);

    function getGuardianSetExpiry() external view returns (uint32);

    function governanceActionIsConsumed(
        bytes32 hash
    ) external view returns (bool);

    function isInitialized(
        address impl
    ) external view returns (bool);

    function chainId() external view returns (uint16);

    function isFork() external view returns (bool);

    function governanceChainId() external view returns (uint16);

    function governanceContract() external view returns (bytes32);

    function messageFee() external view returns (uint256);

    function evmChainId() external view returns (uint256);

    function nextSequence(
        address emitter
    ) external view returns (uint64);

    function parseContractUpgrade(
        bytes memory encodedUpgrade
    ) external pure returns (ContractUpgrade memory cu);

    function parseGuardianSetUpgrade(
        bytes memory encodedUpgrade
    ) external pure returns (GuardianSetUpgrade memory gsu);

    function parseSetMessageFee(
        bytes memory encodedSetMessageFee
    ) external pure returns (SetMessageFee memory smf);

    function parseTransferFees(
        bytes memory encodedTransferFees
    ) external pure returns (TransferFees memory tf);

    function parseRecoverChainId(
        bytes memory encodedRecoverChainId
    ) external pure returns (RecoverChainId memory rci);

    function submitContractUpgrade(
        bytes memory _vm
    ) external;

    function submitSetMessageFee(
        bytes memory _vm
    ) external;

    function submitNewGuardianSet(
        bytes memory _vm
    ) external;

    function submitTransferFees(
        bytes memory _vm
    ) external;

    function submitRecoverChainId(
        bytes memory _vm
    ) external;
}

src/interfaces/IAttester.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/**
 * @notice Interface for exposing data that oracles can bridge cross-chain.
 */
interface IAttester {
    function hasAttested(
        bytes[] calldata payloads
    ) external view returns (bool);
}

src/interfaces/IInputOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

interface IInputOracle {
    /**
     * @notice Check if some data has been attested to on the remote chain.
     * @param remoteChainId ChainId of data origin.
     * @param remoteOracle Attestor on the data origin chain.
     * @param application Application that the data originated from.
     * @param dataHash Hash of data.
     */
    function isProven(
        uint256 remoteChainId,
        bytes32 remoteOracle,
        bytes32 application,
        bytes32 dataHash
    ) external view returns (bool);

    /**
     * @notice Check if a series of data has been attested to.
     * @dev More efficient implementation of isProven. Does not return a boolean, instead reverts if false.
     * This function returns true if proofSeries is empty.
     * @param proofSeries remoteChainId, remoteOracle, application, and dataHash encoded in chunks of 32*4=128 bytes.
     */
    function efficientRequireProven(
        bytes calldata proofSeries
    ) external view;
}

src/libs/AssemblyLib.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/// @notice Library for common assembly operations.
library AssemblyLib {
    /**
     * @notice Computes `and(a, b)` in assembly.
     * @dev Does not clean parameters. If both a and b are dirty, c may also be dirty.
     * @param a Left boolean.
     * @param b Right boolean.
     * @return c Whether a and B are both true
     */
    function and(
        bool a,
        bool b
    ) internal pure returns (bool c) {
        assembly ("memory-safe") {
            c := and(a, b)
        }
    }
}

src/libs/LibAddress.sol

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

/// @title LibAddress
/// @notice Library for address-related utility functions
/// @dev Provides functions for converting addresses to cross-chain identifiers
library LibAddress {
    error HasDirtyBits();
    /// @notice Converts an Ethereum address to a bytes32 identifier that can be used across chains
    /// @dev Uses the address's numeric value as a bytes32 identifier by casting type in-place.
    /// @param addr The address to convert
    /// @return identifier The bytes32 identifier representation of the address

    function toIdentifier(
        address addr
    ) internal pure returns (bytes32 identifier) {
        assembly ("memory-safe") {
            identifier := addr
        }
    }

    /// @notice Converts a bytes32 identifier back to an Ethereum address
    /// @dev Reverses the toIdentifier operation by casting through uint256 and uint160
    /// @param identifier The bytes32 identifier to convert
    /// @return _ The address representation of the identifier
    function fromIdentifier(
        bytes32 identifier
    ) internal pure returns (address) {
        return address(uint160(uint256(identifier)));
    }

    /// @notice Converts a uint256 identifier back to an Ethereum address
    /// @dev Reverses the toIdentifier operation by casting through uint160
    /// @param identifier The uint256 identifier to convert
    /// @return _ The address representation of the identifier
    function fromIdentifier(
        uint256 identifier
    ) internal pure returns (address) {
        return address(uint160(identifier));
    }

    /// @notice Converts a uint256 identifier to an Ethereum address while requiring that the leftmost 12 bytes are
    /// empty.
    /// @dev Reverts if any bit is set in the leftmost 12 bytes. Then typecasts transparently.
    /// @param identifier The uint256 identifier to check and convert
    /// @return addr Validates and casted Ethereum address.
    function validatedCleanAddress(
        uint256 identifier
    ) internal pure returns (address addr) {
        if ((identifier >> 160) != 0) revert HasDirtyBits();
        assembly ("memory-safe") {
            // No dirty bits exist, can be casted safely.
            addr := identifier
        }
    }
}

src/libs/MessageEncodingLib.sol

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

/**
 * @notice Library to aid in encoding a series of payloads and decoding a series of payloads.
 * @dev This library does not understand the payloads. Likewise, when parsed payloads are returned hashed.
 * This library uses uint16 lengths, as a result the maximum number of payloads in a single message is 65'535 and the
 * maximum number of bytes in a payload is 65'535.
 *
 * --- Data Structure ---
 *
 *  Common Structure (Repeated 0 times)
 *      SENDER_IDENTIFIER       0       (32 bytes)
 *      + NUM_PAYLOADS          32      (2 bytes)
 *
 *  Payloads (repeated NUM_PAYLOADS times)
 *      PAYLOAD_LENGTH          M_i+0   (2 bytes)
 *      PAYLOAD                 M_i+2   (PAYLOAD_LENGTH bytes)
 *
 * where M_i = the byte offset of the ith payload, calculated as the sum of previous payload lengths plus their 2-byte
 * size prefixes, starting from byte 34 (32 + 2)
 */
library MessageEncodingLib {
    error TooLargePayload(uint256 size);
    error TooManyPayloads(uint256 size);

    /**
     * @notice Encodes a number of payloads into a single message prepended as reported by an application.
     * @param application Source of the messages.
     * @param payloads to be encoded. Maximum 65'535.
     * @return encodedPayload All payloads encoded into a single bytearray.
     */
    function encodeMessage(
        bytes32 application,
        bytes[] calldata payloads
    ) internal pure returns (bytes memory encodedPayload) {
        uint256 numPayloads = payloads.length;
        if (numPayloads > type(uint16).max) revert TooManyPayloads(numPayloads);
        encodedPayload = bytes.concat(application, bytes2(uint16(numPayloads)));
        for (uint256 i; i < numPayloads; ++i) {
            bytes calldata payload = payloads[i];
            uint256 payloadLength = payload.length;
            if (payloadLength > type(uint16).max) revert TooLargePayload(payloadLength);
            encodedPayload = abi.encodePacked(encodedPayload, uint16(payloadLength), payload);
        }
    }

    /**
     * @notice Decodes a bytearray consisting of encoded payloads.
     * @dev Hashes payloads to reduce memory expansion costs.
     * @return application Source of the messages on the payload.
     * @return payloadHashes A hash of every payload.
     */
    function getHashesOfEncodedPayloads(
        bytes calldata encodedPayload
    ) internal pure returns (bytes32 application, bytes32[] memory payloadHashes) {
        unchecked {
            assembly ("memory-safe") {
                application := calldataload(encodedPayload.offset) // = bytes32(encodedPayload[0:32]);
            }
            uint256 numPayloads = uint256(uint16(bytes2(encodedPayload[32:34])));

            payloadHashes = new bytes32[](numPayloads);
            uint256 pointer = 34;
            for (uint256 index = 0; index < numPayloads; ++index) {
                uint256 payloadSize = uint256(uint16(bytes2(encodedPayload[pointer:pointer += 2]))); // unchecked:
                // calldata less than 2**256 bytes.
                bytes calldata payload = encodedPayload[pointer:pointer += payloadSize];
                bytes32 hashedPayload = keccak256(payload);
                payloadHashes[index] = hashedPayload;
            }
        }
    }
}

src/oracles/BaseInputOracle.sol

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

import { IInputOracle } from "../interfaces/IInputOracle.sol";
import { AssemblyLib } from "../libs/AssemblyLib.sol";

/**
 * @notice Base implementation for storing and exposing attesations for consumers. Maintains a storage slot which is
 * exposed through proving interfaces.
 */
abstract contract BaseInputOracle is IInputOracle {
    error NotDivisible(uint256 value, uint256 divisor);
    error NotProven();

    event OutputProven(uint256 chainid, bytes32 remoteIdentifier, bytes32 application, bytes32 payloadHash);

    /**
     * @notice Stores payload attestations.
     * @dev For gas efficiency, payloads are not stored but instead the hash of the payloads are.
     * To recover a payload, provide the payload (or memory) in calldata then hash it and check.
     */
    mapping(
        uint256 remoteChainId
            => mapping(bytes32 senderIdentifier => mapping(bytes32 application => mapping(bytes32 dataHash => bool)))
    ) internal _attestations;

    //--- Data Attestation Validation ---//

    /**
     * @notice Check if some data has been attested to on some chain.
     * @param remoteChainId ChainId of data origin.
     * @param remoteOracle Attestor on the data origin chain.
     * @param application Application that the data originated from.
     * @param dataHash Hash of data.
     * @return bool Whether the hashed data has been attested to.
     */
    function _isProven(
        uint256 remoteChainId,
        bytes32 remoteOracle,
        bytes32 application,
        bytes32 dataHash
    ) internal view virtual returns (bool) {
        return _attestations[remoteChainId][remoteOracle][application][dataHash];
    }

    /**
     * @notice Check if some data has been attested to on some chain.
     * @param remoteChainId ChainId of data origin.
     * @param remoteOracle Attestor on the data origin chain.
     * @param application Application that the data originated from.
     * @param dataHash Hash of data.
     * @return bool Whether the hashed data has been attested to.
     */
    function isProven(
        uint256 remoteChainId,
        bytes32 remoteOracle,
        bytes32 application,
        bytes32 dataHash
    ) external view returns (bool) {
        return _isProven(remoteChainId, remoteOracle, application, dataHash);
    }

    /**
     * @notice Check if a series of data has been attested to.
     * @dev More efficient implementation of isProven. Does not return a boolean, instead reverts if false.
     * This function returns true if proofSeries is empty.
     * @param proofSeries remoteChainId, remoteOracle, application, and dataHash encoded in chucks of 32*4=128 bytes.
     */
    function efficientRequireProven(
        bytes calldata proofSeries
    ) external view {
        unchecked {
            uint256 proofBytes = proofSeries.length;
            uint256 series = proofBytes / (32 * 4);
            if (series * (32 * 4) != proofBytes) revert NotDivisible(proofBytes, 32 * 4); // unchecked: trivial

            uint256 offset;
            uint256 end;
            assembly ("memory-safe") {
                offset := proofSeries.offset
                // unchecked: proofSeries.offset + proofBytes indicates a point in calldata.
                end := add(proofSeries.offset, proofBytes)
            }
            bool state = true;
            for (; offset < end;) {
                // Load the proof description.
                uint256 remoteChainId;
                bytes32 remoteOracle;
                bytes32 application;
                bytes32 dataHash;
                assembly ("memory-safe") {
                    remoteChainId := calldataload(offset)
                    offset := add(offset, 0x20)
                    remoteOracle := calldataload(offset)
                    offset := add(offset, 0x20)
                    application := calldataload(offset)
                    offset := add(offset, 0x20)
                    dataHash := calldataload(offset)
                    offset := add(offset, 0x20)
                }
                state = AssemblyLib.and(state, _isProven(remoteChainId, remoteOracle, application, dataHash));
            }
            if (!state) revert NotProven();
        }
    }
}

src/oracles/ChainMap.sol

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

import { Ownable } from "openzeppelin/access/Ownable.sol";

/**
 * @notice Add chainmapping functionality to an oracle.
 * @dev If this oracle extension is used, it is important that transparent maps are not used; If a chain does not have a
 * corresponding configured id, it cannot be returned as is. The owner can later change this mapping unexpectedly. This
 * is not true for configured mappings.
 */
abstract contract ChainMap is Ownable {
    error AlreadySet();
    error ZeroValue();

    event ChainMapConfigured(uint256 protocolChainIdentifier, uint256 chainId);

    mapping(uint256 protocolChainidentifier => uint256 chainId) public chainIdMap;
    mapping(uint256 chainId => uint256 protocolChainidentifier) public reverseChainIdMap;

    constructor(
        address _owner
    ) Ownable(_owner) { }

    // --- Chain ID Functions --- //

    /**
     * @dev Wrapper for translating chainIds. Intended to override the implementation of the oracle.
     * @param protocolId ChainId of a message.
     * @return chainId "Canonical" chain id.
     */
    function _getMappedChainId(
        uint256 protocolId
    ) internal view virtual returns (uint256 chainId) {
        chainId = chainIdMap[protocolId];
        if (chainId == 0) revert ZeroValue();
    }

    /**
     * @notice Sets an immutable map between 2 chain identifiers.
     * @dev Can only be called once for every chain.
     * @param protocolChainIdentifier Messaging protocol's chain identifier.
     * @param chainId "Canonical" chain id. For EVM, should be block.chainid.
     */
    function setChainMap(
        uint256 protocolChainIdentifier,
        uint256 chainId
    ) external onlyOwner {
        if (protocolChainIdentifier == 0) revert ZeroValue();
        if (chainId == 0) revert ZeroValue();

        if (chainIdMap[protocolChainIdentifier] != 0) revert AlreadySet();
        if (reverseChainIdMap[chainId] != 0) revert AlreadySet();

        chainIdMap[protocolChainIdentifier] = chainId;
        reverseChainIdMap[chainId] = protocolChainIdentifier;

        emit ChainMapConfigured(protocolChainIdentifier, chainId);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 100000000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "the-compact/=lib/the-compact/",
    "permit2/=lib/permit2/",
    "solady/=lib/solady/src/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@eth-optimism/=lib/@eth-optimism/",
    "broadcaster/=lib/broadcaster/src/contracts/",
    "broadcaster-test/=lib/broadcaster/test/",
    "tron-contracts/=lib/tron-contracts/contracts/",
    "OIF/src/=src/",
    "OIF/test/=test/",
    "lib/broadcaster/lib/openzeppelin-contracts/:erc4626-tests/=lib/broadcaster/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/broadcaster/lib/openzeppelin-contracts/:erc4626-tests/=lib/broadcaster/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/broadcaster/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/broadcaster/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/broadcaster/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/broadcaster/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/the-compact/lib/permit2/:solmate/=lib/the-compact/lib/permit2/lib/solmate/",
    "lib/the-compact/lib/permit2/:solmate/=lib/the-compact/lib/permit2/lib/solmate/",
    "lib/the-compact/lib/permit2/:forge-gas-snapshot/=lib/the-compact/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/the-compact/lib/permit2/:forge-gas-snapshot/=lib/the-compact/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/the-compact/lib/permit2/:openzeppelin-contracts/=lib/the-compact/lib/permit2/lib/openzeppelin-contracts/",
    "lib/the-compact/lib/permit2/:openzeppelin-contracts/=lib/the-compact/lib/permit2/lib/openzeppelin-contracts/",
    "lib/broadcaster/:openzeppelin-contracts/=lib/broadcaster/lib/openzeppelin-contracts/",
    "lib/broadcaster/:openzeppelin-contracts/=lib/broadcaster/lib/openzeppelin-contracts/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/permit2/:solmate/=lib/permit2/lib/solmate/",
    "lib/permit2/:solmate/=lib/permit2/lib/solmate/",
    "lib/permit2/:forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/permit2/:forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/permit2/:openzeppelin-contracts/=lib/permit2/lib/openzeppelin-contracts/",
    "lib/permit2/:openzeppelin-contracts/=lib/permit2/lib/openzeppelin-contracts/",
    "lib/tron-contracts/:erc4626-tests/=lib/tron-contracts/lib/erc4626-tests/",
    "lib/tron-contracts/:erc4626-tests/=lib/tron-contracts/lib/erc4626-tests/",
    "lib/tron-contracts/:halmos-cheatcodes/=lib/tron-contracts/lib/halmos-cheatcodes/src/",
    "lib/tron-contracts/:halmos-cheatcodes/=lib/tron-contracts/lib/halmos-cheatcodes/src/",
    "@arbitrum/nitro-contracts/=lib/broadcaster/node_modules/@arbitrum/nitro-contracts/",
    "block-hash-pusher/=lib/broadcaster/lib/block-hash-pusher/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "soledge/=lib/the-compact/lib/soledge/src/",
    "solmate/=lib/permit2/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.