// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
pragma solidity 0.8.16;
library BeaconChainForks {
function getCapellaSlot(uint32 sourceChainId) internal pure returns (uint256) {
// Returns CAPELLA_FORK_EPOCH * SLOTS_PER_EPOCH for the corresponding beacon chain.
if (sourceChainId == 1) {
// https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/fork.md?plain=1#L30
return 6209536;
} else if (sourceChainId == 5) {
// https://blog.ethereum.org/2023/03/08/goerli-shapella-announcement
// https://github.com/eth-clients/goerli/blob/main/prater/config.yaml#L43
return 5193728;
} else {
// We don't know the exact value for Gnosis Chain yet so we return max uint256
// and fallback to bellatrix logic.
return 2 ** 256 - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Bytes
* @notice Bytes is a library for manipulating byte arrays.
*/
library Bytes {
/**
* @custom:attribution https://github.com/GNSPS/solidity-bytes-utils
* @notice Slices a byte array with a given starting index and length. Returns a new byte array
* as opposed to a pointer to the original array. Will throw if trying to slice more
* bytes than exist in the array.
*
* @param _bytes Byte array to slice.
* @param _start Starting index of the slice.
* @param _length Length of the slice.
*
* @return Slice of the input byte array.
*/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "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;
}
/**
* @notice Slices a byte array with a given starting index up to the end of the original byte
* array. Returns a new array rathern than a pointer to the original.
*
* @param _bytes Byte array to slice.
* @param _start Starting index of the slice.
*
* @return Slice of the input byte array.
*/
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
/**
* @notice Converts a byte array into a nibble array by splitting each byte into two nibbles.
* Resulting nibble array will be exactly twice as long as the input byte array.
*
* @param _bytes Input byte array to convert.
*
* @return Resulting nibble array.
*/
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
uint256 bytesLength = _bytes.length;
bytes memory nibbles = new bytes(bytesLength * 2);
bytes1 b;
for (uint256 i = 0; i < bytesLength; ) {
b = _bytes[i];
nibbles[i * 2] = b >> 4;
nibbles[i * 2 + 1] = b & 0x0f;
unchecked {
++i;
}
}
return nibbles;
}
/**
* @notice Compares two byte arrays by comparing their keccak256 hashes.
*
* @param _bytes First byte array to compare.
* @param _other Second byte array to compare.
*
* @return True if the two byte arrays are equal, false otherwise.
*/
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
pragma solidity ^0.8.16;
import {RLPReader} from "optimism-bedrock-contracts/rlp/RLPReader.sol";
import {RLPWriter} from "optimism-bedrock-contracts/rlp/RLPWriter.sol";
import {MerkleTrie} from "optimism-bedrock-contracts/trie/MerkleTrie.sol";
library EventProof {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
/// @notice Verifies that the given log data is valid for the given event proof.
function parseEvent(
bytes[] memory _receiptProof,
bytes32 _receiptRoot,
bytes memory _txIndexRLPEncoded,
uint256 _logIndex,
address _eventSource,
bytes32 _eventSig
) internal pure returns (bytes32[] memory, bytes memory) {
bytes memory value = MerkleTrie.get(_txIndexRLPEncoded, _receiptProof, _receiptRoot);
bytes1 txTypeOrFirstByte = value[0];
// Currently, there are three possible transaction types on Ethereum. Receipts either come
// in the form "TransactionType | ReceiptPayload" or "ReceiptPayload". The currently
// supported set of transaction types are 0x01 and 0x02. In this case, we must truncate
// the first byte to access the payload. To detect the other case, we can use the fact
// that the first byte of a RLP-encoded list will always be greater than 0xc0.
// Reference 1: https://eips.ethereum.org/EIPS/eip-2718
// Reference 2: https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp
uint256 offset;
if (txTypeOrFirstByte == 0x01 || txTypeOrFirstByte == 0x02) {
offset = 1;
} else if (txTypeOrFirstByte >= 0xc0) {
offset = 0;
} else {
revert("Unsupported transaction type");
}
// Truncate the first byte if eneded and get the RLP decoding of the receipt.
uint256 ptr;
assembly {
ptr := add(value, 32)
}
RLPReader.RLPItem memory valueAsItem = RLPReader.RLPItem({
length: value.length - offset,
ptr: RLPReader.MemoryPointer.wrap(ptr + offset)
});
// The length of the receipt must be at least four, as the fourth entry contains events
RLPReader.RLPItem[] memory valueAsList = valueAsItem.readList();
require(valueAsList.length == 4, "Invalid receipt length");
// Read the logs from the receipts and check that it is not ill-formed
RLPReader.RLPItem[] memory logs = valueAsList[3].readList();
require(_logIndex < logs.length, "Log index out of bounds");
RLPReader.RLPItem[] memory relevantLog = logs[_logIndex].readList();
// Validate that the correct contract emitted the event
address sourceContract = relevantLog[0].readAddress();
require(sourceContract == _eventSource, "Event was not emitted by source contract");
// Validate that the event signature matches
bytes32[] memory topics = parseTopics(relevantLog[1].readList());
require(bytes32(topics[0]) == _eventSig, "Event signature does not match");
bytes memory data = relevantLog[2].readBytes();
return (topics, data);
}
function parseTopics(RLPReader.RLPItem[] memory _topicsRLPEncoded)
private
pure
returns (bytes32[] memory)
{
bytes32[] memory topics = new bytes32[](_topicsRLPEncoded.length);
for (uint256 i = 0; i < _topicsRLPEncoded.length; i++) {
topics[i] = bytes32(_topicsRLPEncoded[i].readUint256());
}
return topics;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.8.0;
interface ILightClient {
function consistent() external view returns (bool);
function head() external view returns (uint256);
function headers(uint256 slot) external view returns (bytes32);
function executionStateRoots(uint256 slot) external view returns (bytes32);
function timestamps(uint256 slot) external view returns (uint256);
}
pragma solidity ^0.8.16;
/// @notice The possible states a subscription can be in.
enum SubscriptionStatus {
UNSUBSCIBED,
SUBSCRIBED
}
/// @notice Represents an active subscription, specific to the combination of all of the parameters.
/// @param sourceChainId The chain ID of the source contract.
/// @param sourceAddress The address of the source contract which emits the target event.
/// @param callbackAddress The address of the contract which will receive the event data. MUST be implement
/// the ISubscriptionCallbackReceiver interface.
/// @param eventSig The signature of the event to listen for.
/// @dev A subscription will still be active even if the endSlot has passed. To renew a subscription
/// with different slot ranges, unsubscribe and re-subscribe. The reason slot ranges are not included
/// in this struct is because they shouldn't influence the subscriptionId -- otherwise a subscriber could
/// have overlapping subscriptions on the same event.
struct Subscription {
uint32 sourceChainId;
address sourceAddress;
address callbackAddress;
bytes32 eventSig;
}
interface ISubscriber {
/// @notice Emitted when a new subscription is created.
/// @param subscriptionId The unique identifier for the subscription.
/// @param startSlot The Beacon Chain slot to start listening for events, 0 for all slots up to endSlot.
/// @param endSlot The Beacon Chain slot to stop listening for events, 0 for no limit.
/// @param subscription The subscription details.
/// @dev The startSlot and endSlot are inclusive.
event Subscribe(
bytes32 indexed subscriptionId,
uint64 indexed startSlot,
uint64 indexed endSlot,
Subscription subscription
);
/// @notice Emitted when a subscription is cancelled.
/// @param subscriptionId The unique identifier for the subscription.
/// @param subscription The subscription details.
event Unsubscribe(bytes32 indexed subscriptionId, Subscription subscription);
function subscribe(
uint32 sourceChainId,
address sourceAddress,
address callbackAddress,
bytes32 eventSig,
uint64 startSlot,
uint64 endSlot
) external returns (bytes32 subscriptionId);
function unsubscribe(uint32 sourceChainId, address sourceAddress, bytes32 eventSig)
external
returns (bytes32 subscriptionId);
}
enum PublishStatus {
NOT_EXECUTED,
EXECUTION_FAILED,
EXECUTION_SUCCEEDED
}
interface IPublisher {
/// @notice Emitted when an event is published for a given subscription.
/// @param subscriptionId The unique identifier for the subscription.
/// @param sourceChainId The chain ID of the source contract.
/// @param sourceAddress The address of the source contract which emitted the target event.
/// @param callbackAddress The address of the contract which received the event data.
/// @param success True if the callbackAddress successfully recieved the publish, false otherwise.
event Publish(
bytes32 indexed subscriptionId,
uint32 indexed sourceChainId,
address indexed sourceAddress,
address callbackAddress,
bool success
);
function publishEvent(
bytes calldata srcSlotTxSlotPack,
bytes32[] calldata receiptsRootProof,
bytes32 receiptsRoot,
bytes[] calldata receiptProof,
bytes memory txIndexRLPEncoded,
uint256 logIndex,
Subscription calldata subscription
) external;
}
pragma solidity ^0.8.16;
interface ISubscriptionReceiver {
function handlePublish(
bytes32 subscriptionId,
uint32 sourceChainId,
address sourceAddress,
uint64 slot,
bytes32 publishKey,
bytes32[] memory eventTopics,
bytes memory eventData
) external returns (bytes4);
}
pragma solidity ^0.8.0;
enum MessageStatus {
NOT_EXECUTED,
EXECUTION_FAILED,
EXECUTION_SUCCEEDED
}
struct Message {
uint8 version;
uint64 nonce;
uint32 sourceChainId;
address sourceAddress;
uint32 destinationChainId;
bytes32 destinationAddress;
bytes data;
}
interface ITelepathyRouter {
event SentMessage(uint64 indexed nonce, bytes32 indexed msgHash, bytes message);
function send(uint32 destinationChainId, bytes32 destinationAddress, bytes calldata data)
external
returns (bytes32);
function send(uint32 destinationChainId, address destinationAddress, bytes calldata data)
external
returns (bytes32);
function sendViaStorage(
uint32 destinationChainId,
bytes32 destinationAddress,
bytes calldata data
) external returns (bytes32);
function sendViaStorage(
uint32 destinationChainId,
address destinationAddress,
bytes calldata data
) external returns (bytes32);
}
interface ITelepathyReceiver {
event ExecutedMessage(
uint32 indexed sourceChainId,
uint64 indexed nonce,
bytes32 indexed msgHash,
bytes message,
bool status
);
function executeMessage(
uint64 slot,
bytes calldata message,
bytes[] calldata accountProof,
bytes[] calldata storageProof
) external;
function executeMessageFromLog(
bytes calldata srcSlotTxSlotPack,
bytes calldata messageBytes,
bytes32[] calldata receiptsRootProof,
bytes32 receiptsRoot,
bytes[] calldata receiptProof, // receipt proof against receipt root
bytes memory txIndexRLPEncoded,
uint256 logIndex
) external;
}
interface ITelepathyHandler {
function handleTelepathy(uint32 _sourceChainId, address _sourceAddress, bytes memory _data)
external
returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Bytes } from "../Bytes.sol";
import { RLPReader } from "../rlp/RLPReader.sol";
/**
* @title MerkleTrie
* @notice MerkleTrie is a small library for verifying standard Ethereum Merkle-Patricia trie
* inclusion proofs. By default, this library assumes a hexary trie. One can change the
* trie radix constant to support other trie radixes.
*/
library MerkleTrie {
/**
* @notice Struct representing a node in the trie.
*
* @custom:field encoded The RLP-encoded node.
* @custom:field decoded The RLP-decoded node.
*/
struct TrieNode {
bytes encoded;
RLPReader.RLPItem[] decoded;
}
/**
* @notice Determines the number of elements per branch node.
*/
uint256 internal constant TREE_RADIX = 16;
/**
* @notice Branch nodes have TREE_RADIX elements and one value element.
*/
uint256 internal constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
/**
* @notice Leaf nodes and extension nodes have two elements, a `path` and a `value`.
*/
uint256 internal constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
/**
* @notice Prefix for even-nibbled extension node paths.
*/
uint8 internal constant PREFIX_EXTENSION_EVEN = 0;
/**
* @notice Prefix for odd-nibbled extension node paths.
*/
uint8 internal constant PREFIX_EXTENSION_ODD = 1;
/**
* @notice Prefix for even-nibbled leaf node paths.
*/
uint8 internal constant PREFIX_LEAF_EVEN = 2;
/**
* @notice Prefix for odd-nibbled leaf node paths.
*/
uint8 internal constant PREFIX_LEAF_ODD = 3;
/**
* @notice Verifies a proof that a given key/value pair is present in the trie.
*
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike traditional Merkle
* trees, this proof is executed top-down and consists of a list of RLP-encoded
* nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the included proof is
* correctly constructed.
*
* @return Whether or not the proof is valid.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bool) {
return Bytes.equal(_value, get(_key, _proof, _root));
}
/**
* @notice Retrieves the value associated with a given key.
*
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
*
* @return Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes[] memory _proof,
bytes32 _root
) internal pure returns (bytes memory) {
require(_key.length > 0, "MerkleTrie: empty key");
TrieNode[] memory proof = _parseProof(_proof);
bytes memory key = Bytes.toNibbles(_key);
bytes memory currentNodeID = abi.encodePacked(_root);
uint256 currentKeyIndex = 0;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < proof.length; i++) {
TrieNode memory currentNode = proof[i];
// Key index should never exceed total key length or we'll be out of bounds.
require(
currentKeyIndex <= key.length,
"MerkleTrie: key index exceeds total key length"
);
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),
"MerkleTrie: invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),
"MerkleTrie: invalid large internal hash"
);
} else {
// Nodes smaller than 32 bytes aren't hashed.
require(
Bytes.equal(currentNode.encoded, currentNodeID),
"MerkleTrie: invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// Value is the last element of the decoded list (for branch nodes). There's
// some ambiguity in the Merkle trie specification because bytes(0) is a
// valid value to place into the trie, but for branch nodes bytes(0) can exist
// even when the value wasn't explicitly placed there. Geth treats a value of
// bytes(0) as "key does not exist" and so we do the same.
bytes memory value = RLPReader.readBytes(currentNode.decoded[TREE_RADIX]);
require(
value.length > 0,
"MerkleTrie: value length must be greater than zero (branch)"
);
// Extra proof elements are not allowed.
require(
i == proof.length - 1,
"MerkleTrie: value node must be last node in proof (branch)"
);
return value;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIndex += 1;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - (prefix % 2);
bytes memory pathRemainder = Bytes.slice(path, offset);
bytes memory keyRemainder = Bytes.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
// Whether this is a leaf node or an extension node, the path remainder MUST be a
// prefix of the key remainder (or be equal to the key remainder) or the proof is
// considered invalid.
require(
pathRemainder.length == sharedNibbleLength,
"MerkleTrie: path remainder must share all nibbles with key"
);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
// Prefix of 2 or 3 means this is a leaf node. For the leaf node to be valid,
// the key remainder must be exactly equal to the path remainder. We already
// did the necessary byte comparison, so it's more efficient here to check that
// the key remainder length equals the shared nibble length, which implies
// equality with the path remainder (since we already did the same check with
// the path remainder and the shared nibble length).
require(
keyRemainder.length == sharedNibbleLength,
"MerkleTrie: key remainder must be identical to path remainder"
);
// Our Merkle Trie is designed specifically for the purposes of the Ethereum
// state trie. Empty values are not allowed in the state trie, so we can safely
// say that if the value is empty, the key should not exist and the proof is
// invalid.
bytes memory value = RLPReader.readBytes(currentNode.decoded[1]);
require(
value.length > 0,
"MerkleTrie: value length must be greater than zero (leaf)"
);
// Extra proof elements are not allowed.
require(
i == proof.length - 1,
"MerkleTrie: value node must be last node in proof (leaf)"
);
return value;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
// Prefix of 0 or 1 means this is an extension node. We move onto the next node
// in the proof and increment the key index by the length of the path remainder
// which is equal to the shared nibble length.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIndex += sharedNibbleLength;
} else {
revert("MerkleTrie: received a node with an unknown prefix");
}
} else {
revert("MerkleTrie: received an unparseable node");
}
}
revert("MerkleTrie: ran out of proof elements");
}
/**
* @notice Parses an array of proof elements into a new array that contains both the original
* encoded element and the RLP-decoded element.
*
* @param _proof Array of proof elements to parse.
*
* @return Proof parsed into easily accessible structs.
*/
function _parseProof(bytes[] memory _proof) private pure returns (TrieNode[] memory) {
uint256 length = _proof.length;
TrieNode[] memory proof = new TrieNode[](length);
for (uint256 i = 0; i < length; ) {
proof[i] = TrieNode({ encoded: _proof[i], decoded: RLPReader.readList(_proof[i]) });
unchecked {
++i;
}
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the "hash" within the
* specification, but nodes < 32 bytes are not actually hashed.
*
* @param _node Node to pull an ID for.
*
* @return ID for the node, depending on the size of its contents.
*/
function _getNodeID(RLPReader.RLPItem memory _node) private pure returns (bytes memory) {
return _node.length < 32 ? RLPReader.readRawBytes(_node) : RLPReader.readBytes(_node);
}
/**
* @notice Gets the path for a leaf or extension node.
*
* @param _node Node to get a path for.
*
* @return Node path, converted to an array of nibbles.
*/
function _getNodePath(TrieNode memory _node) private pure returns (bytes memory) {
return Bytes.toNibbles(RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Utility; determines the number of nibbles shared between two nibble arrays.
*
* @param _a First nibble array.
* @param _b Second nibble array.
*
* @return Number of shared nibbles.
*/
function _getSharedNibbleLength(bytes memory _a, bytes memory _b)
private
pure
returns (uint256)
{
uint256 shared;
uint256 max = (_a.length < _b.length) ? _a.length : _b.length;
for (; shared < max && _a[shared] == _b[shared]; ) {
unchecked {
++shared;
}
}
return shared;
}
}
pragma solidity 0.8.16;
import {Message} from "src/amb/interfaces/ITelepathy.sol";
// From here: https://stackoverflow.com/questions/74443594/how-to-slice-bytes-memory-in-solidity
library BytesLib {
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;
// Check length is 0. `iszero` return 1 for `true` and 0 for `false`.
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)
// Calculate length mod 32 to handle slices that are not a multiple of 32 in size.
let lengthmod := and(_length, 31)
// tempBytes will have the following format in memory: <length><data>
// When copying data we will offset the start forward to avoid allocating additional memory
// Therefore part of the length area will be written, but this will be overwritten later anyways.
// In case no offset is require, the start is set to the data region (0x20 from the tempBytes)
// mc will be used to keep track where to copy the data to.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// Same logic as for mc is applied and additionally the start offset specified for the method is added
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
// increase `mc` and `cc` to read the next word from memory
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Copy the data from source (cc location) to the slice data (mc location)
mstore(mc, mload(cc))
}
// Store the length of the slice. This will overwrite any partial data that
// was copied when having slices that are not a multiple of 32.
mstore(tempBytes, _length)
// update free-memory pointer
// allocating the array padded to 32 bytes like the compiler does now
// To set the used memory as a multiple of 32, add 31 to the actual memory usage (mc)
// and remove the modulo 32 (the `and` with `not(31)`)
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)
// update free-memory pointer
// tempBytes uses 32 bytes in memory (even when empty) for the length.
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
}
library MessageEncoding {
function encode(Message memory message) internal pure returns (bytes memory data) {
data = abi.encodePacked(
message.version,
message.nonce,
message.sourceChainId,
message.sourceAddress,
message.destinationChainId,
message.destinationAddress,
message.data
);
}
function encode(
uint8 version,
uint64 nonce,
uint32 sourceChainId,
address sourceAddress,
uint32 destinationChainId,
bytes32 destinationAddress,
bytes memory data
) internal pure returns (bytes memory) {
return abi.encodePacked(
version,
nonce,
sourceChainId,
sourceAddress,
destinationChainId,
destinationAddress,
data
);
}
function decode(bytes memory data) internal pure returns (Message memory message) {
uint8 version;
uint64 nonce; // 64 / 8 = 8
uint32 sourceChainId; // 32 / 8 = 4
address sourceAddress; // 20 bytes
uint32 destinationChainId; // 4 bytes
bytes32 destinationAddress; // 32
// 8 + 4 + 20 + 4 + 32 = 68
assembly {
version := mload(add(data, 1))
nonce := mload(add(data, 9))
sourceChainId := mload(add(data, 13))
sourceAddress := mload(add(data, 33))
destinationChainId := mload(add(data, 37))
destinationAddress := mload(add(data, 69))
}
message.version = version;
message.nonce = nonce;
message.sourceChainId = sourceChainId;
message.sourceAddress = sourceAddress;
message.destinationChainId = destinationChainId;
message.destinationAddress = destinationAddress;
message.data = BytesLib.slice(data, 69, data.length - 69);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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.
*
* By default, the owner account will be the one that deploys the contract. 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
pragma solidity 0.8.16;
import {PublishStatus} from "src/pubsub/interfaces/IPubSub.sol";
import {SubscriptionStatus} from "src/pubsub/interfaces/IPubSub.sol";
import {ILightClient} from "src/lightclient/interfaces/ILightClient.sol";
import {TelepathyRouter} from "src/amb/TelepathyRouter.sol";
contract PubSubStorage {
address public guardian;
address public timelock;
ILightClient public lightClient;
bool public paused;
/*//////////////////////////////////////////////////////////////
PUBLISHER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(bytes32 => PublishStatus) public eventsPublished;
/*//////////////////////////////////////////////////////////////
SUBSCRIBER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(bytes32 => SubscriptionStatus) public subscriptions;
/// @dev This empty reserved space is put in place to allow future versions to add new variables
/// without shifting down storage in the inheritance chain.
/// See: https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#storage-gaps
uint256[50] private __gap; // TODO reduce by 1 for each
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
/**
* @custom:attribution https://github.com/hamdiallam/Solidity-RLP
* @title RLPReader
* @notice RLPReader is a library for parsing RLP-encoded byte arrays into Solidity types. Adapted
* from Solidity-RLP (https://github.com/hamdiallam/Solidity-RLP) by Hamdi Allam with
* various tweaks to improve readability.
*/
library RLPReader {
/**
* Custom pointer type to avoid confusion between pointers and uint256s.
*/
type MemoryPointer is uint256;
/**
* @notice RLP item types.
*
* @custom:value DATA_ITEM Represents an RLP data item (NOT a list).
* @custom:value LIST_ITEM Represents an RLP list item.
*/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/**
* @notice Struct representing an RLP item.
*
* @custom:field length Length of the RLP item.
* @custom:field ptr Pointer to the RLP item in memory.
*/
struct RLPItem {
uint256 length;
MemoryPointer ptr;
}
/**
* @notice Max list length that this library will accept.
*/
uint256 internal constant MAX_LIST_LENGTH = 32;
/**
* @notice Converts bytes to a reference to memory position and length.
*
* @param _in Input bytes to convert.
*
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
// Empty arrays are not RLP items.
require(
_in.length > 0,
"RLPReader: length of an RLP item must be greater than zero to be decodable"
);
MemoryPointer ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* @notice Reads an RLP list value into a list of RLP items.
*
* @param _in RLP list value.
*
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"RLPReader: decoded item type for list is not a list item"
);
require(
listOffset + listLength == _in.length,
"RLPReader: list item has an invalid data remainder"
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({
length: _in.length - offset,
ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
})
);
// We don't need to check itemCount < out.length explicitly because Solidity already
// handles this check on our behalf, we'd just be wasting gas.
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* @notice Reads an RLP list value into a list of RLP items.
*
* @param _in RLP list value.
*
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* @notice Reads an RLP bytes value into bytes.
*
* @param _in RLP bytes value.
*
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"RLPReader: decoded item type for bytes is not a data item"
);
require(
_in.length == itemOffset + itemLength,
"RLPReader: bytes value contains an invalid remainder"
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* @notice Reads an RLP bytes value into bytes.
*
* @param _in RLP bytes value.
*
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* @notice Reads the raw bytes of an RLP item.
*
* @param _in RLP item to read.
*
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
/**
* @notice Decodes the length of an RLP item.
*
* @param _in RLP item to decode.
*
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
// Short-circuit if there's nothing to decode, note that we perform this check when
// the user creates an RLP item via toRLPItem, but it's always possible for them to bypass
// that function and create an RLP item directly. So we need to check this anyway.
require(
_in.length > 0,
"RLPReader: length of an RLP item must be greater than zero to be decodable"
);
MemoryPointer ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
// slither-disable-next-line variable-scope
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"RLPReader: length of content must be greater than string length (short string)"
);
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
require(
strLen != 1 || firstByteOfContent >= 0x80,
"RLPReader: invalid prefix, single byte < 0x80 are not prefixed (short string)"
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"RLPReader: length of content must be > than length of string length (long string)"
);
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
require(
firstByteOfContent != 0x00,
"RLPReader: length of content must not have any leading zeros (long string)"
);
uint256 strLen;
assembly {
strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))
}
require(
strLen > 55,
"RLPReader: length of content must be greater than 55 bytes (long string)"
);
require(
_in.length > lenOfStrLen + strLen,
"RLPReader: length of content must be greater than total length (long string)"
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
// slither-disable-next-line variable-scope
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"RLPReader: length of content must be greater than list length (short list)"
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"RLPReader: length of content must be > than length of list length (long list)"
);
bytes1 firstByteOfContent;
assembly {
firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
}
require(
firstByteOfContent != 0x00,
"RLPReader: length of content must not have any leading zeros (long list)"
);
uint256 listLen;
assembly {
listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))
}
require(
listLen > 55,
"RLPReader: length of content must be greater than 55 bytes (long list)"
);
require(
_in.length > lenOfListLen + listLen,
"RLPReader: length of content must be greater than total length (long list)"
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* @notice Copies the bytes from a memory location.
*
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
*
* @return Copied bytes.
*/
function _copy(
MemoryPointer _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (_length == 0) {
return out;
}
// Mostly based on Solidity's copy_memory_to_memory:
// solhint-disable max-line-length
// https://github.com/ethereum/solidity/blob/34dd30d71b4da730488be72ff6af7083cf2a91f6/libsolidity/codegen/YulUtilFunctions.cpp#L102-L114
uint256 src = MemoryPointer.unwrap(_src) + _offset;
assembly {
let dest := add(out, 32)
let i := 0
for {
} lt(i, _length) {
i := add(i, 32)
} {
mstore(add(dest, i), mload(add(src, i)))
}
if gt(i, _length) {
mstore(add(dest, _length), 0)
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = MemoryPointer.unwrap(_in.ptr) + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @custom:attribution https://github.com/bakaoh/solidity-rlp-encode
* @title RLPWriter
* @author RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh's
* RLPEncode library (https://github.com/bakaoh/solidity-rlp-encode) with minor
* modifications to improve legibility.
*/
library RLPWriter {
/**
* @notice RLP encodes a byte string.
*
* @param _in The byte string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* @notice RLP encodes a list of RLP encoded byte byte strings.
*
* @param _in The list of RLP encoded byte strings.
*
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* @notice RLP encodes a string.
*
* @param _in The string to encode.
*
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* @notice RLP encodes an address.
*
* @param _in The address to encode.
*
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* @notice RLP encodes a uint.
*
* @param _in The uint256 to encode.
*
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* @notice RLP encodes a bool.
*
* @param _in The bool to encode.
*
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/**
* @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.
*
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
*
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* @notice Encode integer in big endian binary form with no leading zeroes.
*
* @param _x The integer to encode.
*
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* @custom:attribution https://github.com/Arachnid/solidity-stringutils
* @notice Copies a piece of memory to another location.
*
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* @custom:attribution https://github.com/sammayo/solidity-rlp-encoder
* @notice Flattens a list of byte strings into one byte string.
*
* @param _list List of byte strings to flatten.
*
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
pragma solidity 0.8.16;
import {BeaconChainForks} from "src/libraries/BeaconChainForks.sol";
struct BeaconBlockHeader {
uint64 slot;
uint64 proposerIndex;
bytes32 parentRoot;
bytes32 stateRoot;
bytes32 bodyRoot;
}
library SSZ {
uint256 internal constant HISTORICAL_ROOTS_LIMIT = 16777216;
uint256 internal constant SLOTS_PER_HISTORICAL_ROOT = 8192;
function toLittleEndian(uint256 v) internal pure returns (bytes32) {
v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64)
| ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
v = (v >> 128) | (v << 128);
return bytes32(v);
}
function restoreMerkleRoot(bytes32 leaf, uint256 index, bytes32[] memory branch)
internal
pure
returns (bytes32)
{
require(2 ** (branch.length + 1) > index);
bytes32 value = leaf;
uint256 i = 0;
while (index != 1) {
if (index % 2 == 1) {
value = sha256(bytes.concat(branch[i], value));
} else {
value = sha256(bytes.concat(value, branch[i]));
}
index /= 2;
i++;
}
return value;
}
function isValidMerkleBranch(bytes32 leaf, uint256 index, bytes32[] memory branch, bytes32 root)
internal
pure
returns (bool)
{
bytes32 restoredMerkleRoot = restoreMerkleRoot(leaf, index, branch);
return root == restoredMerkleRoot;
}
function sszBeaconBlockHeader(BeaconBlockHeader memory header)
internal
pure
returns (bytes32)
{
bytes32 left = sha256(
bytes.concat(
sha256(
bytes.concat(toLittleEndian(header.slot), toLittleEndian(header.proposerIndex))
),
sha256(bytes.concat(header.parentRoot, header.stateRoot))
)
);
bytes32 right = sha256(
bytes.concat(
sha256(bytes.concat(header.bodyRoot, bytes32(0))),
sha256(bytes.concat(bytes32(0), bytes32(0)))
)
);
return sha256(bytes.concat(left, right));
}
function computeDomain(bytes4 forkVersion, bytes32 genesisValidatorsRoot)
internal
pure
returns (bytes32)
{
return bytes32(uint256(0x07 << 248))
| (sha256(abi.encode(forkVersion, genesisValidatorsRoot)) >> 32);
}
function verifyReceiptsRoot(
bytes32 receiptsRoot,
bytes32[] memory receiptsRootProof,
bytes32 headerRoot,
uint64 srcSlot,
uint64 txSlot,
uint32 sourceChainId
) internal pure returns (bool) {
uint256 capellaForkSlot = BeaconChainForks.getCapellaSlot(sourceChainId);
// In Bellatrix we use state.historical_roots, in Capella we use state.historical_summaries
// We use < here because capellaForkSlot is the last slot processed using Bellatrix logic;
// the last batch in state.historical_roots contains the 8192 slots *before* capellaForkSlot.
uint256 stateToHistoricalGIndex = txSlot < capellaForkSlot ? 7 : 27;
// The list state.historical_summaries is empty at the beginning of Capella
uint256 historicalListIndex = txSlot < capellaForkSlot
? txSlot / SLOTS_PER_HISTORICAL_ROOT
: (txSlot - capellaForkSlot) / SLOTS_PER_HISTORICAL_ROOT;
uint256 index;
if (srcSlot == txSlot) {
index = 8 + 3;
index = index * 2 ** 9 + 387;
} else if (srcSlot - txSlot <= SLOTS_PER_HISTORICAL_ROOT) {
index = 8 + 3;
index = index * 2 ** 5 + 6;
index = index * SLOTS_PER_HISTORICAL_ROOT + txSlot % SLOTS_PER_HISTORICAL_ROOT;
index = index * 2 ** 9 + 387;
} else if (txSlot < srcSlot) {
index = 8 + 3;
index = index * 2 ** 5 + stateToHistoricalGIndex;
index = index * 2 + 0;
index = index * HISTORICAL_ROOTS_LIMIT + historicalListIndex;
index = index * 2 + 1;
index = index * SLOTS_PER_HISTORICAL_ROOT + txSlot % SLOTS_PER_HISTORICAL_ROOT;
index = index * 2 ** 9 + 387;
} else {
revert("TargetAMB: invalid target slot");
}
return isValidMerkleBranch(receiptsRoot, index, receiptsRootProof, headerRoot);
}
}
pragma solidity 0.8.16;
import {UUPSUpgradeable} from "@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin-upgradeable/contracts/access/OwnableUpgradeable.sol";
import {Bytes32} from "src/libraries/Typecast.sol";
import {MessageEncoding} from "src/libraries/MessageEncoding.sol";
import {ITelepathyRouter, Message} from "src/amb/interfaces/ITelepathy.sol";
import {TelepathyAccess} from "src/amb/TelepathyAccess.sol";
import {TelepathyStorage} from "src/amb/TelepathyStorage.sol";
/// @title Source Arbitrary Message Bridge
/// @author Succinct Labs
/// @notice This contract is the entrypoint for sending messages to other chains.
contract SourceAMB is TelepathyStorage, ITelepathyRouter {
error SendingDisabled();
error CannotSendToSameChain();
/// @notice Modifier to require that sending is enabled.
modifier isSendingEnabled() {
if (!sendingEnabled) {
revert SendingDisabled();
}
_;
}
/// @notice Sends a message to a destination chain.
/// @param destinationChainId The chain id that specifies the destination chain.
/// @param destinationAddress The contract address that will be called on the destination chain.
/// @param data The data passed to the contract on the other chain
/// @return bytes32 A unique identifier for a message.
function send(uint32 destinationChainId, bytes32 destinationAddress, bytes calldata data)
external
isSendingEnabled
returns (bytes32)
{
if (destinationChainId == block.chainid) revert CannotSendToSameChain();
(bytes memory message, bytes32 messageRoot) =
_getMessageAndRoot(destinationChainId, destinationAddress, data);
emit SentMessage(nonce++, messageRoot, message);
return messageRoot;
}
function send(uint32 destinationChainId, address destinationAddress, bytes calldata data)
external
isSendingEnabled
returns (bytes32)
{
if (destinationChainId == block.chainid) revert CannotSendToSameChain();
(bytes memory message, bytes32 messageRoot) =
_getMessageAndRoot(destinationChainId, Bytes32.fromAddress(destinationAddress), data);
emit SentMessage(nonce++, messageRoot, message);
return messageRoot;
}
/// @notice Sends a message to a destination chain.
/// @notice This method is more expensive than the `send` method as it requires adding to
/// contract storage. Use `send` when interacting with Telepathy to save gas.
/// @param destinationChainId The chain id that specifies the destination chain.
/// @param destinationAddress The contract address that will be called on the destination chain.
/// @param data The data passed to the contract on the other chain
/// @return bytes32 A unique identifier for a message.
function sendViaStorage(
uint32 destinationChainId,
bytes32 destinationAddress,
bytes calldata data
) external isSendingEnabled returns (bytes32) {
if (destinationChainId == block.chainid) revert CannotSendToSameChain();
(bytes memory message, bytes32 messageRoot) =
_getMessageAndRoot(destinationChainId, destinationAddress, data);
messages[nonce] = messageRoot;
emit SentMessage(nonce++, messageRoot, message);
return messageRoot;
}
function sendViaStorage(
uint32 destinationChainId,
address destinationAddress,
bytes calldata data
) external isSendingEnabled returns (bytes32) {
if (destinationChainId == block.chainid) revert CannotSendToSameChain();
(bytes memory message, bytes32 messageRoot) =
_getMessageAndRoot(destinationChainId, Bytes32.fromAddress(destinationAddress), data);
messages[nonce] = messageRoot;
emit SentMessage(nonce++, messageRoot, message);
return messageRoot;
}
/// @notice Gets the message and message root from the user-provided arguments to `send`
/// @param destinationChainId The chain id that specifies the destination chain.
/// @param destinationAddress The contract address that will be called on the destination chain.
/// @param data The calldata used when calling the contract on the destination chain.
/// @return messageBytes The message encoded as bytes, used in SentMessage event.
/// @return messageRoot The hash of messageBytes, used as a unique identifier for a message.
function _getMessageAndRoot(
uint32 destinationChainId,
bytes32 destinationAddress,
bytes calldata data
) internal view returns (bytes memory messageBytes, bytes32 messageRoot) {
messageBytes = MessageEncoding.encode(
version,
nonce,
uint32(block.chainid),
msg.sender,
destinationChainId,
destinationAddress,
data
);
messageRoot = keccak256(messageBytes);
}
}
pragma solidity 0.8.16;
import {RLPReader} from "@optimism-bedrock/rlp/RLPReader.sol";
import {RLPWriter} from "@optimism-bedrock/rlp/RLPWriter.sol";
import {MerkleTrie} from "@optimism-bedrock/trie/MerkleTrie.sol";
library StorageProof {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
function getStorageValue(bytes32 slotHash, bytes32 storageRoot, bytes[] memory _stateProof)
internal
pure
returns (uint256)
{
bytes memory valueRlpBytes =
MerkleTrie.get(abi.encodePacked(slotHash), _stateProof, storageRoot);
require(valueRlpBytes.length > 0, "Storage value does not exist");
return valueRlpBytes.toRLPItem().readUint256();
}
function getStorageRoot(bytes[] memory proof, address contractAddress, bytes32 stateRoot)
internal
pure
returns (bytes32)
{
bytes32 addressHash = keccak256(abi.encodePacked(contractAddress));
bytes memory acctRlpBytes = MerkleTrie.get(abi.encodePacked(addressHash), proof, stateRoot);
require(acctRlpBytes.length > 0, "Account does not exist");
RLPReader.RLPItem[] memory acctFields = acctRlpBytes.toRLPItem().readList();
require(acctFields.length == 4);
return bytes32(acctFields[2].readUint256());
}
}
library EventProof {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
function getEventTopic(
bytes[] memory proof,
bytes32 receiptRoot,
bytes memory key,
uint256 logIndex,
address claimedEmitter,
bytes32 eventSignature,
uint256 topicIndex
) internal pure returns (bytes32) {
bytes memory value = MerkleTrie.get(key, proof, receiptRoot);
bytes1 txTypeOrFirstByte = value[0];
// Currently, there are three possible transaction types on Ethereum. Receipts either come
// in the form "TransactionType | ReceiptPayload" or "ReceiptPayload". The currently
// supported set of transaction types are 0x01 and 0x02. In this case, we must truncate
// the first byte to access the payload. To detect the other case, we can use the fact
// that the first byte of a RLP-encoded list will always be greater than 0xc0.
// Reference 1: https://eips.ethereum.org/EIPS/eip-2718
// Reference 2: https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp
uint256 offset;
if (txTypeOrFirstByte == 0x01 || txTypeOrFirstByte == 0x02) {
offset = 1;
} else if (txTypeOrFirstByte >= 0xc0) {
offset = 0;
} else {
revert("Unsupported transaction type");
}
// Truncate the first byte if eneded and get the RLP decoding of the receipt.
uint256 ptr;
assembly {
ptr := add(value, 32)
}
RLPReader.RLPItem memory valueAsItem = RLPReader.RLPItem({
length: value.length - offset,
ptr: RLPReader.MemoryPointer.wrap(ptr + offset)
});
// The length of the receipt must be at least four, as the fourth entry contains events
RLPReader.RLPItem[] memory valueAsList = valueAsItem.readList();
require(valueAsList.length == 4, "Invalid receipt length");
// Read the logs from the receipts and check that it is not ill-formed
RLPReader.RLPItem[] memory logs = valueAsList[3].readList();
require(logIndex < logs.length, "Log index out of bounds");
RLPReader.RLPItem[] memory relevantLog = logs[logIndex].readList();
require(relevantLog.length == 3, "Log has incorrect number of fields");
// Validate that the correct contract emitted the event
address contractAddress = relevantLog[0].readAddress();
require(contractAddress == claimedEmitter, "Event was not emitted by claimedEmitter");
RLPReader.RLPItem[] memory topics = relevantLog[1].readList();
// Validate that the correct event was emitted by checking the event signature
require(
bytes32(topics[0].readUint256()) == eventSignature,
"Event signature does not match eventSignature"
);
return topics[topicIndex].readBytes32();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
pragma solidity 0.8.16;
import {ReentrancyGuardUpgradeable} from
"@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol";
import {SSZ} from "src/libraries/SimpleSerialize.sol";
import {StorageProof, EventProof} from "src/libraries/StateProofHelper.sol";
import {Address} from "src/libraries/Typecast.sol";
import {MessageEncoding} from "src/libraries/MessageEncoding.sol";
import {TelepathyStorage} from "src/amb/TelepathyStorage.sol";
import {
ITelepathyHandler,
ITelepathyReceiver,
Message,
MessageStatus
} from "src/amb/interfaces/ITelepathy.sol";
/// @title Target Arbitrary Message Bridge
/// @author Succinct Labs
/// @notice Executes messages sent from the source chain on the destination chain.
contract TargetAMB is TelepathyStorage, ReentrancyGuardUpgradeable, ITelepathyReceiver {
/// @notice The minimum delay for using any information from the light client.
uint256 public constant MIN_LIGHT_CLIENT_DELAY = 2 minutes;
/// @notice The ITelepathyBroadcaster SentMessage event signature used in `executeMessageFromLog`.
bytes32 internal constant SENT_MESSAGE_EVENT_SIG =
keccak256("SentMessage(uint64,bytes32,bytes)");
/// @notice The topic index of the message root in the SourceAMB SentMessage event.
/// @dev Because topic[0] is the hash of the event signature (`SENT_MESSAGE_EVENT_SIG` above),
/// the topic index of msgHash is 2.
uint256 internal constant MSG_HASH_TOPIC_IDX = 2;
/// @notice The index of the `messages` mapping in TelepathyStorage.sol.
/// @dev We need this when calling `executeMessage` via storage proofs, as it is used in
/// getting the slot key.
uint256 internal constant MESSAGES_MAPPING_STORAGE_INDEX = 1;
/// @notice Gets the length of the sourceChainIds array.
/// @return The length of the sourceChainIds array.
function sourceChainIdsLength() external view returns (uint256) {
return sourceChainIds.length;
}
/// @notice Executes a message given a storage proof.
/// @param slot Specifies which execution state root should be read from the light client.
/// @param messageBytes The message we want to execute provided as bytes.
/// @param accountProof Used to prove the broadcaster's state root.
/// @param storageProof Used to prove the existence of the message root inside the broadcaster.
function executeMessage(
uint64 slot,
bytes calldata messageBytes,
bytes[] calldata accountProof,
bytes[] calldata storageProof
) external nonReentrant {
(Message memory message, bytes32 messageRoot) = _checkPreconditions(messageBytes);
requireLightClientConsistency(message.sourceChainId);
requireNotFrozen(message.sourceChainId);
{
requireLightClientDelay(slot, message.sourceChainId);
bytes32 storageRoot;
bytes32 cacheKey = keccak256(
abi.encodePacked(message.sourceChainId, slot, broadcasters[message.sourceChainId])
);
// If the cache is empty for the cacheKey, then we get the
// storageRoot using the provided accountProof.
if (storageRootCache[cacheKey] == 0) {
bytes32 executionStateRoot =
lightClients[message.sourceChainId].executionStateRoots(slot);
require(executionStateRoot != 0, "Execution State Root is not set");
storageRoot = StorageProof.getStorageRoot(
accountProof, broadcasters[message.sourceChainId], executionStateRoot
);
storageRootCache[cacheKey] = storageRoot;
} else {
storageRoot = storageRootCache[cacheKey];
}
bytes32 slotKey = keccak256(
abi.encode(keccak256(abi.encode(message.nonce, MESSAGES_MAPPING_STORAGE_INDEX)))
);
uint256 slotValue = StorageProof.getStorageValue(slotKey, storageRoot, storageProof);
if (bytes32(slotValue) != messageRoot) {
revert("Invalid message hash.");
}
}
_executeMessage(message, messageRoot, messageBytes);
}
/// @notice Executes a message given an event proof.
/// @param srcSlotTxSlotPack The slot where we want to read the header from and the slot where
/// the tx executed, packed as two uint64s.
/// @param messageBytes The message we want to execute provided as bytes.
/// @param receiptsRootProof A merkle proof proving the receiptsRoot in the block header.
/// @param receiptsRoot The receipts root which contains our "SentMessage" event.
/// @param txIndexRLPEncoded The index of our transaction inside the block RLP encoded.
/// @param logIndex The index of the event in our transaction.
function executeMessageFromLog(
bytes calldata srcSlotTxSlotPack,
bytes calldata messageBytes,
bytes32[] calldata receiptsRootProof,
bytes32 receiptsRoot,
bytes[] calldata receiptProof,
bytes memory txIndexRLPEncoded,
uint256 logIndex
) external nonReentrant {
// Verify receiptsRoot against header from light client
(Message memory message, bytes32 messageRoot) = _checkPreconditions(messageBytes);
requireLightClientConsistency(message.sourceChainId);
requireNotFrozen(message.sourceChainId);
{
(uint64 srcSlot, uint64 txSlot) = abi.decode(srcSlotTxSlotPack, (uint64, uint64));
requireLightClientDelay(srcSlot, message.sourceChainId);
bytes32 headerRoot = lightClients[message.sourceChainId].headers(srcSlot);
require(headerRoot != bytes32(0), "HeaderRoot is missing");
bool isValid = SSZ.verifyReceiptsRoot(
receiptsRoot, receiptsRootProof, headerRoot, srcSlot, txSlot, message.sourceChainId
);
require(isValid, "Invalid receipts root proof");
}
{
// TODO maybe we can save calldata by passing in the txIndex as a uint and rlp encode it
// to derive txIndexRLPEncoded instead of passing in `bytes memory txIndexRLPEncoded`
bytes32 receiptMessageRoot = bytes32(
EventProof.getEventTopic(
receiptProof,
receiptsRoot,
txIndexRLPEncoded,
logIndex,
broadcasters[message.sourceChainId],
SENT_MESSAGE_EVENT_SIG,
MSG_HASH_TOPIC_IDX
)
);
require(receiptMessageRoot == messageRoot, "Invalid message hash.");
}
_executeMessage(message, messageRoot, messageBytes);
}
/// @notice Checks that the light client for a given chainId is consistent.
function requireLightClientConsistency(uint32 chainId) internal view {
require(address(lightClients[chainId]) != address(0), "Light client is not set.");
require(lightClients[chainId].consistent(), "Light client is inconsistent.");
}
/// @notice Checks that the chainId is not frozen.
function requireNotFrozen(uint32 chainId) internal view {
require(!frozen[chainId], "Contract is frozen.");
}
/// @notice Checks that the light client delay is adequate.
function requireLightClientDelay(uint64 slot, uint32 chainId) internal view {
require(address(lightClients[chainId]) != address(0), "Light client is not set.");
require(lightClients[chainId].timestamps(slot) != 0, "Timestamp is not set for slot.");
uint256 elapsedTime = block.timestamp - lightClients[chainId].timestamps(slot);
require(elapsedTime >= MIN_LIGHT_CLIENT_DELAY, "Must wait longer to use this slot.");
}
/// @notice Decodes the message from messageBytes and checks conditions before message execution
/// @param messageBytes The message we want to execute provided as bytes.
function _checkPreconditions(bytes calldata messageBytes)
internal
view
returns (Message memory, bytes32)
{
Message memory message = MessageEncoding.decode(messageBytes);
bytes32 messageRoot = keccak256(messageBytes);
if (messageStatus[messageRoot] != MessageStatus.NOT_EXECUTED) {
revert("Message already executed.");
} else if (message.destinationChainId != block.chainid) {
revert("Wrong chain.");
} else if (message.version != version) {
revert("Wrong version.");
} else if (
address(lightClients[message.sourceChainId]) == address(0)
|| broadcasters[message.sourceChainId] == address(0)
) {
revert("Light client or broadcaster for source chain is not set");
}
return (message, messageRoot);
}
/// @notice Executes a message and updates storage with status and emits an event.
/// @dev Assumes that the message is valid and has not been already executed.
/// @dev Assumes that message, messageRoot and messageBytes have already been validated.
/// @param message The message we want to execute.
/// @param messageRoot The message root of the message.
/// @param messageBytes The message we want to execute provided as bytes for use in the event.
function _executeMessage(Message memory message, bytes32 messageRoot, bytes memory messageBytes)
internal
{
bool status;
bytes memory data;
{
bytes memory receiveCall = abi.encodeWithSelector(
ITelepathyHandler.handleTelepathy.selector,
message.sourceChainId,
message.sourceAddress,
message.data
);
address destination = Address.fromBytes32(message.destinationAddress);
(status, data) = destination.call(receiveCall);
}
// Unfortunately, there are some edge cases where a call may have a successful status but
// not have actually called the handler. Thus, we enforce that the handler must return
// a magic constant that we can check here. To avoid stack underflow / decoding errors, we
// only decode the returned bytes if one EVM word was returned by the call.
bool implementsHandler = false;
if (data.length == 32) {
(bytes4 magic) = abi.decode(data, (bytes4));
implementsHandler = magic == ITelepathyHandler.handleTelepathy.selector;
}
if (status && implementsHandler) {
messageStatus[messageRoot] = MessageStatus.EXECUTION_SUCCEEDED;
} else {
messageStatus[messageRoot] = MessageStatus.EXECUTION_FAILED;
}
emit ExecutedMessage(
message.sourceChainId, message.nonce, messageRoot, messageBytes, status
);
}
}
pragma solidity 0.8.16;
import {AccessControlUpgradeable} from
"@openzeppelin-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import {ILightClient} from "src/lightclient/interfaces/ILightClient.sol";
import {TelepathyStorage} from "src/amb/TelepathyStorage.sol";
contract TelepathyAccess is TelepathyStorage, AccessControlUpgradeable {
/// @notice Emitted when the sendingEnabled flag is changed.
event SendingEnabled(bool enabled);
/// @notice Emitted when freezeAll is called.
event FreezeAll();
/// @notice Emitted when freeze is called.
event Freeze(uint32 indexed chainId);
/// @notice Emitted when unfreezeAll is called.
event UnfreezeAll();
/// @notice Emitted when unfreeze is called.
event Unfreeze(uint32 indexed chainId);
/// @notice Emitted when setLightClientAndBroadcaster is called.
event SetLightClientAndBroadcaster(
uint32 indexed chainId, address lightClient, address broadcaster
);
/// @notice Emitted when a new source chain is added.
event SourceChainAdded(uint32 indexed chainId);
/// @notice A random constant used to identify addresses with the permission of a 'guardian'.
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice A random constant used to identify addresses with the permission of a 'timelock'.
bytes32 public constant TIMELOCK_ROLE = keccak256("TIMELOCK_ROLE");
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"TelepathyRouter: only admin can call this function"
);
_;
}
modifier onlyTimelock() {
require(
hasRole(TIMELOCK_ROLE, msg.sender),
"TelepathyRouter: only timelock can call this function"
);
_;
}
modifier onlyGuardian() {
require(
hasRole(GUARDIAN_ROLE, msg.sender),
"TelepathyRouter: only guardian can call this function"
);
_;
}
/// @notice Allows the owner to control whether sending is enabled or not.
function setSendingEnabled(bool enabled) external onlyGuardian {
sendingEnabled = enabled;
emit SendingEnabled(enabled);
}
/// @notice Freezes messages from all chains.
/// @dev This is a safety mechanism to prevent the contract from being used after a security
/// vulnerability is detected.
function freezeAll() external onlyGuardian {
for (uint32 i = 0; i < sourceChainIds.length; i++) {
frozen[sourceChainIds[i]] = true;
}
emit FreezeAll();
}
/// @notice Freezes messages from the specified chain.
/// @dev This is a safety mechanism to prevent the contract from being used after a security
/// vulnerability is detected.
function freeze(uint32 chainId) external onlyGuardian {
frozen[chainId] = true;
emit Freeze(chainId);
}
/// @notice Unfreezes messages from the specified chain.
/// @dev This is a safety mechanism to continue usage of the contract after a security
/// vulnerability is patched.
function unfreeze(uint32 chainId) external onlyGuardian {
frozen[chainId] = false;
emit Unfreeze(chainId);
}
/// @notice Unfreezes messages from all chains.
/// @dev This is a safety mechanism to continue usage of the contract after a security
/// vulnerability is patched.
function unfreezeAll() external onlyGuardian {
for (uint32 i = 0; i < sourceChainIds.length; i++) {
frozen[sourceChainIds[i]] = false;
}
emit UnfreezeAll();
}
/// @notice Sets the light client contract and broadcaster for a given chainId.
/// @dev This is controlled by the timelock as it is a potentially dangerous method
/// since both the light client and broadcaster address are critical in verifying
/// that only valid sent messages are executed.
function setLightClientAndBroadcaster(uint32 chainId, address lightclient, address broadcaster)
external
onlyTimelock
{
bool chainIdExists = false;
for (uint256 i = 0; i < sourceChainIds.length; i++) {
if (sourceChainIds[i] == chainId) {
chainIdExists = true;
break;
}
}
if (!chainIdExists) {
sourceChainIds.push(chainId);
emit SourceChainAdded(chainId);
}
lightClients[chainId] = ILightClient(lightclient);
broadcasters[chainId] = broadcaster;
emit SetLightClientAndBroadcaster(chainId, lightclient, broadcaster);
}
}
pragma solidity ^0.8.16;
import {TelepathyPublisher} from "src/pubsub/TelepathyPublisher.sol";
import {TelepathySubscriber} from "src/pubsub/TelepathySubscriber.sol";
import {PubSubStorage} from "src/pubsub/PubSubStorage.sol";
import {TelepathyRouter} from "src/amb/TelepathyRouter.sol";
import {ILightClient} from "src/lightclient/interfaces/ILightClient.sol";
/// @title TelepathyPubSub
/// @author Succinct Labs
/// @notice This allows an on-chain Publisher-Suscriber model to be used for events. Contracts can subscribe to
/// events emitted from a source contract, and it will be relayed these events through the publisher. Before
/// the events are relayed, they are verified using the Telepathy Light Client for proof of consensus on the
/// source chain.
contract TelepathyPubSub is TelepathyPublisher, TelepathySubscriber {
constructor(address _guardian, address _timelock, address _lightClient) {
guardian = _guardian;
timelock = _timelock;
lightClient = ILightClient(_lightClient);
paused = false;
}
modifier onlyGuardian() {
require(msg.sender == guardian, "Only guardian");
_;
}
modifier onlyTimelock() {
require(msg.sender == timelock, "Only timelock");
_;
}
function togglePause() external onlyGuardian {
paused = !paused;
}
function setLightClient(address _lightClient) external onlyTimelock {
lightClient = ILightClient(_lightClient);
}
}
pragma solidity ^0.8.16;
import {Subscription, IPublisher} from "src/pubsub/interfaces/IPubSub.sol";
import {EventProof} from "src/pubsub/EventProof.sol";
import {ISubscriptionReceiver} from "src/pubsub/interfaces/ISubscriptionReceiver.sol";
import {TelepathyRouter} from "src/amb/TelepathyRouter.sol";
import {SSZ} from "src/libraries/SimpleSerialize.sol";
import {Address} from "src/libraries/Typecast.sol";
import {PubSubStorage} from "src/pubsub/PubSubStorage.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {PublishStatus} from "src/pubsub/interfaces/IPubSub.sol";
/// @title TelepathyPublisher
/// @author Succinct Labs
/// @notice A contract that can publish events to a ISubscriptionReceiver contract.
contract TelepathyPublisher is IPublisher, PubSubStorage, ReentrancyGuard {
error CallFailed();
error InvalidSelector();
/// @notice Publishes an event emit to a callback Subscriber, given an event proof.
/// @param srcSlotTxSlotPack The slot where we want to read the header from and the slot where
/// the tx executed, packed as two uint64s.
/// @param receiptsRootProof A merkle proof proving the receiptsRoot in the block header.
/// @param receiptsRoot The receipts root which contains the event.
/// @param txIndexRLPEncoded The index of our transaction inside the block RLP encoded.
/// @param logIndex The index of the event in our transaction.
/// @param subscription The subscription data (sourceChainId, sourceAddress, callbackAddress, eventSig).
/// @dev This function should be called for every subscriber that is subscribed to the event.
function publishEvent(
bytes calldata srcSlotTxSlotPack,
bytes32[] calldata receiptsRootProof,
bytes32 receiptsRoot,
bytes[] calldata receiptProof,
bytes memory txIndexRLPEncoded,
uint256 logIndex,
Subscription calldata subscription
) external nonReentrant {
require(!paused, "Publishing events is paused");
requireLightClientConsistency(subscription.sourceChainId);
(uint64 srcSlot, uint64 txSlot) = abi.decode(srcSlotTxSlotPack, (uint64, uint64));
// Ensure the event emit may only be published to a subscriber once
bytes32 subscriptionId = keccak256(abi.encode(subscription));
bytes32 publishKey =
keccak256(abi.encode(txSlot, txIndexRLPEncoded, logIndex, subscriptionId));
require(
eventsPublished[publishKey] == PublishStatus.NOT_EXECUTED, "Event already published"
);
bytes32 headerRoot = lightClient.headers(srcSlot);
require(headerRoot != bytes32(0), "HeaderRoot is missing");
bool isValid = SSZ.verifyReceiptsRoot(
receiptsRoot, receiptsRootProof, headerRoot, srcSlot, txSlot, subscription.sourceChainId
);
require(isValid, "Invalid receipts root proof");
(bytes32[] memory eventTopics, bytes memory eventData) = EventProof.parseEvent(
receiptProof,
receiptsRoot,
txIndexRLPEncoded,
logIndex,
subscription.sourceAddress,
subscription.eventSig
);
_publish(subscriptionId, subscription, txSlot, publishKey, eventTopics, eventData);
}
/// @notice Checks that the light client for a given chainId is consistent.
function requireLightClientConsistency(uint32 chainId) internal view {
require(address(lightClient) != address(0), "Light client is not set.");
require(lightClient.consistent(), "Light client is inconsistent.");
}
/// @notice Executes the callback function on the subscriber, and marks the event publish as successful or failed.
function _publish(
bytes32 _subscriptionId,
Subscription calldata _subscription,
uint64 _txSlot,
bytes32 _publishKey,
bytes32[] memory _eventTopics,
bytes memory _eventData
) internal {
bool success;
bytes memory data;
{
bytes memory receiveCall = abi.encodeWithSelector(
ISubscriptionReceiver.handlePublish.selector,
_subscriptionId,
_subscription.sourceChainId,
_subscription.sourceAddress,
_txSlot,
_publishKey,
_eventTopics,
_eventData
);
(success, data) = _subscription.callbackAddress.call(receiveCall);
}
bool implementsHandler = false;
if (data.length == 32) {
(bytes4 magic) = abi.decode(data, (bytes4));
implementsHandler = magic == ISubscriptionReceiver.handlePublish.selector;
}
// Resolves issue regarding EIP-150 (where the child call can fail due to "out of gas" error
// but the parent call will have 1/64 of original gas to finish execution) or, for example,
// because of possible NonReentrant logic in callback contract.
//
// This leads to the possibility to maliciously mark the event as published with
// `PublishStatus.EXECUTION_FAILED` status, while with "fair" execution it should succeed.
//
// To fix the issue, we simply revert the entire tx if the callback fails. This allows for
// retries.
if (!success) {
revert CallFailed();
} else if (!implementsHandler) {
revert InvalidSelector();
}
eventsPublished[_publishKey] = PublishStatus.EXECUTION_SUCCEEDED;
emit Publish(
_subscriptionId,
_subscription.sourceChainId,
_subscription.sourceAddress,
_subscription.callbackAddress,
success
);
}
}
pragma solidity 0.8.16;
import {UUPSUpgradeable} from "@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import {ILightClient} from "src/lightclient/interfaces/ILightClient.sol";
import {TelepathyStorage} from "src/amb/TelepathyStorage.sol";
import {
ITelepathyReceiver,
Message,
MessageStatus,
ITelepathyHandler,
ITelepathyRouter
} from "src/amb/interfaces/ITelepathy.sol";
import {TargetAMB} from "src/amb/TargetAMB.sol";
import {SourceAMB} from "src/amb/SourceAMB.sol";
import {TelepathyAccess} from "src/amb/TelepathyAccess.sol";
/// @title Telepathy Router
/// @author Succinct Labs
/// @notice Send and receive arbitrary messages from other chains.
contract TelepathyRouter is SourceAMB, TargetAMB, TelepathyAccess, UUPSUpgradeable {
/// @notice Returns current contract version.
uint8 public constant VERSION = 1;
/// @notice Prevents the implementation contract from being initialized outside of the upgradeable proxy.
constructor() {
_disableInitializers();
}
/// @notice Initializes the contract and the parent contracts once.
function initialize(
uint32[] memory _sourceChainIds,
address[] memory _lightClients,
address[] memory _broadcasters,
address _timelock,
address _guardian,
bool _sendingEnabled
) external initializer {
__ReentrancyGuard_init();
__AccessControl_init();
_grantRole(GUARDIAN_ROLE, _guardian);
_grantRole(TIMELOCK_ROLE, _timelock);
_grantRole(DEFAULT_ADMIN_ROLE, _timelock);
__UUPSUpgradeable_init();
require(_sourceChainIds.length == _lightClients.length);
require(_sourceChainIds.length == _broadcasters.length);
sourceChainIds = _sourceChainIds;
for (uint32 i = 0; i < sourceChainIds.length; i++) {
lightClients[sourceChainIds[i]] = ILightClient(_lightClients[i]);
broadcasters[sourceChainIds[i]] = _broadcasters[i];
}
sendingEnabled = _sendingEnabled;
version = VERSION;
}
/// @notice Authorizes an upgrade for the implementation contract.
function _authorizeUpgrade(address newImplementation) internal override onlyTimelock {}
}
pragma solidity 0.8.16;
import {ILightClient} from "src/lightclient/interfaces/ILightClient.sol";
import {MessageStatus} from "src/amb/interfaces/ITelepathy.sol";
contract TelepathyStorage {
/*//////////////////////////////////////////////////////////////
BROADCASTER STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Whether sending is enabled or not.
bool public sendingEnabled;
/// @notice Mapping between a nonce and a message root.
mapping(uint64 => bytes32) public messages;
/// @notice Keeps track of the next nonce to be used.
uint64 public nonce;
/*//////////////////////////////////////////////////////////////
RECEIVER STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice All sourceChainIds.
uint32[] public sourceChainIds;
/// @notice Mapping between source chainId and the corresponding light client.
mapping(uint32 => ILightClient) public lightClients;
/// @notice Mapping between source chainId and the address of the Telepathy broadcaster on that chain.
mapping(uint32 => address) public broadcasters;
/// @notice Mapping between a source chainId and whether it's frozen.
mapping(uint32 => bool) public frozen;
/// @notice Mapping between a message root and its status.
mapping(bytes32 => MessageStatus) public messageStatus;
/*//////////////////////////////////////////////////////////////
SHARED STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Returns current contract version.
uint8 public version;
/*//////////////////////////////////////////////////////////////
RECEIVER STORAGE V2
//////////////////////////////////////////////////////////////*/
/// @notice Storage root cache.
mapping(bytes32 => bytes32) public storageRootCache;
/// @dev This empty reserved space is put in place to allow future versions to add new variables
/// without shifting down storage in the inheritance chain.
/// See: https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#storage-gaps
uint256[40] private __gap;
}
pragma solidity ^0.8.16;
import {Subscription, SubscriptionStatus, ISubscriber} from "src/pubsub/interfaces/IPubSub.sol";
import {PubSubStorage} from "src/pubsub/PubSubStorage.sol";
/// @title TelepathySubscriber
/// @author Succinct Labs
/// @notice This allows contracts to subscribe to cross-chain events from a source contract.
contract TelepathySubscriber is ISubscriber, PubSubStorage {
error SubscriptionAlreadyActive(bytes32 subscriptionId);
error SubscriptionNotActive(bytes32 subscriptionId);
error InvalidSlotRange(uint64 startSlot, uint64 endSlot);
/// @dev The block ranges use as a signal to off-chain, and are NOT enforced by the publisher.
/// If events should only a certain range should be valid, the callbackAddress should do their
/// own validation when handling the publish.
function subscribe(
uint32 _sourceChainId,
address _sourceAddress,
address _callbackAddress,
bytes32 _eventSig,
uint64 _startSlot,
uint64 _endSlot
) external returns (bytes32) {
Subscription memory subscription =
Subscription(_sourceChainId, _sourceAddress, _callbackAddress, _eventSig);
bytes32 subscriptionId = keccak256(abi.encode(subscription));
if (subscriptions[subscriptionId] == SubscriptionStatus.SUBSCRIBED) {
revert SubscriptionAlreadyActive(subscriptionId);
}
subscriptions[subscriptionId] = SubscriptionStatus.SUBSCRIBED;
// Either both block's slots are 0, or endSlot is must greater than startSlot.
if (_endSlot < _startSlot) {
revert InvalidSlotRange(_startSlot, _endSlot);
}
emit Subscribe(subscriptionId, _startSlot, _endSlot, subscription);
return subscriptionId;
}
/// @dev Only the original callbackAddress contract will be able to unsubscribe.
function unsubscribe(uint32 _sourceChainId, address _sourceAddress, bytes32 _eventSig)
external
returns (bytes32)
{
Subscription memory subscription =
Subscription(_sourceChainId, _sourceAddress, msg.sender, _eventSig);
bytes32 subscriptionId = keccak256(abi.encode(subscription));
if (subscriptions[subscriptionId] == SubscriptionStatus.UNSUBSCIBED) {
revert SubscriptionNotActive(subscriptionId);
}
subscriptions[subscriptionId] = SubscriptionStatus.UNSUBSCIBED;
emit Unsubscribe(subscriptionId, subscription);
return subscriptionId;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.16;
library Address {
function fromBytes32(bytes32 buffer) internal pure returns (address) {
return address(uint160(uint256(buffer)));
}
}
library Bytes32 {
function fromAddress(address addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(addr)));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
{
"compilationTarget": {
"src/pubsub/TelepathyPubSub.sol": "TelepathyPubSub"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":@openzeppelin/=lib/openzeppelin-contracts/",
":@optimism-bedrock/=lib/optimism-bedrock-contracts/",
":@uniswap/=lib/",
":Solidity-RLP/=lib/Solidity-RLP/contracts/",
":curve-merkle-oracle/=lib/curve-merkle-oracle/contracts/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":optimism-bedrock-contracts/=lib/optimism-bedrock-contracts/",
":v3-core/=lib/v3-core/"
]
}
[{"inputs":[{"internalType":"address","name":"_guardian","type":"address"},{"internalType":"address","name":"_timelock","type":"address"},{"internalType":"address","name":"_lightClient","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CallFailed","type":"error"},{"inputs":[],"name":"InvalidSelector","type":"error"},{"inputs":[{"internalType":"uint64","name":"startSlot","type":"uint64"},{"internalType":"uint64","name":"endSlot","type":"uint64"}],"name":"InvalidSlotRange","type":"error"},{"inputs":[{"internalType":"bytes32","name":"subscriptionId","type":"bytes32"}],"name":"SubscriptionAlreadyActive","type":"error"},{"inputs":[{"internalType":"bytes32","name":"subscriptionId","type":"bytes32"}],"name":"SubscriptionNotActive","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subscriptionId","type":"bytes32"},{"indexed":true,"internalType":"uint32","name":"sourceChainId","type":"uint32"},{"indexed":true,"internalType":"address","name":"sourceAddress","type":"address"},{"indexed":false,"internalType":"address","name":"callbackAddress","type":"address"},{"indexed":false,"internalType":"bool","name":"success","type":"bool"}],"name":"Publish","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subscriptionId","type":"bytes32"},{"indexed":true,"internalType":"uint64","name":"startSlot","type":"uint64"},{"indexed":true,"internalType":"uint64","name":"endSlot","type":"uint64"},{"components":[{"internalType":"uint32","name":"sourceChainId","type":"uint32"},{"internalType":"address","name":"sourceAddress","type":"address"},{"internalType":"address","name":"callbackAddress","type":"address"},{"internalType":"bytes32","name":"eventSig","type":"bytes32"}],"indexed":false,"internalType":"struct Subscription","name":"subscription","type":"tuple"}],"name":"Subscribe","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"subscriptionId","type":"bytes32"},{"components":[{"internalType":"uint32","name":"sourceChainId","type":"uint32"},{"internalType":"address","name":"sourceAddress","type":"address"},{"internalType":"address","name":"callbackAddress","type":"address"},{"internalType":"bytes32","name":"eventSig","type":"bytes32"}],"indexed":false,"internalType":"struct Subscription","name":"subscription","type":"tuple"}],"name":"Unsubscribe","type":"event"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"eventsPublished","outputs":[{"internalType":"enum PublishStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"guardian","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lightClient","outputs":[{"internalType":"contract ILightClient","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"srcSlotTxSlotPack","type":"bytes"},{"internalType":"bytes32[]","name":"receiptsRootProof","type":"bytes32[]"},{"internalType":"bytes32","name":"receiptsRoot","type":"bytes32"},{"internalType":"bytes[]","name":"receiptProof","type":"bytes[]"},{"internalType":"bytes","name":"txIndexRLPEncoded","type":"bytes"},{"internalType":"uint256","name":"logIndex","type":"uint256"},{"components":[{"internalType":"uint32","name":"sourceChainId","type":"uint32"},{"internalType":"address","name":"sourceAddress","type":"address"},{"internalType":"address","name":"callbackAddress","type":"address"},{"internalType":"bytes32","name":"eventSig","type":"bytes32"}],"internalType":"struct Subscription","name":"subscription","type":"tuple"}],"name":"publishEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_lightClient","type":"address"}],"name":"setLightClient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_sourceChainId","type":"uint32"},{"internalType":"address","name":"_sourceAddress","type":"address"},{"internalType":"address","name":"_callbackAddress","type":"address"},{"internalType":"bytes32","name":"_eventSig","type":"bytes32"},{"internalType":"uint64","name":"_startSlot","type":"uint64"},{"internalType":"uint64","name":"_endSlot","type":"uint64"}],"name":"subscribe","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"subscriptions","outputs":[{"internalType":"enum SubscriptionStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"timelock","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"togglePause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_sourceChainId","type":"uint32"},{"internalType":"address","name":"_sourceAddress","type":"address"},{"internalType":"bytes32","name":"_eventSig","type":"bytes32"}],"name":"unsubscribe","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"}]