Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x277a7d31...170CE37bF The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
BlockBuilderPolicy
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 44444444 runs
Other Settings:
prague EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {FlashtestationRegistry} from "./FlashtestationRegistry.sol";
import {IFlashtestationRegistry} from "./interfaces/IFlashtestationRegistry.sol";
import {IBlockBuilderPolicy, WorkloadId} from "./interfaces/IBlockBuilderPolicy.sol";
/**
* @notice Cached workload information for gas optimization
* @dev Stores computed workloadId and associated quoteHash to avoid expensive recomputation
*/
struct CachedWorkload {
/// @notice The computed workload identifier
WorkloadId workloadId;
/// @notice The keccak256 hash of the raw quote used to compute this workloadId
bytes32 quoteHash;
}
/**
* @title BlockBuilderPolicy
* @notice A reference implementation of a policy contract for the FlashtestationRegistry
* @notice A Policy is a collection of related WorkloadIds. A Policy exists to specify which
* WorkloadIds are valid for a particular purpose, in this case for remote block building. It also
* exists to handle the problem that TEE workloads will need to change multiple times a year, either because
* of Intel DCAP Endorsement updates or updates to the TEE configuration (and thus its WorkloadId). Without
* Policies, consumer contracts that makes use of Flashtestations would need to be updated every time a TEE workload
* changes, which is a costly and error-prone process. Instead, consumer contracts need only check if a TEE address
* is allowed under any workload in a Policy, and the FlashtestationRegistry will handle the rest
*/
contract BlockBuilderPolicy is
Initializable,
UUPSUpgradeable,
OwnableUpgradeable,
EIP712Upgradeable,
IBlockBuilderPolicy
{
using ECDSA for bytes32;
// ============ EIP-712 Constants ============
/// @inheritdoc IBlockBuilderPolicy
bytes32 public constant VERIFY_BLOCK_BUILDER_PROOF_TYPEHASH =
keccak256("VerifyBlockBuilderProof(uint8 version,bytes32 blockContentHash,uint256 nonce)");
// ============ TDX workload constants ============
/// @dev See section 11.5.3 in TDX Module v1.5 Base Architecture Specification https://www.intel.com/content/www/us/en/content-details/733575/intel-tdx-module-v1-5-base-architecture-specification.html
/// @notice Enabled FPU (always enabled)
bytes8 constant TD_XFAM_FPU = 0x0000000000000001;
/// @notice Enabled SSE (always enabled)
bytes8 constant TD_XFAM_SSE = 0x0000000000000002;
/// @dev See section 3.4.1 in TDX Module ABI specification https://cdrdv2.intel.com/v1/dl/getContent/733579
/// @notice Allows disabling of EPT violation conversion to #VE on access of PENDING pages. Needed for Linux
bytes8 constant TD_TDATTRS_VE_DISABLED = 0x0000000010000000;
/// @notice Enabled Supervisor Protection Keys (PKS)
bytes8 constant TD_TDATTRS_PKS = 0x0000000040000000;
/// @notice Enabled Key Locker (KL)
bytes8 constant TD_TDATTRS_KL = 0x0000000080000000;
// ============ Storage Variables ============
/// @notice Mapping from workloadId to its metadata (commit hash and source locators)
/// @dev This is only updateable by governance (i.e. the owner) of the Policy contract
/// Adding and removing a workload is O(1).
/// This means the critical `_cachedIsAllowedPolicy` function is O(1) since we can directly check if a workloadId exists
/// in the mapping
mapping(bytes32 workloadId => WorkloadMetadata) private approvedWorkloads;
/// @inheritdoc IBlockBuilderPolicy
address public registry;
/// @inheritdoc IBlockBuilderPolicy
mapping(address teeAddress => uint256 permitNonce) public nonces;
/// @notice Cache of computed workloadIds to avoid expensive recomputation
/// @dev Maps teeAddress to cached workload information for gas optimization
mapping(address teeAddress => CachedWorkload) private cachedWorkloads;
/// @dev Storage gap to allow for future storage variable additions in upgrades
/// @dev This reserves 46 storage slots (out of 50 total - 4 used for approvedWorkloads, registry, nonces, and cachedWorkloads)
uint256[46] __gap;
/// @inheritdoc IBlockBuilderPolicy
function initialize(address _initialOwner, address _registry) external override initializer {
__Ownable_init(_initialOwner);
__UUPSUpgradeable_init();
__EIP712_init("BlockBuilderPolicy", "1");
require(_registry != address(0), InvalidRegistry());
registry = _registry;
emit RegistrySet(_registry);
}
/// @notice Restricts upgrades to owner only
/// @param newImplementation The address of the new implementation contract
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
/// @inheritdoc IBlockBuilderPolicy
function verifyBlockBuilderProof(uint8 version, bytes32 blockContentHash) external override {
_verifyBlockBuilderProof(msg.sender, version, blockContentHash);
}
/// @inheritdoc IBlockBuilderPolicy
function permitVerifyBlockBuilderProof(
uint8 version,
bytes32 blockContentHash,
uint256 nonce,
bytes calldata eip712Sig
) external override {
// Get the TEE address from the signature
bytes32 digest = getHashedTypeDataV4(computeStructHash(version, blockContentHash, nonce));
address teeAddress = digest.recover(eip712Sig);
// Verify the nonce
uint256 expectedNonce = nonces[teeAddress];
require(nonce == expectedNonce, InvalidNonce(expectedNonce, nonce));
// Increment the nonce
nonces[teeAddress]++;
// Verify the block builder proof
_verifyBlockBuilderProof(teeAddress, version, blockContentHash);
}
/// @notice Internal function to verify a block builder proof
/// @dev This function is internal because it is only used by the permitVerifyBlockBuilderProof function
/// and it is not needed to be called by other contracts
/// @param teeAddress The TEE-controlled address
/// @param version The version of the flashtestation's protocol
/// @param blockContentHash The hash of the block content
function _verifyBlockBuilderProof(address teeAddress, uint8 version, bytes32 blockContentHash) internal {
// Check if the caller is an authorized TEE block builder for our Policy and update cache
(bool allowed, WorkloadId workloadId) = _cachedIsAllowedPolicy(teeAddress);
require(allowed, UnauthorizedBlockBuilder(teeAddress));
// At this point, we know:
// 1. The caller is a registered TEE-controlled address from an attested TEE
// 2. The TEE is running an approved block builder workload (via policy)
// Note: Due to EVM limitations (no retrospection), we cannot validate the blockContentHash
// onchain. We rely on the TEE workload to correctly compute this hash according to the
// specified version of the calculation method.
bytes32 workloadKey = WorkloadId.unwrap(workloadId);
string memory commitHash = approvedWorkloads[workloadKey].commitHash;
emit BlockBuilderProofVerified(teeAddress, workloadKey, version, blockContentHash, commitHash);
}
/// @inheritdoc IBlockBuilderPolicy
function isAllowedPolicy(address teeAddress) public view override returns (bool allowed, WorkloadId) {
// Get full registration data and compute workload ID
(, IFlashtestationRegistry.RegisteredTEE memory registration) =
FlashtestationRegistry(registry).getRegistration(teeAddress);
// Invalid Registrations means the attestation used to register the TEE is no longer valid
// and so we cannot trust any input from the TEE
if (!registration.isValid) {
return (false, WorkloadId.wrap(0));
}
WorkloadId workloadId = workloadIdForTDRegistration(registration);
// Check if the workload exists in our approved workloads mapping
if (bytes(approvedWorkloads[WorkloadId.unwrap(workloadId)].commitHash).length > 0) {
return (true, workloadId);
}
return (false, WorkloadId.wrap(0));
}
/// @notice isAllowedPolicy but with caching to reduce gas costs
/// @dev This function is only used by the verifyBlockBuilderProof function, which needs to be as efficient as possible
/// because it is called onchain for every flashblock. The workloadId is cached to avoid expensive recomputation
/// @dev A careful reader will notice that this function does not delete stale cache entries. It overwrites them
/// if the underlying TEE registration is still valid. But for stale cache entries in every other scenario, the
/// cache entry persists indefinitely. This is because every other instance results in a return value of (false, 0)
/// to the caller (which is always the verifyBlockBuilderProof function) and it immediately reverts. This is an unfortunate
/// consequence of our need to make this function as gas-efficient as possible, otherwise we would try to cleanup
/// stale cache entries
/// @param teeAddress The TEE-controlled address
/// @return True if the TEE is using an approved workload in the policy
/// @return The workloadId of the TEE that is using an approved workload in the policy, or 0 if
/// the TEE is not using an approved workload in the policy
function _cachedIsAllowedPolicy(address teeAddress) private returns (bool, WorkloadId) {
// Get the current registration status (fast path)
(bool isValid, bytes32 quoteHash) = FlashtestationRegistry(registry).getRegistrationStatus(teeAddress);
if (!isValid) {
return (false, WorkloadId.wrap(0));
}
// Now, check if we have a cached workload for this TEE
CachedWorkload memory cached = cachedWorkloads[teeAddress];
// Check if we've already fetched and computed the workloadId for this TEE
bytes32 cachedWorkloadId = WorkloadId.unwrap(cached.workloadId);
if (cachedWorkloadId != 0 && cached.quoteHash == quoteHash) {
// Cache hit - verify the workload is still a part of this policy's approved workloads
if (bytes(approvedWorkloads[cachedWorkloadId].commitHash).length > 0) {
return (true, cached.workloadId);
} else {
// The workload is no longer approved, so the policy is no longer valid for this TEE\
return (false, WorkloadId.wrap(0));
}
} else {
// Cache miss or quote changed - use the view function to get the result
(bool allowed, WorkloadId workloadId) = isAllowedPolicy(teeAddress);
if (allowed) {
// Update cache with the new workload ID
cachedWorkloads[teeAddress] = CachedWorkload({workloadId: workloadId, quoteHash: quoteHash});
}
return (allowed, workloadId);
}
}
/// @inheritdoc IBlockBuilderPolicy
function workloadIdForTDRegistration(IFlashtestationRegistry.RegisteredTEE memory registration)
public
pure
override
returns (WorkloadId)
{
// We expect FPU and SSE xfam bits to be set, and anything else should be handled by explicitly allowing the workloadid
bytes8 expectedXfamBits = TD_XFAM_FPU | TD_XFAM_SSE;
// We don't mind VE_DISABLED, PKS, and KL tdattributes bits being set either way, anything else requires explicitly allowing the workloadid
bytes8 ignoredTdAttributesBitmask = TD_TDATTRS_VE_DISABLED | TD_TDATTRS_PKS | TD_TDATTRS_KL;
return WorkloadId.wrap(
keccak256(
bytes.concat(
registration.parsedReportBody.mrTd,
registration.parsedReportBody.rtMr0,
registration.parsedReportBody.rtMr1,
registration.parsedReportBody.rtMr2,
registration.parsedReportBody.rtMr3,
// VMM configuration
registration.parsedReportBody.mrConfigId,
registration.parsedReportBody.xFAM ^ expectedXfamBits,
registration.parsedReportBody.tdAttributes & ~ignoredTdAttributesBitmask
)
)
);
}
/// @inheritdoc IBlockBuilderPolicy
function addWorkloadToPolicy(WorkloadId workloadId, string calldata commitHash, string[] calldata sourceLocators)
external
override
onlyOwner
{
require(bytes(commitHash).length > 0, EmptyCommitHash());
require(sourceLocators.length > 0, EmptySourceLocators());
bytes32 workloadKey = WorkloadId.unwrap(workloadId);
// Check if workload already exists
require(bytes(approvedWorkloads[workloadKey].commitHash).length == 0, WorkloadAlreadyInPolicy());
// Store the workload metadata
approvedWorkloads[workloadKey] = WorkloadMetadata({commitHash: commitHash, sourceLocators: sourceLocators});
emit WorkloadAddedToPolicy(workloadKey);
}
/// @inheritdoc IBlockBuilderPolicy
function removeWorkloadFromPolicy(WorkloadId workloadId) external override onlyOwner {
bytes32 workloadKey = WorkloadId.unwrap(workloadId);
// Check if workload exists
require(bytes(approvedWorkloads[workloadKey].commitHash).length > 0, WorkloadNotInPolicy());
// Remove the workload metadata
delete approvedWorkloads[workloadKey];
emit WorkloadRemovedFromPolicy(workloadKey);
}
/// @inheritdoc IBlockBuilderPolicy
function getWorkloadMetadata(WorkloadId workloadId) external view override returns (WorkloadMetadata memory) {
return approvedWorkloads[WorkloadId.unwrap(workloadId)];
}
/// @inheritdoc IBlockBuilderPolicy
function getHashedTypeDataV4(bytes32 structHash) public view returns (bytes32) {
return _hashTypedDataV4(structHash);
}
/// @inheritdoc IBlockBuilderPolicy
function computeStructHash(uint8 version, bytes32 blockContentHash, uint256 nonce) public pure returns (bytes32) {
return keccak256(abi.encode(VERIFY_BLOCK_BUILDER_PROOF_TYPEHASH, version, blockContentHash, nonce));
}
/// @inheritdoc IBlockBuilderPolicy
function domainSeparator() external view returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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]
* ```solidity
* 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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./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.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @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 ERC-1967) 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 ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @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() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {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 notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../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.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: The upgradeable version of this contract does not use an immutable cache and recomputes the domain separator
* each time {_domainSeparatorV4} is called. That is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/// @inheritdoc IERC5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ReentrancyGuardTransientUpgradeable} from
"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardTransientUpgradeable.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {IAttestation} from "./interfaces/IAttestation.sol";
import {IFlashtestationRegistry} from "./interfaces/IFlashtestationRegistry.sol";
import {QuoteParser} from "./utils/QuoteParser.sol";
import {TD10ReportBody} from "automata-dcap-attestation/contracts/types/V4Structs.sol";
/**
* @title FlashtestationRegistry
* @dev A contract for managing trusted execution environment (TEE) identities and configurations
* using Automata's Intel DCAP attestation
*/
contract FlashtestationRegistry is
IFlashtestationRegistry,
Initializable,
UUPSUpgradeable,
OwnableUpgradeable,
EIP712Upgradeable,
ReentrancyGuardTransientUpgradeable
{
using ECDSA for bytes32;
// ============ Constants ============
/// @notice Minimum length of the td reportdata field: tee address (20 bytes) and hash of extendedRegistrationData(32 bytes)
/// @dev This is the minimum length of the td reportdata field, which is required by the TDX specification
/// @dev The remaining 12 bytes of the 64 byte reportdata field is left unused, it does not matter what is put there
uint256 public constant TD_REPORTDATA_LENGTH = 52;
/// @notice Maximum size for byte arrays to prevent DoS attacks
/// @dev 20KB limit
uint256 public constant MAX_BYTES_SIZE = 20 * 1024;
/// @notice EIP-712 Typehash, used in the permitRegisterTEEService function
bytes32 public constant override REGISTER_TYPEHASH =
keccak256("RegisterTEEService(bytes rawQuote,bytes extendedRegistrationData,uint256 nonce,uint256 deadline)");
// ============ Storage Variables ============
/// @inheritdoc IFlashtestationRegistry
IAttestation public override attestationContract;
/**
* @notice Returns the registered TEE for a given address
* @dev This is used to get the registered TEE for a given address
*/
mapping(address teeAddress => RegisteredTEE) public registeredTEEs;
/// @inheritdoc IFlashtestationRegistry
mapping(address teeAddress => uint256 permitNonce) public override nonces;
/// @dev Storage gap to allow for future storage variable additions in upgrades
/// @dev This reserves 47 storage slots (out of 50 total - 3 used for attestationContract, registeredTEEs and nonces)
uint256[47] __gap;
/// @inheritdoc IFlashtestationRegistry
function initialize(address owner, address _attestationContract) external override initializer {
__Ownable_init(owner);
__EIP712_init("FlashtestationRegistry", "1");
__ReentrancyGuardTransient_init();
__UUPSUpgradeable_init();
require(_attestationContract != address(0), InvalidAttestationContract());
attestationContract = IAttestation(_attestationContract);
}
/**
* @notice Internal function to authorize contract upgrades to the contract
* @dev Only the owner can authorize upgrades
* @dev This function is required by the UUPSUpgradeable contract
* @dev Once there are no bugs in the code for a safe amount of time, we plan to transfer ownership
* to the 0x0 address, so that the contract is no longer upgradeable
* @param newImplementation The address of the new implementation contract
*/
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
/**
* @dev Modifier to check if input bytes size is within limits
* to protect against DoS attacks
* @param data The bytes to check the size of
*/
modifier limitBytesSize(bytes memory data) {
require(data.length <= MAX_BYTES_SIZE, ByteSizeExceeded(data.length));
_;
}
/// @inheritdoc IFlashtestationRegistry
function registerTEEService(bytes calldata rawQuote, bytes calldata extendedRegistrationData)
external
payable
override
nonReentrant
{
doRegister(msg.sender, rawQuote, extendedRegistrationData);
}
/// @inheritdoc IFlashtestationRegistry
function permitRegisterTEEService(
bytes calldata rawQuote,
bytes calldata extendedRegistrationData,
uint256 nonce,
uint256 deadline,
bytes calldata signature
) external payable override nonReentrant {
// Create the digest using EIP712Upgradeable's _hashTypedDataV4
bytes32 digest = hashTypedDataV4(computeStructHash(rawQuote, extendedRegistrationData, nonce, deadline));
// Recover the signer, and ensure it matches the TEE-controlled address, otherwise we have no proof
// whoever created the attestation quote has access to the private key
address signer = digest.recover(signature);
// Verify the nonce
uint256 expectedNonce = nonces[signer];
require(nonce == expectedNonce, InvalidNonce(expectedNonce, nonce));
require(block.timestamp <= deadline, ExpiredSignature(deadline));
// Increment the nonce so that any attempts at replaying this transaction will fail
nonces[signer]++;
doRegister(signer, rawQuote, extendedRegistrationData);
}
/**
* @notice Verifies + Registers a TEE workload with a specific TEE-controlled address in the FlashtestationRegistry
* @dev In order to mitigate DoS attacks, the quote must be less than 20KB
* @dev This is a costly operation (5 million gas) and should be used sparingly.
* @param signer The address from which registration request originates, must match the one in the quote
* @param rawQuote The raw quote from the TEE device. Must be a V4 TDX quote
* @param extendedRegistrationData Abi-encoded application specific attested data
*/
function doRegister(address signer, bytes calldata rawQuote, bytes calldata extendedRegistrationData)
internal
limitBytesSize(rawQuote)
limitBytesSize(extendedRegistrationData)
{
(bool success, bytes memory output) = attestationContract.verifyAndAttestOnChain{value: msg.value}(rawQuote);
require(success, InvalidQuote(output));
// now we know the quote is valid, we can safely parse the output into the TDX report body,
// from which we'll extract the data we need to register the TEE
TD10ReportBody memory td10ReportBody = QuoteParser.parseV4VerifierOutput(output);
// Binding the tee address and extended report data to the quote
require(
td10ReportBody.reportData.length >= TD_REPORTDATA_LENGTH,
InvalidReportDataLength(td10ReportBody.reportData.length)
);
(address teeAddress, bytes32 extendedDataReportHash) = QuoteParser.parseReportData(td10ReportBody.reportData);
// Ensure that the caller is the TEE-controlled address, otherwise we have no guarantees that
// the TEE-controlled address is the one that is registering the TEE
require(signer == teeAddress, SignerMustMatchTEEAddress(signer, teeAddress));
// Verify that the extended registration data matches the hash in the TDX report data
// This is to ensure that the values in extendedRegistrationData are the same as the values
// in the TDX report data, which cannot be forged by the TEE-controlled address
bytes32 extendedRegistrationDataHash = keccak256(extendedRegistrationData);
require(
extendedRegistrationDataHash == extendedDataReportHash,
InvalidRegistrationDataHash(extendedDataReportHash, extendedRegistrationDataHash)
);
bytes32 newQuoteHash = keccak256(rawQuote);
bool previouslyRegistered = checkPreviousRegistration(teeAddress, newQuoteHash);
// Register the address in the registry with the raw quote so later on if the TEE has its
// underlying DCAP endorsements updated, we can invalidate the TEE's attestation
registeredTEEs[teeAddress] = RegisteredTEE({
rawQuote: rawQuote,
parsedReportBody: td10ReportBody,
extendedRegistrationData: extendedRegistrationData,
isValid: true,
quoteHash: newQuoteHash
});
emit TEEServiceRegistered(teeAddress, rawQuote, previouslyRegistered);
}
/**
* @notice Checks if a TEE is already registered with the same quote
* @dev We use the quoteHash instead of the rawQuote to avoid unnecessary SLOADs
* @dev If a user is trying to add the same address, and quote, this is a no-op
* and we should revert to signal that the user may be making a mistake (why would
* they be trying to add the same TEE twice?).
* @dev If the TEE is already registered and we're using a different quote,
* that is fine and indicates the TEE-controlled address is either re-attesting
* (with a new quote) or has moved its private key to a new TEE device
* @dev We do not need to check the public key, because the address has a cryptographically-ensured
* 1-to-1 relationship with the public key, so checking it would be redundant
* @param teeAddress The TEE-controlled address of the TEE
* @param newQuoteHash The hash of registration's new raw quote
* @return Whether the TEE is already registered but is updating its quote
*/
function checkPreviousRegistration(address teeAddress, bytes32 newQuoteHash) internal view returns (bool) {
bytes32 existingQuoteHash = registeredTEEs[teeAddress].quoteHash;
require(newQuoteHash != existingQuoteHash, TEEServiceAlreadyRegistered(teeAddress));
// if the TEE is already registered, but we're using a different quote,
// return true to signal that the TEE is already registered but is updating its quote
return existingQuoteHash != 0;
}
/// @inheritdoc IFlashtestationRegistry
function getRegistration(address teeAddress) public view override returns (bool, RegisteredTEE memory) {
return (registeredTEEs[teeAddress].isValid, registeredTEEs[teeAddress]);
}
/// @inheritdoc IFlashtestationRegistry
function getRegistrationStatus(address teeAddress)
external
view
override
returns (bool isValid, bytes32 quoteHash)
{
RegisteredTEE storage tee = registeredTEEs[teeAddress];
return (tee.isValid, tee.quoteHash);
}
/// @inheritdoc IFlashtestationRegistry
function invalidateAttestation(address teeAddress) external payable override nonReentrant {
// check to make sure it even makes sense to invalidate the TEE-controlled address
// if the TEE-controlled address is not registered with the FlashtestationRegistry,
// it doesn't make sense to invalidate the attestation
RegisteredTEE memory registeredTEE = registeredTEEs[teeAddress];
require(registeredTEE.rawQuote.length > 0, TEEServiceNotRegistered(teeAddress));
require(registeredTEE.isValid, TEEServiceAlreadyInvalid(teeAddress));
// now we check the attestation, and invalidate the TEE if it's no longer valid.
// This will only happen if the DCAP Endorsements associated with the TEE's quote
// have been updated
(bool success,) = attestationContract.verifyAndAttestOnChain{value: msg.value}(registeredTEE.rawQuote);
require(!success, TEEIsStillValid(teeAddress));
registeredTEEs[teeAddress].isValid = false;
emit TEEServiceInvalidated(teeAddress);
}
/// @inheritdoc IFlashtestationRegistry
function invalidatePreviousSignature(uint256 _nonce) external override {
uint256 nonce = nonces[msg.sender];
require(_nonce == nonce, InvalidNonce(nonce, _nonce));
nonces[msg.sender]++;
emit PreviousSignatureInvalidated(msg.sender, nonce);
}
/// @inheritdoc IFlashtestationRegistry
function hashTypedDataV4(bytes32 structHash) public view override returns (bytes32) {
return _hashTypedDataV4(structHash);
}
/// @inheritdoc IFlashtestationRegistry
function computeStructHash(
bytes calldata rawQuote,
bytes calldata extendedRegistrationData,
uint256 nonce,
uint256 deadline
) public pure override returns (bytes32) {
return keccak256(
abi.encode(REGISTER_TYPEHASH, keccak256(rawQuote), keccak256(extendedRegistrationData), nonce, deadline)
);
}
/// @inheritdoc IFlashtestationRegistry
function domainSeparator() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IAttestation} from "./IAttestation.sol";
import {TD10ReportBody} from "automata-dcap-attestation/contracts/types/V4Structs.sol";
/**
* @title IFlashtestationRegistry
* @dev Interface for the FlashtestationRegistry contract which manages trusted execution environment (TEE)
* identities and configurations using Automata's Intel DCAP attestation
*/
interface IFlashtestationRegistry {
/// @notice TEE identity and status tracking
struct RegisteredTEE {
bool isValid; // true upon first registration, and false after a quote invalidation
bytes rawQuote; // The raw quote from the TEE device, which is stored to allow for future quote quote invalidation
TD10ReportBody parsedReportBody; // Parsed form of the quote to avoid unnecessary parsing
bytes extendedRegistrationData; // Any additional attested data for application purposes. This data is attested by a bytes32 in the attestation's reportData, where that bytes32 is a hash of the ABI-encoded values in the extendedRegistrationData. This registration data can be anything that's needed for your app, for instance an vmOperatorIdPublicKey that allows you to verify signatures from your TEE operator, parts of runtime configuration of the VM, configuration submitted by the VM operator, for example the public IP of the instance,
bytes32 quoteHash; // keccak256 hash of rawQuote for caching purposes
}
// ============ Events ============
/// @notice Emitted when a TEE service is registered
/// @param teeAddress The address of the TEE service
/// @param rawQuote The raw quote from the TEE device
/// @param alreadyExists Whether the TEE service is already registered
event TEEServiceRegistered(address indexed teeAddress, bytes rawQuote, bool alreadyExists);
/// @notice Emitted when a TEE service is invalidated
/// @param teeAddress The address of the TEE service
event TEEServiceInvalidated(address indexed teeAddress);
/// @notice Emitted when a previous signature is invalidated
/// @param teeAddress The address of the TEE service
/// @param invalidatedNonce The nonce of the invalidated signature
event PreviousSignatureInvalidated(address indexed teeAddress, uint256 invalidatedNonce);
// ============ Errors ============
/// @notice Emitted when the attestation contract is the 0x0 address
error InvalidAttestationContract();
/// @notice Emitted when the signature is expired because the deadline has passed
error ExpiredSignature(uint256 deadline);
/// @notice Emitted when the quote is invalid according to the Automata DCAP Attestation contract
error InvalidQuote(bytes output);
/// @notice Emitted when the report data length is too short
error InvalidReportDataLength(uint256 length);
/// @notice Emitted when the registration data hash does not match the expected hash
error InvalidRegistrationDataHash(bytes32 expected, bytes32 received);
/// @notice Emitted when the byte size is exceeded
error ByteSizeExceeded(uint256 size);
/// @notice Emitted when the TEE service is already registered when registering
error TEEServiceAlreadyRegistered(address teeAddress);
/// @notice Emitted when the signer doesn't match the TEE address
error SignerMustMatchTEEAddress(address signer, address teeAddress);
/// @notice Emitted when the TEE service is not registered
error TEEServiceNotRegistered(address teeAddress);
/// @notice Emitted when the TEE service is already invalid when trying to invalidate a TEE registration
error TEEServiceAlreadyInvalid(address teeAddress);
/// @notice Emitted when the TEE service is still valid when trying to invalidate a TEE registration
error TEEIsStillValid(address teeAddress);
/// @notice Emitted when the nonce is invalid when verifying a signature
error InvalidNonce(uint256 expected, uint256 provided);
// ============ Functions ============
/**
* Initializer to set the Automata DCAP Attestation contract, which verifies TEE quotes
* @param owner The address of the initial owner of the contract, who is able to upgrade the contract
* @param _attestationContract The address of the Automata DCAP attestation contract, used to verify TEE quotes
*/
function initialize(address owner, address _attestationContract) external;
/**
* @notice Registers a TEE workload with a specific TEE-controlled address in the FlashtestationRegistry
* @notice The TEE must be registered with a quote whose validity is verified by the attestationContract
* @dev In order to mitigate DoS attacks, the quote must be less than 20KB
* @dev This is a costly operation (5 million gas) and should be used sparingly.
* @param rawQuote The raw quote from the TEE device. Must be a V4 TDX quote
* @param extendedRegistrationData Abi-encoded application specific attested data, reserved for future upgrades
*/
function registerTEEService(bytes calldata rawQuote, bytes calldata extendedRegistrationData) external payable;
/**
* @notice Registers a TEE workload with a specific TEE-controlled address using EIP-712 signatures
* @notice The TEE must be registered with a quote whose validity is verified by the attestationContract
* @dev In order to mitigate DoS attacks, the quote must be less than 20KB
* @dev This function exists so that the TEE does not need to be funded with gas for transaction fees, and
* instead can rely on any EOA to execute the transaction, but still only allow quotes from attested TEEs
* @dev Replay is implicitly shielded against replay attacks through the transaction's nonce (TEE must sign the new nonce)
* @param rawQuote The raw quote from the TEE device. Must be a V4 TDX quote
* @param extendedRegistrationData Abi-encoded application specific attested data, this is arbitrary app-related
* data that the app wants to associate with the TEE-controlled address. Even though it's passed in as a parameter,
* we can trust that it comes from the TEE because we verify that the hash derived from all of the variables in
* extendedRegistrationData matches the hash in the TDX report data.
* @param nonce The nonce to use for the EIP-712 signature (to prevent replay attacks)
* @param deadline The blocktime after which this signature is no longer valid
* @param signature The EIP-712 signature of the registration message
*/
function permitRegisterTEEService(
bytes calldata rawQuote,
bytes calldata extendedRegistrationData,
uint256 nonce,
uint256 deadline,
bytes calldata signature
) external payable;
/**
* @notice Fetches only the validity status and quote hash for a given TEE address
* @dev This is a gas-optimized version of getRegistration that only returns the minimal data
* needed for caching optimizations in policy contracts
* @param teeAddress The TEE-controlled address to check
* @return isValid True if the TEE is registered and the attestation is valid
* @return registeredTEE The registered TEE
*/
function getRegistration(address teeAddress)
external
view
returns (bool isValid, RegisteredTEE memory registeredTEE);
/**
* @notice Fetches only the validity status and quote hash for a given TEE address
* @dev This is a gas-optimized version of getRegistration that only returns the minimal data
* needed for caching optimizations in policy contracts
* @param teeAddress The TEE-controlled address to check
* @return isValid True if the TEE is registered and the attestation is valid
* @return quoteHash The keccak256 hash of the raw quote
*/
function getRegistrationStatus(address teeAddress) external view returns (bool isValid, bytes32 quoteHash);
/**
* @notice Invalidates the attestation of a TEE
* @dev This is a costly operation (5 million gas) and should be used sparingly.
* @dev Will always revert except if the attestation is valid and the attestation re-verification
* fails. This is to prevent a user needlessly calling this function and for a no-op to occur
* @dev This function exists to handle an important security requirement: occasionally Intel
* will release a new set of DCAP Endorsements for a particular TEE setup (for instance if a
* TDX vulnerability was discovered), which invalidates all prior quotes generated by that TEE.
* By invalidates we mean that the outputs generated by the TEE-controlled address associated
* with these invalid quotes are no longer secure and cannot be relied upon. This fact needs to be
* reflected onchain, so that any upstream contracts that try to call `getRegistration` will
* correctly return `false` for the TEE-controlled addresses associated with these invalid quotes.
* This is a security requirement to ensure that no downstream contracts can be exploited by
* a malicious TEE that has been compromised
* @dev Note: this function is callable by anyone, so that offchain monitoring services can
* quickly mark TEEs as invalid
* @param teeAddress The TEE-controlled address to invalidate
*/
function invalidateAttestation(address teeAddress) external payable;
/**
* @notice Allows a user to increment their EIP-712 signature nonce, invalidating any previously signed but unexecuted permit signatures.
* @dev This function provides a way for users to proactively invalidate old signatures by incrementing their nonce,
* without needing to execute a valid permit.
* This is particularly useful if a user suspects a signature may have been compromised or simply wants to ensure
* that any outstanding, unused signatures with the current nonce can no longer be executed.
* @dev The function requires the provided nonce to match the user's current nonce, as a defense against the caller
* mistakenly invalidating a nonce that they did not intend to invalidate
* @param _nonce The expected current nonce for the caller; must match the stored nonce
*/
function invalidatePreviousSignature(uint256 _nonce) external;
/**
* @notice Computes the digest for the EIP-712 signature
* @dev This is useful for when both onchain and offchain users want to compute the digest
* for the EIP-712 signature, and then use it to verify the signature
* @param structHash The struct hash for the EIP-712 signature
* @return The digest for the EIP-712 signature
*/
function hashTypedDataV4(bytes32 structHash) external view returns (bytes32);
/**
* @notice Computes the struct hash for the EIP-712 signature
* @dev This is useful for when both onchain and offchain users want to compute the struct hash
* for the EIP-712 signature, and then use it to verify the signature
* @param rawQuote The raw quote from the TEE device
* @param extendedRegistrationData Abi-encoded attested data, application specific
* @param nonce The nonce to use for the EIP-712 signature
* @param deadline The blocktime after which this signature is no longer valid
* @return The struct hash for the EIP-712 signature
*/
function computeStructHash(
bytes calldata rawQuote,
bytes calldata extendedRegistrationData,
uint256 nonce,
uint256 deadline
) external pure returns (bytes32);
/**
* @notice Returns the domain separator for the EIP-712 signature
* @dev This is useful for when both onchain and offchain users want to compute the domain separator
* for the EIP-712 signature, and then use it to verify the signature
* @return The domain separator for the EIP-712 signature
*/
function domainSeparator() external view returns (bytes32);
/**
* @notice Returns the current nonce for a given TEE-controlled address
* @dev This is used in the permitRegisterTEEService function to prevent replay attacks
* @param teeAddress The TEE-controlled address
* @return The current nonce
*/
function nonces(address teeAddress) external view returns (uint256);
/**
* @notice EIP-712 Typehash, used in the permitRegisterTEEService function
* @dev This is used in the permitRegisterTEEService function to prevent replay attacks
* @return The EIP-712 Typehash
*/
function REGISTER_TYPEHASH() external view returns (bytes32);
/**
* @notice Returns the address of the Automata DCAP Attestation contract
* @dev This is used to verify TEE quotes
* @return The address of the Automata DCAP Attestation contract
*/
function attestationContract() external view returns (IAttestation);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IFlashtestationRegistry} from "./IFlashtestationRegistry.sol";
/// @notice WorkloadID uniquely identifies a TEE workload. A workload is roughly equivalent to a version of an application's
/// code, can be reproduced from source code, and is derived from a combination of the TEE's measurement registers.
/// The TDX platform provides several registers that capture cryptographic hashes of code, data, and configuration
/// loaded into the TEE's environment. This means that whenever a TEE device changes anything about its compute stack
/// (e.g. user code, firmware, OS, etc), the workloadID will change.
/// See the [Flashtestation's specification](https://github.com/flashbots/rollup-boost/blob/main/specs/flashtestations.md#workload-identity-derivation) for more details
type WorkloadId is bytes32;
/**
* @title IBlockBuilderPolicy
* @dev Interface exposing errors, events, and external/public functions of BlockBuilderPolicy
*/
interface IBlockBuilderPolicy {
// ============ Types ============
/**
* @notice Metadata associated with a workload
* @dev Used to track the source code used to build the TEE image identified by the workloadId
*/
struct WorkloadMetadata {
string commitHash;
string[] sourceLocators;
}
// ============ Events ============
/// @notice Emitted when a workload is added to the policy
/// @param workloadId The workload identifier
event WorkloadAddedToPolicy(bytes32 indexed workloadId);
/// @notice Emitted when a workload is removed from the policy
/// @param workloadId The workload identifier
event WorkloadRemovedFromPolicy(bytes32 indexed workloadId);
/// @notice Emitted when the registry is set in the initializer
/// @param registry The address of the registry
event RegistrySet(address indexed registry);
/// @notice Emitted when a block builder proof is successfully verified
/// @param caller The address that called the verification function (TEE address)
/// @param workloadId The workload identifier of the TEE
/// @param version The flashtestation protocol version used
/// @param blockContentHash The hash of the block content
/// @param commitHash The git commit hash associated with the workload
event BlockBuilderProofVerified(
address caller, bytes32 workloadId, uint8 version, bytes32 blockContentHash, string commitHash
);
// ============ Errors ============
/// @notice Emitted when the registry is the 0x0 address
error InvalidRegistry();
/// @notice Emitted when a workload to be added is already in the policy
error WorkloadAlreadyInPolicy();
/// @notice Emitted when a workload to be removed is not in the policy
error WorkloadNotInPolicy();
/// @notice Emitted when the address is not in the approvedWorkloads mapping
error UnauthorizedBlockBuilder(address caller);
/// @notice Emitted when the nonce is invalid
error InvalidNonce(uint256 expected, uint256 provided);
/// @notice Emitted when the commit hash is empty
error EmptyCommitHash();
/// @notice Emitted when the source locators array is empty
error EmptySourceLocators();
// ============ Functions ============
/// @notice Initializer to set the FlashtestationRegistry contract which verifies TEE quotes and the initial owner of the contract
/// @param _initialOwner The address of the initial owner of the contract
/// @param _registry The address of the registry contract
function initialize(address _initialOwner, address _registry) external;
/// @notice Verify a block builder proof with a Flashtestation Transaction
/// @param version The version of the flashtestation's protocol used to generate the block builder proof
/// @param blockContentHash The hash of the block content
/// @notice This function will only succeed if the caller is a registered TEE-controlled address from an attested TEE
/// and the TEE is running an approved block builder workload (see `addWorkloadToPolicy`)
/// @notice The blockContentHash is a keccak256 hash of a subset of the block header, as specified by the version.
/// See the [flashtestations spec](https://github.com/flashbots/rollup-boost/blob/main/specs/flashtestations.md) for more details
/// @dev If you do not want to deal with the operational difficulties of keeping your TEE-controlled
/// addresses funded, you can use the permitVerifyBlockBuilderProof function instead which costs
/// more gas, but allows any EOA to submit a block builder proof on behalf of a TEE
function verifyBlockBuilderProof(uint8 version, bytes32 blockContentHash) external;
/// @notice Verify a block builder proof with a Flashtestation Transaction using EIP-712 signatures
/// @notice This function allows any EOA to submit a block builder proof on behalf of a TEE
/// @notice The TEE must sign a proper EIP-712-formatted message, and the signer must match a TEE-controlled address
/// whose associated workload is approved under this policy
/// @dev This function is useful if you do not want to deal with the operational difficulties of keeping your
/// TEE-controlled addresses funded, but note that because of the larger number of function arguments, will cost
/// more gas than the non-EIP-712 verifyBlockBuilderProof function
/// @param version The version of the flashtestation's protocol used to generate the block builder proof
/// @param blockContentHash The hash of the block content
/// @param nonce The nonce to use for the EIP-712 signature
/// @param eip712Sig The EIP-712 signature of the verification message
function permitVerifyBlockBuilderProof(
uint8 version,
bytes32 blockContentHash,
uint256 nonce,
bytes calldata eip712Sig
) external;
/// @notice Check if this TEE-controlled address has registered a valid TEE workload with the registry, and
/// if the workload is approved under this policy
/// @param teeAddress The TEE-controlled address
/// @return allowed True if the TEE is using an approved workload in the policy
/// @return workloadId The workloadId of the TEE that is using an approved workload in the policy, or 0 if
/// the TEE is not using an approved workload in the policy
function isAllowedPolicy(address teeAddress) external view returns (bool, WorkloadId workloadId);
/// @notice Application specific mapping of registration data to a workload identifier
/// @dev Think of the workload identifier as the version of the application for governance.
/// The workloadId verifiably maps to a version of source code that builds the TEE VM image
/// @param registration The registration data from a TEE device
/// @return workloadId The computed workload identifier
function workloadIdForTDRegistration(IFlashtestationRegistry.RegisteredTEE memory registration)
external
pure
returns (WorkloadId);
/// @notice Add a workload to a policy (governance only)
/// @notice Only the owner of this contract can add workloads to the policy
/// and it is the responsibility of the owner to ensure that the workload is valid
/// otherwise the address associated with this workload has full power to do anything
/// who's authorization is based on this policy
/// @dev The commitHash solves the following problem; The only way for a smart contract like BlockBuilderPolicy
/// to verify that a TEE (identified by its workloadId) is running a specific piece of code (for instance,
/// op-rbuilder) is to reproducibly build that workload onchain. This is prohibitively expensive, so instead
/// we rely on a permissioned multisig (the owner of this contract) to add a commit hash to the policy whenever
/// it adds a new workloadId. We're already relying on the owner to verify that the workloadId is valid, so
/// we can also assume the owner will not add a commit hash that is not associated with the workloadId. If
/// the owner did act maliciously, this can easily be determined offchain by an honest actor building the
/// TEE image from the given commit hash, deriving the image's workloadId, and then comparing it to the
/// workloadId stored on the policy that is associated with the commit hash. If the workloadId is different,
/// this can be used to prove that the owner acted maliciously. In the honest case, this Policy serves as a
/// source of truth for which source code of build software (i.e. the commit hash) is used to build the TEE image
/// identified by the workloadId.
/// @param workloadId The workload identifier
/// @param commitHash The 40-character hexadecimal commit hash of the git repository
/// whose source code is used to build the TEE image identified by the workloadId
/// @param sourceLocators An array of URIs pointing to the source code
function addWorkloadToPolicy(WorkloadId workloadId, string calldata commitHash, string[] calldata sourceLocators)
external;
/// @notice Remove a workload from a policy (governance only)
/// @param workloadId The workload identifier
function removeWorkloadFromPolicy(WorkloadId workloadId) external;
/// @notice Mapping from workloadId to its metadata (commit hash and source locators)
/// @dev This is only updateable by governance (i.e. the owner) of the Policy contract
/// Adding and removing a workload is O(1)
/// @param workloadId The workload identifier to query
/// @return The metadata associated with the workload
function getWorkloadMetadata(WorkloadId workloadId) external view returns (WorkloadMetadata memory);
/// @notice Computes the digest for the EIP-712 signature
/// @param structHash The struct hash for the EIP-712 signature
/// @return The digest for the EIP-712 signature
function getHashedTypeDataV4(bytes32 structHash) external view returns (bytes32);
/// @notice Computes the struct hash for the EIP-712 signature
/// @param version The version of the flashtestation's protocol
/// @param blockContentHash The hash of the block content
/// @param nonce The nonce to use for the EIP-712 signature
/// @return The struct hash for the EIP-712 signature
function computeStructHash(uint8 version, bytes32 blockContentHash, uint256 nonce)
external
pure
returns (bytes32);
/// @notice Returns the domain separator for the EIP-712 signature
/// @dev This is useful for when both onchain and offchain users want to compute the domain separator
/// for the EIP-712 signature, and then use it to verify the signature
/// @return The domain separator for the EIP-712 signature
function domainSeparator() external view returns (bytes32);
// ============ Auto-generated getters for public state ============
/// @notice Address of the FlashtestationRegistry contract that verifies TEE quotes
function registry() external view returns (address);
/// @notice Tracks nonces for EIP-712 signatures to prevent replay attacks
function nonces(address teeAddress) external view returns (uint256);
/// @notice EIP-712 Typehash, used in the permitVerifyBlockBuilderProof function
function VERIFY_BLOCK_BUILDER_PROOF_TYPEHASH() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)
pragma solidity >=0.4.16;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "@openzeppelin/contracts/utils/TransientSlot.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransientUpgradeable is Initializable {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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 __ReentrancyGuardTransient_init() internal onlyInitializing {
}
function __ReentrancyGuardTransient_init_unchained() internal onlyInitializing {
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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 REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/**
* @title IAttestation
* @dev Interface for the Automata DCAPattestation contract, which verifies TEE quotes
*/
interface IAttestation {
function verifyAndAttestOnChain(bytes calldata rawQuote) external payable returns (bool, bytes memory);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {TD10ReportBody} from "automata-dcap-attestation/contracts/types/V4Structs.sol";
import {BytesUtils} from "@automata-network/on-chain-pccs/utils/BytesUtils.sol";
import {TD_REPORT10_LENGTH, TDX_TEE, HEADER_LENGTH} from "automata-dcap-attestation/contracts/types/Constants.sol";
/**
* @title QuoteParser
* @dev A library for parsing and extracting workload and TEE-controlled address from Automata DCAP Attestation TDX quotes
*/
library QuoteParser {
using BytesUtils for bytes;
// Constants
// The TDX version of the quote Flashtestation's accepts
uint256 public constant ACCEPTED_TDX_VERSION = 4;
// This is the number of bytes in the Output struct that come before the quoteBody.
// See the Output struct definition in the Automata DCAP Attestation repo:
// https://github.com/automata-network/automata-dcap-attestation/blob/evm-v1.0.0/evm/contracts/types/CommonStruct.sol#L113
// 13 bytes = quoteVersion (2 bytes) + tee (4 byte) + tcbStatus (1 byte) + fmspcBytes (6 bytes)
uint256 public constant SERIALIZED_OUTPUT_OFFSET = 13;
// Errors
error InvalidTEEType(bytes4 teeType);
error InvalidTEEVersion(uint16 version);
error InvalidQuoteLength(uint256 length);
/**
* @notice Parses the serialized output of the V4QuoteVerifier into a TD10ReportBody which contains
* all the data we need for registering a TEE, using the serializedOutput bytes generated by Automata's
* verification logic
* @param serializedOutput The serializedOutput bytes generated by Automata's verification logic
* @return report The parsed TD10ReportBody
* @dev Taken from Automata's DCAP Attestation repo:
* https://github.com/automata-network/automata-dcap-attestation/blob/evm-v1.0.0/evm/contracts/verifiers/V4QuoteVerifier.sol#L309
*/
function parseV4VerifierOutput(bytes memory serializedOutput) internal pure returns (TD10ReportBody memory) {
// check that now-verified quote is version 4 and of type TDX, otherwise
// in the next step the output will not have the byte length we expect
// and we'll fail to parse it, returning a unhelpful error message
checkTEEVersion(serializedOutput);
checkTEEType(serializedOutput);
require(
serializedOutput.length >= SERIALIZED_OUTPUT_OFFSET + TD_REPORT10_LENGTH,
InvalidQuoteLength(serializedOutput.length)
);
return parseRawReportBody(serializedOutput.substring(SERIALIZED_OUTPUT_OFFSET, TD_REPORT10_LENGTH));
}
/**
* @notice Parses a V4 TDX quote into a TD10ReportBody
* @param rawV4Quote The raw V4 TDX quote
* @return report The parsed TD10ReportBody
*/
function parseV4Quote(bytes memory rawV4Quote) internal pure returns (TD10ReportBody memory) {
require(rawV4Quote.length >= HEADER_LENGTH + TD_REPORT10_LENGTH, InvalidQuoteLength(rawV4Quote.length));
return parseRawReportBody(rawV4Quote.substring(HEADER_LENGTH, TD_REPORT10_LENGTH));
}
/**
* @notice Parses a raw report body into a TD10ReportBody
* @param rawReportBody The raw report body
* @return report The parsed TD10ReportBody
* @dev Taken from Automata's DCAP Attestation repo:
* https://github.com/automata-network/automata-dcap-attestation/blob/evm-v1.0.0/evm/contracts/verifiers/V4QuoteVerifier.sol#L309
*/
function parseRawReportBody(bytes memory rawReportBody) internal pure returns (TD10ReportBody memory report) {
report.teeTcbSvn = bytes16(rawReportBody.substring(0, 16));
report.mrSeam = rawReportBody.substring(16, 48);
report.mrsignerSeam = rawReportBody.substring(64, 48);
report.seamAttributes = bytes8(rawReportBody.substring(112, 8));
report.tdAttributes = bytes8(rawReportBody.substring(120, 8));
report.xFAM = bytes8(rawReportBody.substring(128, 8));
report.mrTd = rawReportBody.substring(136, 48);
report.mrConfigId = rawReportBody.substring(184, 48);
report.mrOwner = rawReportBody.substring(232, 48);
report.mrOwnerConfig = rawReportBody.substring(280, 48);
report.rtMr0 = rawReportBody.substring(328, 48);
report.rtMr1 = rawReportBody.substring(376, 48);
report.rtMr2 = rawReportBody.substring(424, 48);
report.rtMr3 = rawReportBody.substring(472, 48);
report.reportData = rawReportBody.substring(520, 64);
}
/**
* Parses reportData to tee address and hash of extended report data
*/
function parseReportData(bytes memory reportDataBytes)
internal
pure
returns (address teeAddress, bytes32 extDataHash)
{
teeAddress = address(uint160(bytes20(reportDataBytes.substring(0, 20))));
extDataHash = bytes32(reportDataBytes.substring(20, 32));
}
/**
* Parses and checks that the uint16 version from the quote header is one we accept
* @param rawReportBody The rawQuote bytes generated by Automata's verification logic
* @dev Automata currently only supports V3 and V4 TDX quotes
*/
function checkTEEVersion(bytes memory rawReportBody) internal pure {
uint16 version = uint16(bytes2((rawReportBody.substring(0, 2)))); // uint16 is 2 bytes
require(version == ACCEPTED_TDX_VERSION, InvalidTEEVersion(version));
}
/**
* Parses and checks that the bytes4 tee type from the quote header is of type TDX
* @param rawReportBody The rawQuote bytes generated by Automata's verification logic
* @dev Automata currently only supports SGX and TDX TEE types
*/
function checkTEEType(bytes memory rawReportBody) internal pure {
bytes4 teeType = bytes4(rawReportBody.substring(2, 4)); // 4 bytes
require(teeType == TDX_TEE, InvalidTEEType(teeType));
}
}//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./CommonStruct.sol";
/**
* @notice V4 Intel TDX Quote uses this struct as the quote body
* @dev Section A.3.2 of Intel V4 TDX DCAP API Library Documentation
* @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/7e5b2a13ca5472de8d97dd7d7024c2ea5af9a6ba/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L82-L103
*/
struct TD10ReportBody {
bytes16 teeTcbSvn;
bytes mrSeam; // 48 bytes
bytes mrsignerSeam; // 48 bytes
bytes8 seamAttributes;
bytes8 tdAttributes;
bytes8 xFAM;
bytes mrTd; // 48 bytes
bytes mrConfigId; // 48 bytes
bytes mrOwner; // 48 bytes
bytes mrOwnerConfig; // 48 bytes
bytes rtMr0; // 48 bytes
bytes rtMr1; // 48 nytes
bytes rtMr2; // 48 bytes
bytes rtMr3; // 48 bytes
bytes reportData; // 64 bytes
}
/**
* @notice QE Report Certification Data struct definition
* @dev this struct is the data that is stored as bytes array in CertificationData of type 6
* @dev Section A.3.11 of Intel V4 TDX DCAP API Library Documentation
* @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L143-L151
*/
struct QEReportCertificationData {
EnclaveReport qeReport;
bytes qeReportSignature;
QEAuthData qeAuthData;
CertificationData certification;
}
/**
* @notice ECDSA V4 Quote Signature Data Structure Definition
* @dev Section A.3.8 of Intel V4 TDX DCAP API Library Documentation
*/
struct ECDSAQuoteV4AuthData {
bytes ecdsa256BitSignature; // 64 bytes
bytes ecdsaAttestationKey; // 64 bytes
QEReportCertificationData qeReportCertData;
}
/// In the Solidity implementation, quotes using different TEE types are represented by different structs.
/// As opposed to a unified struct, as seen in https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/Quote.h
struct V4SGXQuote {
Header header;
EnclaveReport localEnclaveReport;
ECDSAQuoteV4AuthData authData;
}
struct V4TDXQuote {
Header header;
TD10ReportBody reportBody;
ECDSAQuoteV4AuthData authData;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) 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
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @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 ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.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) {
uint256 localValue = value;
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] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
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);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: BSD 2-Clause License
pragma solidity ^0.8.0;
// Inspired by ensdomains/dnssec-oracle - BSD-2-Clause license
// https://github.com/ensdomains/dnssec-oracle/blob/master/contracts/BytesUtils.sol
library BytesUtils {
/*
* @dev Returns the keccak-256 hash of a byte range.
* @param self The byte string to hash.
* @param offset The position to start hashing at.
* @param len The number of bytes to hash.
* @return The hash of the byte range.
*/
function keccak(bytes memory self, uint256 offset, uint256 len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := keccak256(add(add(self, 32), offset), len)
}
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal.
* @param self The first bytes to compare.
* @param other The second bytes to compare.
* @return The result of the comparison.
*/
function compare(bytes memory self, bytes memory other) internal pure returns (int256) {
return compare(self, 0, self.length, other, 0, other.length);
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first bytes to compare.
* @param offset The offset of self.
* @param len The length of self.
* @param other The second bytes to compare.
* @param otheroffset The offset of the other string.
* @param otherlen The length of the other string.
* @return The result of the comparison.
*/
function compare(
bytes memory self,
uint256 offset,
uint256 len,
bytes memory other,
uint256 otheroffset,
uint256 otherlen
) internal pure returns (int256) {
uint256 shortest = len;
if (otherlen < len) {
shortest = otherlen;
}
uint256 selfptr;
uint256 otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint256 idx = 0; idx < shortest; idx += 32) {
uint256 a;
uint256 b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask;
if (shortest > 32) {
mask = type(uint256).max; // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0) {
return int256(diff);
}
}
selfptr += 32;
otherptr += 32;
}
return int256(len) - int256(otherlen);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @param len The number of bytes to compare
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint256 offset, bytes memory other, uint256 otherOffset, uint256 len)
internal
pure
returns (bool)
{
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
/*
* @dev Returns true if the two byte ranges are equal with offsets.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint256 offset, bytes memory other, uint256 otherOffset)
internal
pure
returns (bool)
{
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
/*
* @dev Compares a range of 'self' to all of 'other' and returns True iff
* they are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint256 offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, bytes memory other) internal pure returns (bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
/*
* @dev Returns the 8-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 8 bits of the string, interpreted as an integer.
*/
function readUint8(bytes memory self, uint256 idx) internal pure returns (uint8 ret) {
return uint8(self[idx]);
}
/*
* @dev Returns the 16-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 16 bits of the string, interpreted as an integer.
*/
function readUint16(bytes memory self, uint256 idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
/*
* @dev Returns the 32-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bits of the string, interpreted as an integer.
*/
function readUint32(bytes memory self, uint256 idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes32(bytes memory self, uint256 idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes20(bytes memory self, uint256 idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret :=
and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
/*
* @dev Returns the n byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes.
* @param len The number of bytes.
* @return The specified 32 bytes of the string.
*/
function readBytesN(bytes memory self, uint256 idx, uint256 len) internal pure returns (bytes32 ret) {
require(len <= 32);
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint256 mask;
if (len == 0) {
mask = type(uint256).max; // Set to maximum value of uint256
} else {
mask = 256 ** (32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Copies a substring into a new byte string.
* @param self The byte string to copy from.
* @param offset The offset to start copying at.
* @param len The number of bytes to copy.
*/
function substring(bytes memory self, uint256 offset, uint256 len) internal pure returns (bytes memory) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint256 dest;
uint256 src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
// Maps characters from 0x30 to 0x7A to their base32 values.
// 0xFF represents invalid characters in that range.
bytes constant base32HexTable =
hex"00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
/**
* @dev Decodes unpadded base32 data of up to one word in length.
* @param self The data to decode.
* @param off Offset into the string to start at.
* @param len Number of characters to decode.
* @return The decoded data, left aligned.
*/
function base32HexDecodeWord(bytes memory self, uint256 off, uint256 len) internal pure returns (bytes32) {
require(len <= 52);
uint256 ret = 0;
uint8 decoded;
for (uint256 i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint256(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if (i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint256 bitlen = len * 5;
if (len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if (len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if (len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if (len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if (len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
function compareBytes(bytes memory a, bytes memory b) internal pure returns (bool) {
if (a.length != b.length) {
return false;
}
for (uint256 i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
}//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteConstants.h uint16 constant HEADER_LENGTH = 48; bytes2 constant SUPPORTED_ATTESTATION_KEY_TYPE = 0x0200; // ECDSA_256_WITH_P256_CURVE (LE) // TEE_TYPE are little-endian encoded, hence reversing the order of bytes bytes4 constant SGX_TEE = 0x00000000; bytes4 constant TDX_TEE = 0x81000000; bytes16 constant VALID_QE_VENDOR_ID = 0x939a7233f79c4ca9940a0db3957f0607; uint16 constant ENCLAVE_REPORT_LENGTH = 384; uint16 constant TD_REPORT10_LENGTH = 584; // Header (48 bytes) + Body (minimum 384 bytes) + AuthDataSize (4 bytes) + AuthData: // ECDSA_SIGNATURE (64 bytes) + ECDSA_KEY (64 bytes) + QE_REPORT_BYTES (384 bytes) // + QE_REPORT_SIGNATURE (64 bytes) + QE_AUTH_DATA_SIZE (2 bytes) + QE_CERT_DATA_TYPE (2 bytes) // + QE_CERT_DATA_SIZE (4 bytes) uint16 constant MINIMUM_QUOTE_LENGTH = 1020; // timestamp + tcb_info_hash + identity_hash + root_ca_hash + tcb_signing_hash + root_crl_hash + pck_crl_hash // 8 + 6 * 32 = 200 uint16 constant VERIFIED_OUTPUT_COLLATERAL_HASHES_LENGTH = 200;
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {TCBStatus} from "@automata-network/on-chain-pccs/helpers/FmspcTcbHelper.sol";
import {X509CertObj} from "@automata-network/on-chain-pccs/helpers/X509Helper.sol";
/**
* @title CommonStruct
* @notice Structs that are common across different versions and TEE of Intel DCAP Quote
* @dev may refer to Intel Official Documentation for more details on the struct definiton
* @dev Intel V3 SGX DCAP API Library: https://download.01.org/intel-sgx/sgx-dcap/1.22/linux/docs/Intel_SGX_ECDSA_QuoteLibReference_DCAP_API.pdf
* @dev Intel V4 TDX DCAP API Library: https://download.01.org/intel-sgx/sgx-dcap/1.22/linux/docs/Intel_TDX_DCAP_Quoting_Library_API.pdf
* @dev Fields that are declared as integers (uint*) must reverse the byte order to big-endian
* @dev Whereas, fields that are declared as bytes* type do not reverse the byte order
*/
/**
* @notice The Quote Header struct definition
* @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L42-L53
* @dev Section A.3 of Intel V4 TDX DCAP API Library Documentation
*/
struct Header {
uint16 version; // LE -> BE
bytes2 attestationKeyType;
bytes4 teeType;
bytes2 qeSvn;
bytes2 pceSvn;
bytes16 qeVendorId;
bytes20 userData;
}
/**
* @notice The struct definition of EnclaveReport
* @notice The Quoting Enclave (QE) Report uses this struct
* @notice Both v3 and v4 Intel SGX Quotes use this struct as the quote body
* @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L63-L80
* @dev Table 5 in Section A.4 of Intel V3 SGX DCAP API Library Documentation
* @dev Section A.3.10 of Intel V4 TDX DCAP API Library Documentation
*/
struct EnclaveReport {
bytes16 cpuSvn;
bytes4 miscSelect;
bytes28 reserved1;
bytes16 attributes;
bytes32 mrEnclave;
bytes32 reserved2;
bytes32 mrSigner;
bytes reserved3; // 96 bytes
uint16 isvProdId; // LE -> BE
uint16 isvSvn; // LE -> BE
bytes reserved4; // 60 bytes
bytes reportData; // 64 bytes - For QEReports, this contains sha256(attestation key || QEAuthData) || bytes32(0)
}
/**
* @notice The struct definition of QE Authentication Data
* @dev Table 8 in Section A.4 of Intel V3 SGX DCAP API Library Documentation
* @dev Section A.4.9 of Intel V4 TDX DCAP API Library Documentation
* @dev https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L128-L133
*/
struct QEAuthData {
uint16 parsedDataSize; // LE -> BE
bytes data;
}
/**
* @notice The struct definition of QE Certification Data
* @dev Table 9 in Section A.4 of Intel V3 SGX DCAP API Library Documentation
* @dev Section A.4.11 of Intel V4 TDX DCAP API Library Documentation
* @dev The Solidity implementation only supports certType == 5
* @dev Hence, we can safely contain the certification data as a parsed struct, rather than a raw byte array
* @dev Modified from https://github.com/intel/SGX-TDX-DCAP-QuoteVerificationLibrary/blob/16b7291a7a86e486fdfcf1dfb4be885c0cc00b4e/Src/AttestationLibrary/src/QuoteVerification/QuoteStructures.h#L135-L141
*/
struct CertificationData {
uint16 certType; // LE -> BE
uint32 certDataSize; // LE -> BE
PCKCollateral pck;
}
/// ========== CUSTOM TYPES ==========
/**
* @title PCK Certificate Collateral
* @param pckChain The Parsed PCK Certificate Chain
* @param pckExtension Parsed Intel SGX Extension from the PCK Certificate
*/
struct PCKCollateral {
X509CertObj[] pckChain;
PCKCertTCB pckExtension;
}
/**
* @title PCK Platform TCB
* @notice These are the TCB values extracted from the PCK Certificate extension
*/
struct PCKCertTCB {
uint16 pcesvn;
uint8[] cpusvns;
bytes fmspcBytes;
bytes pceidBytes;
}
/**
* @title Verified Output struct
* @notice The output returned by the contract upon successful verification of the quote
* @param quoteVersion The version of the quote
* @param tee The TEE type of the quote
* @param tcbStatus The TCB status of the quote
* @param fmspcBytes The FMSPC values
* @param quoteBody This can either be the Local ISV Report or TD10 Report, depending on the TEE type
* @param advisoryIDs The list of advisory IDs returned by the matching FMSPC TCB entry
*/
struct Output {
uint16 quoteVersion; // serialized as BE, for EVM compatibility
bytes4 tee;
TCBStatus tcbStatus;
bytes6 fmspcBytes;
bytes quoteBody;
string[] advisoryIDs;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JSONParserLib} from "solady/utils/JSONParserLib.sol";
import {LibString} from "solady/utils/LibString.sol";
import {DateTimeUtils} from "../utils/DateTimeUtils.sol";
import {BytesUtils} from "../utils/BytesUtils.sol";
// https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/e7604e02331b3377f3766ed3653250e03af72d45/QuoteVerification/QVL/Src/AttestationLibrary/src/CertVerification/X509Constants.h#L64
uint256 constant TCB_CPUSVN_SIZE = 16;
enum TcbId {
/// the "id" field is absent from TCBInfo V2
/// which defaults TcbId to SGX
/// since TDX TCBInfos are only included in V3 or above
SGX,
TDX
}
/**
* @dev This is a simple representation of the TCBInfo.json in string as a Solidity object.
* @param tcbInfo: tcbInfoJson.tcbInfo string object body
* @param signature The signature to be passed as bytes array
*/
struct TcbInfoJsonObj {
string tcbInfoStr;
bytes signature;
}
/// @dev Solidity object representing TCBInfo.json excluding TCBLevels
struct TcbInfoBasic {
/// the name "tcbType" can be confusing/misleading
/// as the tcbType referred here in this struct is the type
/// of TCB level composition that determines TCB level comparison logic
/// It is not the same as the "type" parameter passed as an argument to the
/// getTcbInfo() API method described in Section 4.2.3 of the Intel PCCS Design Document
/// Instead, getTcbInfo() "type" argument should be checked against the "id" value of this struct
/// which represents the TEE type for the given TCBInfo
uint8 tcbType;
TcbId id;
uint32 version;
uint64 issueDate;
uint64 nextUpdate;
uint32 evaluationDataNumber;
bytes6 fmspc;
bytes2 pceid;
}
struct TCBLevelsObj {
uint16 pcesvn;
uint8[] sgxComponentCpuSvns;
uint8[] tdxComponentCpuSvns;
uint64 tcbDateTimestamp;
TCBStatus status;
string[] advisoryIDs;
}
struct TDXModule {
bytes mrsigner; // 48 bytes
bytes8 attributes;
bytes8 attributesMask;
}
struct TDXModuleIdentity {
string id;
bytes8 attributes;
bytes8 attributesMask;
bytes mrsigner; // 48 bytes
TDXModuleTCBLevelsObj[] tcbLevels;
}
struct TDXModuleTCBLevelsObj {
uint8 isvsvn;
uint64 tcbDateTimestamp;
TCBStatus status;
}
enum TCBStatus {
OK,
TCB_SW_HARDENING_NEEDED,
TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED,
TCB_CONFIGURATION_NEEDED,
TCB_OUT_OF_DATE,
TCB_OUT_OF_DATE_CONFIGURATION_NEEDED,
TCB_REVOKED,
TCB_UNRECOGNIZED
}
/**
* @title FMSPC TCB Helper Contract
* @notice This is a standalone contract that can be used by off-chain applications and smart contracts
* to parse TCBInfo data
*/
contract FmspcTcbHelper {
using JSONParserLib for JSONParserLib.Item;
using LibString for string;
using BytesUtils for bytes;
error TCBInfo_Invalid();
error TCB_TDX_Version_Invalid();
error TCB_TDX_ID_Invalid();
/**
* @notice this method generates content-specific hash
* @notice in other words, we omit the "issueDate" and "nextUpdate" fields from the preimage
* @notice of the hash.
* @notice hence, this allows us to keep track of the changes made ONLY to the TCBInfo content
* @notice regardless of when the collateral is being issued and expires
*/
function generateFmspcTcbContentHash(
TcbInfoBasic memory tcbInfoContent,
string memory tcbLevelsString,
string memory tdxModuleString,
string memory tdxModuleIdentitiesString
) external pure returns (bytes32 contentHash) {
bytes memory content = abi.encodePacked(
tcbInfoContent.tcbType,
tcbInfoContent.id,
tcbInfoContent.version,
tcbInfoContent.evaluationDataNumber,
tcbInfoContent.fmspc,
tcbInfoContent.pceid,
bytes(tcbLevelsString)
);
if (bytes(tdxModuleString).length > 0) {
content = abi.encodePacked(content, bytes(tdxModuleString));
}
if (bytes(tdxModuleIdentitiesString).length > 0) {
content = abi.encodePacked(content, bytes(tdxModuleIdentitiesString));
}
contentHash = keccak256(content);
}
function tcbLevelsObjToBytes(TCBLevelsObj calldata obj) external pure returns (bytes memory serialized) {
// first slot = (uint64, uint64, uint64)
uint256 firstSlot = uint256(obj.pcesvn) << (2 * 64) | uint256(obj.tcbDateTimestamp) << 64 | uint8(obj.status);
// second slot = (padded uint16 sgxCpuSvns (16 bytes) + padded uint16 tdxCpuSvns (16 bytes))
uint256 secondSlot;
uint256 n = obj.sgxComponentCpuSvns.length;
for (uint256 i = 0; i < n;) {
uint256 v1Shift = 8 * ((2 * n) - i - 1);
secondSlot |= uint256(obj.sgxComponentCpuSvns[i]) << v1Shift;
unchecked {
i++;
}
}
if (obj.tdxComponentCpuSvns.length > 0) {
for (uint256 i = 0; i < n;) {
uint256 v2Shift = 8 * (n - i - 1);
secondSlot |= uint256(obj.tdxComponentCpuSvns[i]) << v2Shift;
unchecked {
i++;
}
}
}
// string slot = padding all advisory IDs together using '\n' as a delimiter
bytes memory stringSlot;
if (obj.advisoryIDs.length > 0) {
string memory concat = obj.advisoryIDs[0];
for (uint256 j = 1; j < obj.advisoryIDs.length; j++) {
concat = string.concat(concat, "\n", obj.advisoryIDs[j]);
}
stringSlot = bytes(concat);
}
serialized = abi.encodePacked(firstSlot, secondSlot, stringSlot);
}
function tcbLevelsObjFromBytes(bytes calldata encoded) external pure returns (TCBLevelsObj memory parsed) {
// Step 1: decode first slot
parsed.pcesvn = uint16(bytes2(encoded[14:16]));
parsed.tcbDateTimestamp = uint64(bytes8(encoded[16:24]));
parsed.status = TCBStatus(uint8(bytes1(encoded[31:32])));
// Step 2: decode second slot
parsed.sgxComponentCpuSvns = new uint8[](16);
parsed.tdxComponentCpuSvns = new uint8[](16);
bytes32 encodedSlot2 = bytes32(encoded[32:64]);
for (uint256 i = 0; i < 16;) {
if (encodedSlot2[i] != 0) {
parsed.sgxComponentCpuSvns[i] = uint8(bytes1(encodedSlot2[i]));
}
if (encodedSlot2[i + 16] != 0) {
parsed.tdxComponentCpuSvns[i] = uint8(bytes1(encodedSlot2[i + 16]));
}
unchecked {
i++;
}
}
// Step 3: decode the string
if (encoded.length > 64) {
parsed.advisoryIDs = LibString.split(string(encoded[64:encoded.length]), "\n");
}
}
function tdxModuleIdentityToBytes(TDXModuleIdentity calldata tdxModuleIdentity)
external
pure
returns (bytes memory packedTdxModuleIdentity)
{
bytes32 slot1 = LibString.packOne(tdxModuleIdentity.id);
// mrsigner is split into two slots
// first slot: contains the first 32 bytes of mrsigner
// second slot: contains the remaining 16 bytes, followed by 16 zero bytes
bytes32 slot2 = bytes32(tdxModuleIdentity.mrsigner);
bytes32 slot3 = bytes32(abi.encodePacked(slot2, tdxModuleIdentity.mrsigner.substring(32, 16)));
// Slot 4 is occupied by packing both the attributes and attributes mask
// Slot 4 = (attributes, attributesMask)
bytes32 slot4 = bytes32(tdxModuleIdentity.attributes) | bytes32(tdxModuleIdentity.attributesMask) >> 128;
// encode the tdx module array
uint256 n = tdxModuleIdentity.tcbLevels.length;
uint256[] memory tdxTcbSlots = new uint256[](n);
for (uint256 i = 0; i < n;) {
tdxTcbSlots[i] = _tdxModuleTcbLevelsObjToSlot(tdxModuleIdentity.tcbLevels[i]);
unchecked {
i++;
}
}
// total slots = 4 + n
packedTdxModuleIdentity = abi.encodePacked(slot1, slot2, slot3, slot4, abi.encodePacked(tdxTcbSlots));
}
function tdxModuleIdentityFromBytes(bytes calldata packedTdxModuleIdentity)
external
pure
returns (TDXModuleIdentity memory tdxModuleIdentity)
{
// decode slot 1
tdxModuleIdentity.id = LibString.unpackOne(bytes32(packedTdxModuleIdentity[0:32]));
// decode slots 2 and 3 to get mrsigner
tdxModuleIdentity.mrsigner = packedTdxModuleIdentity[32:80];
// decode tdx module identity tcb level array
tdxModuleIdentity.attributes = bytes8(packedTdxModuleIdentity[96:104]);
tdxModuleIdentity.attributesMask = bytes8(packedTdxModuleIdentity[112:120]);
uint256 offset = 128;
uint256 n = (packedTdxModuleIdentity.length - offset) / 32;
tdxModuleIdentity.tcbLevels = new TDXModuleTCBLevelsObj[](n);
for (uint256 i = 0; i < n;) {
uint256 end = offset + 32;
uint256 slot = uint256(bytes32(packedTdxModuleIdentity[offset:end]));
tdxModuleIdentity.tcbLevels[i] = _tdxModuleTcbLevelsObjFromSlot(slot);
offset = end;
unchecked {
i++;
}
}
}
// use bitmaps to represent the keys found in TCBInfo
// all tcb types regardless of version and tee types should have these keys described below:
// [version, issueDate, nextUpdate, fmspc, pceId, tcbType, tcbEvaluationDataNumber, tcbLevels]
// Bits are sorted in the order of the keys above from LSB to MSB
// e.g. if version is found, the bytes would look like 00000001
// e.g. if both version and fmspc were found, the bytes would look like 00001001
// the next byte contains the keys only found for V3, and TDX TCBInfos
// [id, tdxModule, tdxModuleIdentities]
uint8 constant TCB_VERSION_BIT = 1;
uint8 constant TCB_ISSUE_DATE_BIT = 2;
uint8 constant TCB_NEXT_UPDATE_BIT = 4;
uint8 constant TCB_FMSPC_BIT = 8;
uint8 constant TCB_PCEID_BIT = 16;
uint8 constant TCB_TYPE_BIT = 32;
uint8 constant TCB_EVALUATION_DATA_NUMBER_BIT = 64;
uint8 constant TCB_LEVELS_BIT = 128;
uint16 constant TCB_ID_BIT = 256;
uint16 constant TCB_TDX_MODULE_BIT = 512;
uint16 constant TCB_TDX_MODULE_IDENTITIES_BIT = 1024;
function parseTcbString(string calldata tcbInfoStr)
external
pure
returns (
TcbInfoBasic memory tcbInfo,
string memory tcbLevelsString,
string memory tdxModuleString,
string memory tdxModuleIdentitiesString
)
{
JSONParserLib.Item memory root = JSONParserLib.parse(tcbInfoStr);
JSONParserLib.Item[] memory tcbInfoObj = root.children();
uint256 f;
bool isTdx;
uint256 n = root.size();
for (uint256 i = 0; i < n;) {
JSONParserLib.Item memory current = tcbInfoObj[i];
string memory decodedKey = JSONParserLib.decodeString(current.key());
string memory val = current.value();
if (f & TCB_ID_BIT == 0 && decodedKey.eq("id")) {
string memory idStr = JSONParserLib.decodeString(val);
f |= TCB_ID_BIT;
if (idStr.eq("TDX")) {
tcbInfo.id = TcbId.TDX;
isTdx = true;
} else if (!idStr.eq("SGX")) {
revert TCBInfo_Invalid();
}
} else if (f & TCB_VERSION_BIT == 0 && decodedKey.eq("version")) {
tcbInfo.version = uint32(JSONParserLib.parseUint(val));
f |= TCB_VERSION_BIT;
if (tcbInfo.version < 3) {
f |= TCB_ID_BIT;
}
} else if (f & TCB_ISSUE_DATE_BIT == 0 && decodedKey.eq("issueDate")) {
tcbInfo.issueDate = uint64(DateTimeUtils.fromISOToTimestamp(JSONParserLib.decodeString(val)));
f |= TCB_ISSUE_DATE_BIT;
} else if (f & TCB_NEXT_UPDATE_BIT == 0 && decodedKey.eq("nextUpdate")) {
tcbInfo.nextUpdate = uint64(DateTimeUtils.fromISOToTimestamp(JSONParserLib.decodeString(val)));
f |= TCB_NEXT_UPDATE_BIT;
} else if (f & TCB_FMSPC_BIT == 0 && decodedKey.eq("fmspc")) {
tcbInfo.fmspc = bytes6(uint48(JSONParserLib.parseUintFromHex(JSONParserLib.decodeString(val))));
f |= TCB_FMSPC_BIT;
} else if (f & TCB_PCEID_BIT == 0 && decodedKey.eq("pceId")) {
tcbInfo.pceid = bytes2(uint16(JSONParserLib.parseUintFromHex(JSONParserLib.decodeString(val))));
f |= TCB_PCEID_BIT;
} else if (f & TCB_TYPE_BIT == 0 && decodedKey.eq("tcbType")) {
tcbInfo.tcbType = uint8(JSONParserLib.parseUint(val));
f |= TCB_TYPE_BIT;
} else if (f & TCB_EVALUATION_DATA_NUMBER_BIT == 0 && decodedKey.eq("tcbEvaluationDataNumber")) {
tcbInfo.evaluationDataNumber = uint32(JSONParserLib.parseUint(val));
f |= TCB_EVALUATION_DATA_NUMBER_BIT;
} else if (
tcbInfo.version > 2 && isTdx && (f & TCB_TDX_MODULE_BIT == 0 || f & TCB_TDX_MODULE_IDENTITIES_BIT == 0)
) {
if (f & TCB_TDX_MODULE_BIT == 0 && decodedKey.eq("tdxModule")) {
tdxModuleString = val;
f |= TCB_TDX_MODULE_BIT;
} else if (f & TCB_TDX_MODULE_IDENTITIES_BIT == 0 && decodedKey.eq("tdxModuleIdentities")) {
tdxModuleIdentitiesString = val;
f |= TCB_TDX_MODULE_IDENTITIES_BIT;
}
} else if (f & TCB_LEVELS_BIT == 0 && decodedKey.eq("tcbLevels")) {
tcbLevelsString = val;
f |= TCB_LEVELS_BIT;
}
unchecked {
i++;
}
}
// v2 tcbinfo does not explicitly have the "id" field
// but we set the bit to 1 anyway to save gas by skipping the check
// incrementing n prevents from the "id" bit to be set to 0 by masking
if (tcbInfo.version < 3) {
n++;
}
bool allFound = f == (2 ** n) - 1;
if (!allFound) {
revert TCBInfo_Invalid();
}
}
function parseTcbLevels(uint256 version, string calldata tcbLevelsString)
external
pure
returns (TCBLevelsObj[] memory tcbLevels)
{
JSONParserLib.Item memory root = JSONParserLib.parse(tcbLevelsString);
JSONParserLib.Item[] memory tcbLevelsObj = root.children();
uint256 tcbLevelsSize = tcbLevelsObj.length;
tcbLevels = new TCBLevelsObj[](tcbLevelsSize);
// iterating through the array
for (uint256 i = 0; i < tcbLevelsSize; i++) {
JSONParserLib.Item[] memory tcbObj = tcbLevelsObj[i].children();
// iterating through individual tcb objects
for (uint256 j = 0; j < tcbLevelsObj[i].size(); j++) {
string memory tcbKey = JSONParserLib.decodeString(tcbObj[j].key());
if (tcbKey.eq("tcb")) {
string memory tcbStr = tcbObj[j].value();
JSONParserLib.Item memory tcbParent = JSONParserLib.parse(tcbStr);
JSONParserLib.Item[] memory tcbComponents = tcbParent.children();
if (version == 2) {
(tcbLevels[i].sgxComponentCpuSvns, tcbLevels[i].pcesvn) = _parseV2Tcb(tcbComponents);
} else if (version == 3) {
(tcbLevels[i].sgxComponentCpuSvns, tcbLevels[i].tdxComponentCpuSvns, tcbLevels[i].pcesvn) =
_parseV3Tcb(tcbComponents);
} else {
revert TCBInfo_Invalid();
}
} else if (tcbKey.eq("tcbDate")) {
tcbLevels[i].tcbDateTimestamp =
uint64(DateTimeUtils.fromISOToTimestamp(JSONParserLib.decodeString(tcbObj[j].value())));
} else if (tcbKey.eq("tcbStatus")) {
tcbLevels[i].status = _getTcbStatus(JSONParserLib.decodeString(tcbObj[j].value()));
} else if (tcbKey.eq("advisoryIDs")) {
JSONParserLib.Item[] memory advisoryArr = tcbObj[j].children();
uint256 n = tcbObj[j].size();
tcbLevels[i].advisoryIDs = new string[](n);
for (uint256 k = 0; k < n; k++) {
tcbLevels[i].advisoryIDs[k] = JSONParserLib.decodeString(advisoryArr[k].value());
}
}
}
}
}
function parseTcbTdxModules(string calldata tdxModuleString, string calldata tdxModuleIdentitiesString)
external
pure
returns (TDXModule memory module, TDXModuleIdentity[] memory moduleIdentities)
{
JSONParserLib.Item memory tdxModuleRoot = JSONParserLib.parse(tdxModuleString);
JSONParserLib.Item[] memory tdxModuleItems = tdxModuleRoot.children();
JSONParserLib.Item memory tdxModuleIdentitiesRoot = JSONParserLib.parse(tdxModuleIdentitiesString);
JSONParserLib.Item[] memory tdxModuleIdentitiesItems = tdxModuleIdentitiesRoot.children();
module = _parseTdxModule(tdxModuleItems);
moduleIdentities = _parseTdxModuleIdentities(tdxModuleIdentitiesItems);
}
/// ====== INTERNAL METHODS BELOW ======
function _tdxModuleTcbLevelsObjToSlot(TDXModuleTCBLevelsObj memory tdxModuleTcbLevelsObj)
private
pure
returns (uint256 tdxTcbPacked)
{
// tcb levels within tdx module can be packed into a single slot
// (uint64 packedIsvsvn, uint64 packedTcbDateTimestamp, uint64 packedStatus)
tdxTcbPacked = uint256(tdxModuleTcbLevelsObj.isvsvn) << (2 * 64)
| uint256(tdxModuleTcbLevelsObj.tcbDateTimestamp) << 64 | uint8(tdxModuleTcbLevelsObj.status);
}
function _tdxModuleTcbLevelsObjFromSlot(uint256 tdxTcbPacked)
private
pure
returns (TDXModuleTCBLevelsObj memory tdxModuleTcbLevelsObj)
{
uint64 mask = 0xFFFFFFFFFFFFFFFF;
tdxModuleTcbLevelsObj.status = TCBStatus(uint8(uint64(tdxTcbPacked & mask)));
tdxModuleTcbLevelsObj.tcbDateTimestamp = uint64((tdxTcbPacked >> 64) & mask);
tdxModuleTcbLevelsObj.isvsvn = uint8(uint64((tdxTcbPacked >> 128) & mask));
}
function _getTcbStatus(string memory statusStr) private pure returns (TCBStatus status) {
if (statusStr.eq("UpToDate")) {
status = TCBStatus.OK;
} else if (statusStr.eq("OutOfDate")) {
status = TCBStatus.TCB_OUT_OF_DATE;
} else if (statusStr.eq("OutOfDateConfigurationNeeded")) {
status = TCBStatus.TCB_OUT_OF_DATE_CONFIGURATION_NEEDED;
} else if (statusStr.eq("ConfigurationNeeded")) {
status = TCBStatus.TCB_CONFIGURATION_NEEDED;
} else if (statusStr.eq("ConfigurationAndSWHardeningNeeded")) {
status = TCBStatus.TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED;
} else if (statusStr.eq("SWHardeningNeeded")) {
status = TCBStatus.TCB_SW_HARDENING_NEEDED;
} else if (statusStr.eq("Revoked")) {
status = TCBStatus.TCB_REVOKED;
} else {
status = TCBStatus.TCB_UNRECOGNIZED;
}
}
function _parseV2Tcb(JSONParserLib.Item[] memory tcbComponents)
private
pure
returns (uint8[] memory sgxComponentCpuSvns, uint16 pcesvn)
{
sgxComponentCpuSvns = new uint8[](TCB_CPUSVN_SIZE);
uint256 cpusvnCounter = 0;
for (uint256 i = 0; i < tcbComponents.length; i++) {
string memory key = JSONParserLib.decodeString(tcbComponents[i].key());
uint256 value = JSONParserLib.parseUint(tcbComponents[i].value());
if (key.eq("pcesvn")) {
pcesvn = uint16(value);
} else {
sgxComponentCpuSvns[cpusvnCounter++] = uint8(value);
}
}
if (cpusvnCounter != TCB_CPUSVN_SIZE) {
revert TCBInfo_Invalid();
}
}
function _parseV3Tcb(JSONParserLib.Item[] memory tcbComponents)
private
pure
returns (uint8[] memory sgxComponentCpuSvns, uint8[] memory tdxComponentCpuSvns, uint16 pcesvn)
{
sgxComponentCpuSvns = new uint8[](TCB_CPUSVN_SIZE);
tdxComponentCpuSvns = new uint8[](TCB_CPUSVN_SIZE);
for (uint256 i = 0; i < tcbComponents.length; i++) {
string memory key = JSONParserLib.decodeString(tcbComponents[i].key());
if (key.eq("pcesvn")) {
pcesvn = uint16(JSONParserLib.parseUint(tcbComponents[i].value()));
} else {
string memory componentKey = key;
JSONParserLib.Item[] memory componentArr = tcbComponents[i].children();
uint256 cpusvnCounter = 0;
for (uint256 j = 0; j < tcbComponents[i].size(); j++) {
JSONParserLib.Item[] memory component = componentArr[j].children();
for (uint256 k = 0; k < componentArr[j].size(); k++) {
key = JSONParserLib.decodeString(component[k].key());
if (key.eq("svn")) {
if (componentKey.eq("tdxtcbcomponents")) {
tdxComponentCpuSvns[cpusvnCounter++] =
uint8(JSONParserLib.parseUint(component[k].value()));
} else {
sgxComponentCpuSvns[cpusvnCounter++] =
uint8(JSONParserLib.parseUint(component[k].value()));
}
}
}
}
if (cpusvnCounter != TCB_CPUSVN_SIZE) {
revert TCBInfo_Invalid();
}
}
}
}
function _parseTdxModule(JSONParserLib.Item[] memory tdxModuleObj) private pure returns (TDXModule memory module) {
for (uint256 i = 0; i < tdxModuleObj.length; i++) {
string memory key = JSONParserLib.decodeString(tdxModuleObj[i].key());
string memory val = JSONParserLib.decodeString(tdxModuleObj[i].value());
if (key.eq("attributes")) {
module.attributes = bytes8(uint64(JSONParserLib.parseUintFromHex(val)));
}
if (key.eq("attributesMask")) {
module.attributesMask = bytes8(uint64(JSONParserLib.parseUintFromHex(val)));
}
if (key.eq("mrsigner")) {
module.mrsigner = _getMrSignerHex(val);
}
}
}
function _parseTdxModuleIdentities(JSONParserLib.Item[] memory tdxModuleIdentitiesArr)
private
pure
returns (TDXModuleIdentity[] memory identities)
{
uint256 n = tdxModuleIdentitiesArr.length;
identities = new TDXModuleIdentity[](n);
for (uint256 i = 0; i < n; i++) {
JSONParserLib.Item[] memory currIdentity = tdxModuleIdentitiesArr[i].children();
for (uint256 j = 0; j < tdxModuleIdentitiesArr[i].size(); j++) {
string memory key = JSONParserLib.decodeString(currIdentity[j].key());
if (key.eq("id")) {
string memory val = JSONParserLib.decodeString(currIdentity[j].value());
identities[i].id = val;
}
if (key.eq("mrsigner")) {
string memory val = JSONParserLib.decodeString(currIdentity[j].value());
identities[i].mrsigner = _getMrSignerHex(val);
}
if (key.eq("attributes")) {
string memory val = JSONParserLib.decodeString(currIdentity[j].value());
identities[i].attributes = bytes8(uint64(JSONParserLib.parseUintFromHex(val)));
}
if (key.eq("attributesMask")) {
string memory val = JSONParserLib.decodeString(currIdentity[j].value());
identities[i].attributesMask = bytes8(uint64(JSONParserLib.parseUintFromHex(val)));
}
if (key.eq("tcbLevels")) {
JSONParserLib.Item[] memory tcbLevelsArr = currIdentity[j].children();
uint256 x = tcbLevelsArr.length;
identities[i].tcbLevels = new TDXModuleTCBLevelsObj[](x);
for (uint256 k = 0; k < x; k++) {
JSONParserLib.Item[] memory tcb = tcbLevelsArr[k].children();
for (uint256 l = 0; l < tcb.length; l++) {
key = JSONParserLib.decodeString(tcb[l].key());
if (key.eq("tcb")) {
JSONParserLib.Item[] memory isvsvnObj = tcb[l].children();
key = JSONParserLib.decodeString(isvsvnObj[0].key());
if (key.eq("isvsvn")) {
identities[i].tcbLevels[k].isvsvn =
uint8(JSONParserLib.parseUint(isvsvnObj[0].value()));
} else {
revert TCBInfo_Invalid();
}
}
if (key.eq("tcbDate")) {
identities[i].tcbLevels[k].tcbDateTimestamp =
uint64(DateTimeUtils.fromISOToTimestamp(JSONParserLib.decodeString(tcb[l].value())));
}
if (key.eq("tcbStatus")) {
identities[i].tcbLevels[k].status =
_getTcbStatus(JSONParserLib.decodeString(tcb[l].value()));
}
}
}
}
}
}
}
function _getMrSignerHex(string memory mrSignerStr) private pure returns (bytes memory mrSignerBytes) {
string memory mrSignerUpper16BytesStr = mrSignerStr.slice(0, 16);
string memory mrSignerLower32BytesStr = mrSignerStr.slice(16, 48);
uint256 mrSignerUpperBytes = JSONParserLib.parseUintFromHex(mrSignerUpper16BytesStr);
uint256 mrSignerLowerBytes = JSONParserLib.parseUintFromHex(mrSignerLower32BytesStr);
mrSignerBytes = abi.encodePacked(uint128(mrSignerUpperBytes), mrSignerLowerBytes);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Asn1Decode, NodePtr} from "../utils/Asn1Decode.sol";
import {BytesUtils} from "../utils/BytesUtils.sol";
import {DateTimeUtils} from "../utils/DateTimeUtils.sol";
/**
* @title Solidity Structure representing X509 Certificates
* @notice This is a simplified structure of a DER-decoded X509 Certificate
*/
struct X509CertObj {
uint256 serialNumber;
string issuerCommonName;
uint256 validityNotBefore;
uint256 validityNotAfter;
string subjectCommonName;
bytes subjectPublicKey;
// the extension needs to be parsed further for PCK Certificates
uint256 extensionPtr;
bytes authorityKeyIdentifier;
bytes subjectKeyIdentifier;
// for signature verification in the cert chain
bytes signature;
bytes tbs;
}
// 2.5.4.3
bytes constant COMMON_NAME_OID = hex"550403";
// 2.5.29.35
bytes constant AUTHORITY_KEY_IDENTIFIER_OID = hex"551D23";
// 2.5.29.14
bytes constant SUBJECT_KEY_IDENTIFIER_OID = hex"551D0E";
/**
* @title X509 Certificates Helper Contract
* @notice This is a standalone contract that can be used by off-chain applications and smart contracts
* to parse DER-encoded X509 certificates.
* @dev This parser is only valid for ECDSA signature algorithm and p256 key algorithm.
*/
contract X509Helper {
using Asn1Decode for bytes;
using NodePtr for uint256;
using BytesUtils for bytes;
/// =================================================================================
/// USE THE GETTERS BELOW IF YOU DON'T WANT TO PARSE THE ENTIRE X509 CERTIFICATE
/// =================================================================================
function getTbsAndSig(bytes calldata der) external pure returns (bytes memory tbs, bytes memory sig) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 sigPtr = der.nextSiblingOf(tbsParentPtr);
sigPtr = der.nextSiblingOf(sigPtr);
tbs = der.allBytesAt(tbsParentPtr);
sig = _getSignature(der, sigPtr);
}
function getSerialNumber(bytes calldata der) external pure returns (uint256 serialNum) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
serialNum = _parseSerialNumber(der, tbsPtr);
}
function getIssuerCommonName(bytes calldata der) external pure returns (string memory issuerCommonName) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
issuerCommonName = _getCommonName(der, tbsPtr);
}
function getCertValidity(bytes calldata der)
external
pure
returns (uint256 validityNotBefore, uint256 validityNotAfter)
{
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
(validityNotBefore, validityNotAfter) = _getValidity(der, tbsPtr);
}
function getSubjectCommonName(bytes calldata der) external pure returns (string memory subjectCommonName) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
subjectCommonName = _getCommonName(der, tbsPtr);
}
function getSubjectPublicKey(bytes calldata der) external pure returns (bytes memory pubKey) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
pubKey = _getSubjectPublicKey(der, der.firstChildOf(tbsPtr));
}
function getExtensionPtr(bytes calldata der) external pure returns (uint256 extensionPtr) {
extensionPtr = _getExtensionPtr(der);
}
/// @dev according to RFC 5280, the Authority Key Identifier is mandatory for CA certificates
/// @dev if not present, this method returns 0x00
function getAuthorityKeyIdentifier(bytes calldata der) external pure returns (bytes memory akid) {
uint256 extensionPtr = _getExtensionPtr(der);
uint256 extnValuePtr = _findExtensionValuePtr(der, extensionPtr, AUTHORITY_KEY_IDENTIFIER_OID);
if (extnValuePtr != 0) {
akid = _getAuthorityKeyIdentifier(der, extnValuePtr);
}
}
/// @dev according to RFC 5280, the Subject Key Identifier is RECOMMENDED for CA certificates
/// @dev Intel DCAP attestation certificates contain this extension
/// @dev this value can be useful for checking CRLs without performing signature verification, which can be costly in terms of gas
/// @dev we can simply use this value to check against the CRL's authority key identifier
/// @dev if not present, this method returns 0x00
function getSubjectKeyIdentifier(bytes calldata der) external pure returns (bytes memory skid) {
uint256 extensionPtr = _getExtensionPtr(der);
uint256 extValuePtr = _findExtensionValuePtr(der, extensionPtr, SUBJECT_KEY_IDENTIFIER_OID);
if (extValuePtr != 0) {
skid = _getSubjectKeyIdentifier(der, extValuePtr);
}
}
/// x509 Certificates generally contain a sequence of elements in the following order:
/// 1. tbs
/// - 1a. version
/// - 1b. serial number
/// - 1c. siganture algorithm
/// - 1d. issuer
/// - - 1d(a). common name
/// - - 1d(b). organization name
/// - - 1d(c). locality name
/// - - 1d(d). state or province name
/// - - 1d(e). country name
/// - 1e. validity
/// - - 1e(a) notBefore
/// - - 1e(b) notAfter
/// - 1f. subject
/// - - contains the same set of elements as 1d
/// - 1g. subject public key info
/// - - 1g(a). algorithm
/// - - 1g(b). subject public key
/// - 1h. Extensions
/// 2. Signature Algorithm
/// 3. Signature
function parseX509DER(bytes calldata der) external pure returns (X509CertObj memory cert) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
cert.tbs = der.allBytesAt(tbsParentPtr);
uint256 tbsPtr = der.firstChildOf(tbsParentPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
cert.serialNumber = _parseSerialNumber(der, tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
cert.issuerCommonName = _getCommonName(der, tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
(cert.validityNotBefore, cert.validityNotAfter) = _getValidity(der, tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
cert.subjectCommonName = _getCommonName(der, tbsPtr);
tbsPtr = der.nextSiblingOf(tbsPtr);
cert.subjectPublicKey = _getSubjectPublicKey(der, der.firstChildOf(tbsPtr));
uint256 extensionPtr = der.nextSiblingOf(tbsPtr);
if (bytes1(der[extensionPtr.ixs()]) == 0xA3) {
cert.extensionPtr = extensionPtr;
uint256 authorityKeyIdentifierPtr = _findExtensionValuePtr(der, extensionPtr, AUTHORITY_KEY_IDENTIFIER_OID);
if (authorityKeyIdentifierPtr != 0) {
cert.authorityKeyIdentifier = _getAuthorityKeyIdentifier(der, authorityKeyIdentifierPtr);
}
uint256 subjectKeyIdentifierPtr = _findExtensionValuePtr(der, extensionPtr, SUBJECT_KEY_IDENTIFIER_OID);
if (subjectKeyIdentifierPtr != 0) {
cert.subjectKeyIdentifier = _getSubjectKeyIdentifier(der, subjectKeyIdentifierPtr);
}
} else {
revert("Extension is missing");
}
// tbs iteration completed
// now we just need to look for the signature
uint256 sigPtr = der.nextSiblingOf(tbsParentPtr);
sigPtr = der.nextSiblingOf(sigPtr);
cert.signature = _getSignature(der, sigPtr);
}
function _parseSerialNumber(bytes calldata der, uint256 serialNumberPtr) private pure returns (uint256 serial) {
require(bytes1(der[serialNumberPtr.ixs()]) == 0x02, "not an integer");
bytes memory serialBytes = der.bytesAt(serialNumberPtr);
uint256 shift = 8 * (32 - serialBytes.length);
serial = uint256(bytes32(serialBytes) >> shift);
}
function _getCommonName(bytes calldata der, uint256 rdnParentPtr) private pure returns (string memory) {
// All we are doing here is iterating through a sequence of
// one or many RelativeDistinguishedName (RDN) sets
// which consists of one or many AttributeTypeAndValue sequences
// we are only interested in the sequence with the CommonName type
uint256 rdnPtr = der.firstChildOf(rdnParentPtr);
bool commonNameFound = false;
while (rdnPtr != 0) {
uint256 sequencePtr = der.firstChildOf(rdnPtr);
while (sequencePtr.ixl() <= rdnPtr.ixl()) {
uint256 oidPtr = der.firstChildOf(sequencePtr);
if (BytesUtils.compareBytes(der.bytesAt(oidPtr), COMMON_NAME_OID)) {
commonNameFound = true;
return string(der.bytesAt(der.nextSiblingOf(oidPtr)));
} else if (sequencePtr.ixl() == rdnPtr.ixl()) {
break;
} else {
sequencePtr = der.nextSiblingOf(sequencePtr);
}
}
if (rdnPtr.ixl() < rdnParentPtr.ixl()) {
rdnPtr = der.nextSiblingOf(rdnPtr);
} else {
rdnPtr = 0;
}
}
if (!commonNameFound) {
revert("Missing common name");
}
}
function _getValidity(bytes calldata der, uint256 validityPtr)
private
pure
returns (uint256 notBefore, uint256 notAfter)
{
uint256 notBeforePtr = der.firstChildOf(validityPtr);
uint256 notAfterPtr = der.nextSiblingOf(notBeforePtr);
notBefore = DateTimeUtils.fromDERToTimestamp(der.bytesAt(notBeforePtr));
notAfter = DateTimeUtils.fromDERToTimestamp(der.bytesAt(notAfterPtr));
}
function _getSubjectPublicKey(bytes calldata der, uint256 subjectPublicKeyInfoPtr)
private
pure
returns (bytes memory pubKey)
{
subjectPublicKeyInfoPtr = der.nextSiblingOf(subjectPublicKeyInfoPtr);
pubKey = der.bitstringAt(subjectPublicKeyInfoPtr);
if (pubKey.length != 65) {
// TODO: we need to figure out how to handle key with prefix byte 0x02 or 0x03
revert("compressed public key not supported");
}
pubKey = _trimBytes(pubKey, 64);
}
function _getAuthorityKeyIdentifier(bytes calldata der, uint256 extnValuePtr)
private
pure
returns (bytes memory akid)
{
bytes memory extValue = der.bytesAt(extnValuePtr);
// The AUTHORITY_KEY_IDENTIFIER consists of a SEQUENCE with the following elements
// [0] - keyIdentifier (ESSENTIAL, but OPTIONAL as per RFC 5280)
// [1] - authorityCertIssuer (OPTIONAL as per RFC 5280)
// [2] - authorityCertSerialNumber (OPTIONAL as per RFC 5280)
// since we are interested in only the key identifier
// we iterate through the sequence until we find a tag matches with [0]
uint256 parentPtr = extValue.root();
uint256 ptr = extValue.firstChildOf(parentPtr);
bytes1 contextTag = 0x80;
while (true) {
bytes1 tag = bytes1(extValue[ptr.ixs()]);
if (tag == contextTag) {
akid = extValue.bytesAt(ptr);
break;
}
if (ptr.ixl() < parentPtr.ixl()) {
ptr = extValue.nextSiblingOf(ptr);
} else {
break;
}
}
}
function _getSubjectKeyIdentifier(bytes calldata der, uint256 extValuePtr)
private
pure
returns (bytes memory skid)
{
// The SUBJECT_KEY_IDENTIFIER simply consists of the KeyIdentifier of Octet String type (0x04)
// so we can return the value as it is
// check octet string tag
require(der[extValuePtr.ixf()] == 0x04, "keyIdentifier must be of OctetString type");
uint8 length = uint8(bytes1(der[extValuePtr.ixf() + 1]));
skid = der[extValuePtr.ixf() + 2:extValuePtr.ixf() + 2 + length];
}
function _getSignature(bytes calldata der, uint256 sigPtr) private pure returns (bytes memory sig) {
sigPtr = der.rootOfBitStringAt(sigPtr);
sigPtr = der.firstChildOf(sigPtr);
bytes memory r = _trimBytes(der.bytesAt(sigPtr), 32);
sigPtr = der.nextSiblingOf(sigPtr);
bytes memory s = _trimBytes(der.bytesAt(sigPtr), 32);
sig = abi.encodePacked(r, s);
}
/// @dev remove unnecessary prefix from the input
function _trimBytes(bytes memory input, uint256 expectedLength) private pure returns (bytes memory output) {
uint256 n = input.length;
if (n == expectedLength) {
output = input;
} else if (n < expectedLength) {
output = new bytes(expectedLength);
uint256 padLength = expectedLength - n;
for (uint256 i = 0; i < n; i++) {
output[padLength + i] = input[i];
}
} else {
uint256 lengthDiff = n - expectedLength;
output = input.substring(lengthDiff, expectedLength);
}
}
function _getExtensionPtr(bytes calldata der) private pure returns (uint256 extensionPtr) {
uint256 root = der.root();
uint256 tbsParentPtr = der.firstChildOf(root);
extensionPtr = der.firstChildOf(tbsParentPtr);
// iterate through the sequence until we find the extension tag (0xA3)
while (extensionPtr.ixl() <= tbsParentPtr.ixl()) {
bytes1 tag = bytes1(der[extensionPtr.ixs()]);
if (tag == 0xA3) {
return extensionPtr;
} else {
if (extensionPtr.ixl() == tbsParentPtr.ixl()) {
revert("Extension is missing");
} else {
extensionPtr = der.nextSiblingOf(extensionPtr);
}
}
}
}
function _findExtensionValuePtr(bytes calldata der, uint256 extensionPtr, bytes memory oid)
private
pure
returns (uint256)
{
uint256 parentPtr = der.firstChildOf(extensionPtr);
uint256 ptr = der.firstChildOf(parentPtr);
while (ptr != 0) {
uint256 oidPtr = der.firstChildOf(ptr);
if (der[oidPtr.ixs()] != 0x06) {
revert("Missing OID");
}
if (BytesUtils.compareBytes(der.bytesAt(oidPtr), oid)) {
return der.nextSiblingOf(oidPtr);
}
if (ptr.ixl() < parentPtr.ixl()) {
ptr = der.nextSiblingOf(ptr);
} else {
ptr = 0;
}
}
return 0; // not found
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for parsing JSONs.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/JSONParserLib.sol)
library JSONParserLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The input is invalid.
error ParsingFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// There are 6 types of variables in JSON (excluding undefined).
/// @dev For denoting that an item has not been initialized.
/// A item returned from `parse` will never be of an undefined type.
/// Parsing a invalid JSON string will simply revert.
uint8 internal constant TYPE_UNDEFINED = 0;
/// @dev Type representing an array (e.g. `[1,2,3]`).
uint8 internal constant TYPE_ARRAY = 1;
/// @dev Type representing an object (e.g. `{"a":"A","b":"B"}`).
uint8 internal constant TYPE_OBJECT = 2;
/// @dev Type representing a number (e.g. `-1.23e+21`).
uint8 internal constant TYPE_NUMBER = 3;
/// @dev Type representing a string (e.g. `"hello"`).
uint8 internal constant TYPE_STRING = 4;
/// @dev Type representing a boolean (i.e. `true` or `false`).
uint8 internal constant TYPE_BOOLEAN = 5;
/// @dev Type representing null (i.e. `null`).
uint8 internal constant TYPE_NULL = 6;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev A pointer to a parsed JSON node.
struct Item {
// Do NOT modify the `_data` directly.
uint256 _data;
}
// Private constants for packing `_data`.
uint256 private constant _BITPOS_STRING = 32 * 7 - 8;
uint256 private constant _BITPOS_KEY_LENGTH = 32 * 6 - 8;
uint256 private constant _BITPOS_KEY = 32 * 5 - 8;
uint256 private constant _BITPOS_VALUE_LENGTH = 32 * 4 - 8;
uint256 private constant _BITPOS_VALUE = 32 * 3 - 8;
uint256 private constant _BITPOS_CHILD = 32 * 2 - 8;
uint256 private constant _BITPOS_SIBLING_OR_PARENT = 32 * 1 - 8;
uint256 private constant _BITMASK_POINTER = 0xffffffff;
uint256 private constant _BITMASK_TYPE = 7;
uint256 private constant _KEY_INITED = 1 << 3;
uint256 private constant _VALUE_INITED = 1 << 4;
uint256 private constant _CHILDREN_INITED = 1 << 5;
uint256 private constant _PARENT_IS_ARRAY = 1 << 6;
uint256 private constant _PARENT_IS_OBJECT = 1 << 7;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* JSON PARSING OPERATION */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Parses the JSON string `s`, and returns the root.
/// Reverts if `s` is not a valid JSON as specified in RFC 8259.
/// Object items WILL simply contain all their children, inclusive of repeated keys,
/// in the same order which they appear in the JSON string.
///
/// Note: For efficiency, this function WILL NOT make a copy of `s`.
/// The parsed tree WILL contain offsets to `s`.
/// Do NOT pass in a string that WILL be modified later on.
function parse(string memory s) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // We will use our own allocation instead.
}
bytes32 r = _query(_toInput(s), 255);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* JSON ITEM OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note:
// - An item is a node in the JSON tree.
// - The value of a string item WILL be double-quoted, JSON encoded.
// - We make a distinction between `index` and `key`.
// - Items in arrays are located by `index` (uint256).
// - Items in objects are located by `key` (string).
// - Keys are always strings, double-quoted, JSON encoded.
//
// These design choices are made to balance between efficiency and ease-of-use.
/// @dev Returns the string value of the item.
/// This is its exact string representation in the original JSON string.
/// The returned string WILL have leading and trailing whitespace trimmed.
/// All inner whitespace WILL be preserved, exactly as it is in the original JSON string.
/// If the item's type is string, the returned string WILL be double-quoted, JSON encoded.
///
/// Note: This function lazily instantiates and caches the returned string.
/// Do NOT modify the returned string.
function value(Item memory item) internal pure returns (string memory result) {
bytes32 r = _query(_toInput(item), 0);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/// @dev Returns the index of the item in the array.
/// It the item's parent is not an array, returns 0.
function index(Item memory item) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if and(mload(item), _PARENT_IS_ARRAY) {
result := and(_BITMASK_POINTER, shr(_BITPOS_KEY, mload(item)))
}
}
}
/// @dev Returns the key of the item in the object.
/// It the item's parent is not an object, returns an empty string.
/// The returned string WILL be double-quoted, JSON encoded.
///
/// Note: This function lazily instantiates and caches the returned string.
/// Do NOT modify the returned string.
function key(Item memory item) internal pure returns (string memory result) {
if (item._data & _PARENT_IS_OBJECT != 0) {
bytes32 r = _query(_toInput(item), 1);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
}
/// @dev Returns the key of the item in the object.
/// It the item is neither an array nor object, returns an empty array.
///
/// Note: This function lazily instantiates and caches the returned array.
/// Do NOT modify the returned array.
function children(Item memory item) internal pure returns (Item[] memory result) {
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/// @dev Returns the number of children.
/// It the item is neither an array nor object, returns zero.
function size(Item memory item) internal pure returns (uint256 result) {
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := mload(r)
}
}
/// @dev Returns the item at index `i` for (array).
/// If `item` is not an array, the result's type WILL be undefined.
/// If there is no item with the index, the result's type WILL be undefined.
function at(Item memory item, uint256 i) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We'll allocate manually.
}
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(r, 0x20), shl(5, i)))
if iszero(and(lt(i, mload(r)), eq(and(mload(item), _BITMASK_TYPE), TYPE_ARRAY))) {
result := 0x60 // Reset to the zero pointer.
}
}
}
/// @dev Returns the item at key `k` for (object).
/// If `item` is not an object, the result's type WILL be undefined.
/// The key MUST be double-quoted, JSON encoded. This is for efficiency reasons.
/// - Correct : `item.at('"k"')`.
/// - Wrong : `item.at("k")`.
/// For duplicated keys, the last item with the key WILL be returned.
/// If there is no item with the key, the result's type WILL be undefined.
function at(Item memory item, string memory k) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We'll allocate manually.
result := 0x60 // Initialize to the zero pointer.
}
if (isObject(item)) {
bytes32 kHash = keccak256(bytes(k));
Item[] memory r = children(item);
// We'll just do a linear search. The alternatives are very bloated.
for (uint256 i = r.length << 5; i != 0;) {
/// @solidity memory-safe-assembly
assembly {
item := mload(add(r, i))
i := sub(i, 0x20)
}
if (keccak256(bytes(key(item))) != kHash) continue;
result = item;
break;
}
}
}
/// @dev Returns the item's type.
function getType(Item memory item) internal pure returns (uint8 result) {
result = uint8(item._data & _BITMASK_TYPE);
}
/// Note: All types are mutually exclusive.
/// @dev Returns whether the item is of type undefined.
function isUndefined(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_UNDEFINED;
}
/// @dev Returns whether the item is of type array.
function isArray(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_ARRAY;
}
/// @dev Returns whether the item is of type object.
function isObject(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_OBJECT;
}
/// @dev Returns whether the item is of type number.
function isNumber(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_NUMBER;
}
/// @dev Returns whether the item is of type string.
function isString(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_STRING;
}
/// @dev Returns whether the item is of type boolean.
function isBoolean(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_BOOLEAN;
}
/// @dev Returns whether the item is of type null.
function isNull(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_NULL;
}
/// @dev Returns the item's parent.
/// If the item does not have a parent, the result's type will be undefined.
function parent(Item memory item) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We've already allocated.
result := and(shr(_BITPOS_SIBLING_OR_PARENT, mload(item)), _BITMASK_POINTER)
if iszero(result) { result := 0x60 } // Reset to the zero pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UTILITY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Parses an unsigned integer from a string (in decimal, i.e. base 10).
/// Reverts if `s` is not a valid uint256 string matching the RegEx `^[0-9]+$`,
/// or if the parsed number is too big for a uint256.
function parseUint(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let preMulOverflowThres := div(not(0), 10)
for { let i := 0 } 1 {} {
i := add(i, 1)
let digit := sub(and(mload(add(s, i)), 0xff), 48)
let mulOverflowed := gt(result, preMulOverflowThres)
let product := mul(10, result)
result := add(product, digit)
n := mul(n, iszero(or(or(mulOverflowed, lt(result, product)), gt(digit, 9))))
if iszero(lt(i, n)) { break }
}
if iszero(n) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Parses a signed integer from a string (in decimal, i.e. base 10).
/// Reverts if `s` is not a valid int256 string matching the RegEx `^[+-]?[0-9]+$`,
/// or if the parsed number is too big for a int256.
function parseInt(string memory s) internal pure returns (int256 result) {
uint256 n = bytes(s).length;
uint256 sign;
uint256 isNegative;
/// @solidity memory-safe-assembly
assembly {
if n {
let c := and(mload(add(s, 1)), 0xff)
isNegative := eq(c, 45)
if or(eq(c, 43), isNegative) {
sign := c
s := add(s, 1)
mstore(s, sub(n, 1))
}
if iszero(or(sign, lt(sub(c, 48), 10))) { s := 0x60 }
}
}
uint256 x = parseUint(s);
/// @solidity memory-safe-assembly
assembly {
if shr(255, x) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
if sign {
mstore(s, sign)
s := sub(s, 1)
mstore(s, n)
}
result := xor(x, mul(xor(x, add(not(x), 1)), isNegative))
}
}
/// @dev Parses an unsigned integer from a string (in hexadecimal, i.e. base 16).
/// Reverts if `s` is not a valid uint256 hex string matching the RegEx
/// `^(0[xX])?[0-9a-fA-F]+$`, or if the parsed number is too big for a uint256.
function parseUintFromHex(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
// Skip two if starts with '0x' or '0X'.
let i := shl(1, and(eq(0x3078, or(shr(240, mload(add(s, 0x20))), 0x20)), gt(n, 1)))
for {} 1 {} {
i := add(i, 1)
let c :=
byte(
and(0x1f, shr(and(mload(add(s, i)), 0xff), 0x3e4088843e41bac000000000000)),
0x3010a071000000b0104040208000c05090d060e0f
)
n := mul(n, iszero(or(iszero(c), shr(252, result))))
result := add(shl(4, result), sub(c, 1))
if iszero(lt(i, n)) { break }
}
if iszero(n) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Decodes a JSON encoded string.
/// The string MUST be double-quoted, JSON encoded.
/// Reverts if the string is invalid.
/// As you can see, it's pretty complex for a deceptively simple looking task.
function decodeString(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
function fail() {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
function decodeUnicodeEscapeSequence(pIn_, end_) -> _unicode, _pOut {
_pOut := add(pIn_, 4)
let b_ := iszero(gt(_pOut, end_))
let t_ := mload(pIn_) // Load the whole word.
for { let i_ := 0 } iszero(eq(i_, 4)) { i_ := add(i_, 1) } {
let c_ := sub(byte(i_, t_), 48)
if iszero(and(shr(c_, 0x7e0000007e03ff), b_)) { fail() } // Not hexadecimal.
c_ := sub(c_, add(mul(gt(c_, 16), 7), shl(5, gt(c_, 48))))
_unicode := add(shl(4, _unicode), c_)
}
}
function decodeUnicodeCodePoint(pIn_, end_) -> _unicode, _pOut {
_unicode, _pOut := decodeUnicodeEscapeSequence(pIn_, end_)
if iszero(or(lt(_unicode, 0xd800), gt(_unicode, 0xdbff))) {
let t_ := mload(_pOut) // Load the whole word.
end_ := mul(end_, eq(shr(240, t_), 0x5c75)) // Fail if not starting with '\\u'.
t_, _pOut := decodeUnicodeEscapeSequence(add(_pOut, 2), end_)
_unicode := add(0x10000, add(shl(10, and(0x3ff, _unicode)), and(0x3ff, t_)))
}
}
function appendCodePointAsUTF8(pIn_, c_) -> _pOut {
if iszero(gt(c_, 0x7f)) {
mstore8(pIn_, c_)
_pOut := add(pIn_, 1)
leave
}
mstore8(0x1f, c_)
mstore8(0x1e, shr(6, c_))
if iszero(gt(c_, 0x7ff)) {
mstore(pIn_, shl(240, or(0xc080, and(0x1f3f, mload(0x00)))))
_pOut := add(pIn_, 2)
leave
}
mstore8(0x1d, shr(12, c_))
if iszero(gt(c_, 0xffff)) {
mstore(pIn_, shl(232, or(0xe08080, and(0x0f3f3f, mload(0x00)))))
_pOut := add(pIn_, 3)
leave
}
mstore8(0x1c, shr(18, c_))
mstore(pIn_, shl(224, or(0xf0808080, and(0x073f3f3f, mload(0x00)))))
_pOut := add(pIn_, shl(2, lt(c_, 0x110000)))
}
function chr(p_) -> _c {
_c := byte(0, mload(p_))
}
let n := mload(s)
let end := add(add(s, n), 0x1f)
if iszero(and(gt(n, 1), eq(0x2222, or(and(0xff00, mload(add(s, 2))), chr(end))))) {
fail() // Fail if not double-quoted.
}
let out := add(mload(0x40), 0x20)
for { let curr := add(s, 0x21) } iszero(eq(curr, end)) {} {
let c := chr(curr)
curr := add(curr, 1)
// Not '\\'.
if iszero(eq(c, 92)) {
// Not '"'.
if iszero(eq(c, 34)) {
mstore8(out, c)
out := add(out, 1)
continue
}
curr := end
}
if iszero(eq(curr, end)) {
let escape := chr(curr)
curr := add(curr, 1)
// '"', '/', '\\'.
if and(shr(escape, 0x100000000000800400000000), 1) {
mstore8(out, escape)
out := add(out, 1)
continue
}
// 'u'.
if eq(escape, 117) {
escape, curr := decodeUnicodeCodePoint(curr, end)
out := appendCodePointAsUTF8(out, escape)
continue
}
// `{'b':'\b', 'f':'\f', 'n':'\n', 'r':'\r', 't':'\t'}`.
escape := byte(sub(escape, 85), 0x080000000c000000000000000a0000000d0009)
if escape {
mstore8(out, escape)
out := add(out, 1)
continue
}
}
fail()
break
}
mstore(out, 0) // Zeroize the last slot.
result := mload(0x40)
mstore(result, sub(out, add(result, 0x20))) // Store the length.
mstore(0x40, add(out, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Performs a query on the input with the given mode.
function _query(bytes32 input, uint256 mode) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
function fail() {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
function chr(p_) -> _c {
_c := byte(0, mload(p_))
}
function skipWhitespace(pIn_, end_) -> _pOut {
for { _pOut := pIn_ } 1 { _pOut := add(_pOut, 1) } {
if iszero(and(shr(chr(_pOut), 0x100002600), 1)) { leave } // Not in ' \n\r\t'.
}
}
function setP(packed_, bitpos_, p_) -> _packed {
// Perform an out-of-gas revert if `p_` exceeds `_BITMASK_POINTER`.
returndatacopy(returndatasize(), returndatasize(), gt(p_, _BITMASK_POINTER))
_packed := or(and(not(shl(bitpos_, _BITMASK_POINTER)), packed_), shl(bitpos_, p_))
}
function getP(packed_, bitpos_) -> _p {
_p := and(_BITMASK_POINTER, shr(bitpos_, packed_))
}
function mallocItem(s_, packed_, pStart_, pCurr_, type_) -> _item {
_item := mload(0x40)
// forgefmt: disable-next-item
packed_ := setP(setP(packed_, _BITPOS_VALUE, sub(pStart_, add(s_, 0x20))),
_BITPOS_VALUE_LENGTH, sub(pCurr_, pStart_))
mstore(_item, or(packed_, type_))
mstore(0x40, add(_item, 0x20)) // Allocate memory.
}
function parseValue(s_, sibling_, pIn_, end_) -> _item, _pOut {
let packed_ := setP(mload(0x00), _BITPOS_SIBLING_OR_PARENT, sibling_)
_pOut := skipWhitespace(pIn_, end_)
if iszero(lt(_pOut, end_)) { leave }
for { let c_ := chr(_pOut) } 1 {} {
// If starts with '"'.
if eq(c_, 34) {
let pStart_ := _pOut
_pOut := parseStringSub(s_, packed_, _pOut, end_)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_STRING)
break
}
// If starts with '['.
if eq(c_, 91) {
_item, _pOut := parseArray(s_, packed_, _pOut, end_)
break
}
// If starts with '{'.
if eq(c_, 123) {
_item, _pOut := parseObject(s_, packed_, _pOut, end_)
break
}
// If starts with any in '0123456789-'.
if and(shr(c_, shl(45, 0x1ff9)), 1) {
_item, _pOut := parseNumber(s_, packed_, _pOut, end_)
break
}
if iszero(gt(add(_pOut, 4), end_)) {
let pStart_ := _pOut
let w_ := shr(224, mload(_pOut))
// 'true' in hex format.
if eq(w_, 0x74727565) {
_pOut := add(_pOut, 4)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_BOOLEAN)
break
}
// 'null' in hex format.
if eq(w_, 0x6e756c6c) {
_pOut := add(_pOut, 4)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_NULL)
break
}
}
if iszero(gt(add(_pOut, 5), end_)) {
let pStart_ := _pOut
let w_ := shr(216, mload(_pOut))
// 'false' in hex format.
if eq(w_, 0x66616c7365) {
_pOut := add(_pOut, 5)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_BOOLEAN)
break
}
}
fail()
break
}
_pOut := skipWhitespace(_pOut, end_)
}
function parseArray(s_, packed_, pIn_, end_) -> _item, _pOut {
let j_ := 0
for { _pOut := add(pIn_, 1) } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(_pOut, end_)) { fail() }
if iszero(_item) {
_pOut := skipWhitespace(_pOut, end_)
if eq(chr(_pOut), 93) { break } // ']'.
}
_item, _pOut := parseValue(s_, _item, _pOut, end_)
if _item {
// forgefmt: disable-next-item
mstore(_item, setP(or(_PARENT_IS_ARRAY, mload(_item)),
_BITPOS_KEY, j_))
j_ := add(j_, 1)
let c_ := chr(_pOut)
if eq(c_, 93) { break } // ']'.
if eq(c_, 44) { continue } // ','.
}
_pOut := end_
}
_pOut := add(_pOut, 1)
packed_ := setP(packed_, _BITPOS_CHILD, _item)
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_ARRAY)
}
function parseObject(s_, packed_, pIn_, end_) -> _item, _pOut {
for { _pOut := add(pIn_, 1) } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(_pOut, end_)) { fail() }
if iszero(_item) {
_pOut := skipWhitespace(_pOut, end_)
if eq(chr(_pOut), 125) { break } // '}'.
}
_pOut := skipWhitespace(_pOut, end_)
let pKeyStart_ := _pOut
let pKeyEnd_ := parseStringSub(s_, _item, _pOut, end_)
_pOut := skipWhitespace(pKeyEnd_, end_)
// If ':'.
if eq(chr(_pOut), 58) {
_item, _pOut := parseValue(s_, _item, add(_pOut, 1), end_)
if _item {
// forgefmt: disable-next-item
mstore(_item, setP(setP(or(_PARENT_IS_OBJECT, mload(_item)),
_BITPOS_KEY_LENGTH, sub(pKeyEnd_, pKeyStart_)),
_BITPOS_KEY, sub(pKeyStart_, add(s_, 0x20))))
let c_ := chr(_pOut)
if eq(c_, 125) { break } // '}'.
if eq(c_, 44) { continue } // ','.
}
}
_pOut := end_
}
_pOut := add(_pOut, 1)
packed_ := setP(packed_, _BITPOS_CHILD, _item)
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_OBJECT)
}
function checkStringU(p_, o_) {
// If not in '0123456789abcdefABCDEF', revert.
if iszero(and(shr(sub(chr(add(p_, o_)), 48), 0x7e0000007e03ff), 1)) { fail() }
if iszero(eq(o_, 5)) { checkStringU(p_, add(o_, 1)) }
}
function parseStringSub(s_, packed_, pIn_, end_) -> _pOut {
if iszero(lt(pIn_, end_)) { fail() }
for { _pOut := add(pIn_, 1) } 1 {} {
let c_ := chr(_pOut)
if eq(c_, 34) { break } // '"'.
// Not '\'.
if iszero(eq(c_, 92)) {
_pOut := add(_pOut, 1)
continue
}
c_ := chr(add(_pOut, 1))
// '"', '\', '//', 'b', 'f', 'n', 'r', 't'.
if and(shr(sub(c_, 34), 0x510110400000000002001), 1) {
_pOut := add(_pOut, 2)
continue
}
// 'u'.
if eq(c_, 117) {
checkStringU(_pOut, 2)
_pOut := add(_pOut, 6)
continue
}
_pOut := end_
break
}
if iszero(lt(_pOut, end_)) { fail() }
_pOut := add(_pOut, 1)
}
function skip0To9s(pIn_, end_, atLeastOne_) -> _pOut {
for { _pOut := pIn_ } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(sub(chr(_pOut), 48), 10)) { break } // Not '0'..'9'.
}
if and(atLeastOne_, eq(pIn_, _pOut)) { fail() }
}
function parseNumber(s_, packed_, pIn_, end_) -> _item, _pOut {
_pOut := pIn_
if eq(chr(_pOut), 45) { _pOut := add(_pOut, 1) } // '-'.
if iszero(lt(sub(chr(_pOut), 48), 10)) { fail() } // Not '0'..'9'.
let c_ := chr(_pOut)
_pOut := add(_pOut, 1)
if iszero(eq(c_, 48)) { _pOut := skip0To9s(_pOut, end_, 0) } // Not '0'.
if eq(chr(_pOut), 46) { _pOut := skip0To9s(add(_pOut, 1), end_, 1) } // '.'.
let t_ := mload(_pOut)
// 'E', 'e'.
if eq(or(0x20, byte(0, t_)), 101) {
// forgefmt: disable-next-item
_pOut := skip0To9s(add(byte(sub(byte(1, t_), 14), 0x010001), // '+', '-'.
add(_pOut, 1)), end_, 1)
}
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_NUMBER)
}
function copyStr(s_, offset_, len_) -> _sCopy {
_sCopy := mload(0x40)
s_ := add(s_, offset_)
let w_ := not(0x1f)
for { let i_ := and(add(len_, 0x1f), w_) } 1 {} {
mstore(add(_sCopy, i_), mload(add(s_, i_)))
i_ := add(i_, w_) // `sub(i_, 0x20)`.
if iszero(i_) { break }
}
mstore(_sCopy, len_) // Copy the length.
mstore(add(add(_sCopy, 0x20), len_), 0) // Zeroize the last slot.
mstore(0x40, add(add(_sCopy, 0x40), len_)) // Allocate memory.
}
function value(item_) -> _value {
let packed_ := mload(item_)
_value := getP(packed_, _BITPOS_VALUE) // The offset in the string.
if iszero(and(_VALUE_INITED, packed_)) {
let s_ := getP(packed_, _BITPOS_STRING)
_value := copyStr(s_, _value, getP(packed_, _BITPOS_VALUE_LENGTH))
packed_ := setP(packed_, _BITPOS_VALUE, _value)
mstore(s_, or(_VALUE_INITED, packed_))
}
}
function children(item_) -> _arr {
_arr := 0x60 // Initialize to the zero pointer.
let packed_ := mload(item_)
for {} iszero(gt(and(_BITMASK_TYPE, packed_), TYPE_OBJECT)) {} {
if or(iszero(packed_), iszero(item_)) { break }
if and(packed_, _CHILDREN_INITED) {
_arr := getP(packed_, _BITPOS_CHILD)
break
}
_arr := mload(0x40)
let o_ := add(_arr, 0x20)
for { let h_ := getP(packed_, _BITPOS_CHILD) } h_ {} {
mstore(o_, h_)
let q_ := mload(h_)
let y_ := getP(q_, _BITPOS_SIBLING_OR_PARENT)
mstore(h_, setP(q_, _BITPOS_SIBLING_OR_PARENT, item_))
h_ := y_
o_ := add(o_, 0x20)
}
let w_ := not(0x1f)
let n_ := add(w_, sub(o_, _arr))
mstore(_arr, shr(5, n_))
mstore(0x40, o_) // Allocate memory.
packed_ := setP(packed_, _BITPOS_CHILD, _arr)
mstore(item_, or(_CHILDREN_INITED, packed_))
// Reverse the array.
if iszero(lt(n_, 0x40)) {
let lo_ := add(_arr, 0x20)
let hi_ := add(_arr, n_)
for {} 1 {} {
let temp_ := mload(lo_)
mstore(lo_, mload(hi_))
mstore(hi_, temp_)
hi_ := add(hi_, w_)
lo_ := add(lo_, 0x20)
if iszero(lt(lo_, hi_)) { break }
}
}
break
}
}
function getStr(item_, bitpos_, bitposLength_, bitmaskInited_) -> _result {
_result := 0x60 // Initialize to the zero pointer.
let packed_ := mload(item_)
if or(iszero(item_), iszero(packed_)) { leave }
_result := getP(packed_, bitpos_)
if iszero(and(bitmaskInited_, packed_)) {
let s_ := getP(packed_, _BITPOS_STRING)
_result := copyStr(s_, _result, getP(packed_, bitposLength_))
mstore(item_, or(bitmaskInited_, setP(packed_, bitpos_, _result)))
}
}
switch mode
// Get value.
case 0 { result := getStr(input, _BITPOS_VALUE, _BITPOS_VALUE_LENGTH, _VALUE_INITED) }
// Get key.
case 1 { result := getStr(input, _BITPOS_KEY, _BITPOS_KEY_LENGTH, _KEY_INITED) }
// Get children.
case 3 { result := children(input) }
// Parse.
default {
let p := add(input, 0x20)
let e := add(p, mload(input))
if iszero(eq(p, e)) {
let c := chr(e)
mstore8(e, 34) // Place a '"' at the end to speed up parsing.
// The `34 << 248` makes `mallocItem` preserve '"' at the end.
mstore(0x00, setP(shl(248, 34), _BITPOS_STRING, input))
result, p := parseValue(input, 0, p, e)
mstore8(e, c) // Restore the original char at the end.
}
if or(lt(p, e), iszero(result)) { fail() }
}
}
}
/// @dev Casts the input to a bytes32.
function _toInput(string memory input) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := input
}
}
/// @dev Casts the input to a bytes32.
function _toInput(Item memory input) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := input
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory str) {
if (value >= 0) {
return toString(uint256(value));
}
unchecked {
str = toString(uint256(-value));
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let length := mload(str) // Load the string length.
mstore(str, 0x2d) // Store the '-' character.
str := sub(str, 1) // Move back the string pointer by a byte.
mstore(str, add(length, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2 + 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value, length);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 length)
internal
pure
returns (string memory str)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(str, add(length, length))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(str, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := add(mload(str), 2) // Compute the length.
mstore(add(str, o), 0x3078) // Write the "0x" prefix, accounting for leading zero.
str := sub(add(str, o), 2) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := mload(str) // Get the length.
str := add(str, o) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
str := add(mload(0x40), 0x80)
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory str) {
str = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(str, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
str := mload(0x40)
// Allocate the memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(str, 0x80))
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
str := add(str, 2)
mstore(str, 40)
let o := add(str, 0x20)
mstore(add(o, 40), 0)
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory str) {
str = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
let length := mload(raw)
str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(str, add(length, length)) // Store the length of the output.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let o := add(str, 0x20)
let end := add(raw, length)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let mask := shl(7, div(not(0), 255))
result := 1
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.
function replace(string memory subject, string memory search, string memory replacement)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(result, o), mload(add(replacement, o)))
o := add(o, 0x20)
if iszero(lt(o, replacementLength)) { break }
}
result := add(result, replacementLength)
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
}
let resultRemainder := result
result := add(mload(0x40), 0x20)
let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
// Copy the rest of the string one word at a time.
for {} lt(subject, subjectEnd) {} {
mstore(resultRemainder, mload(subject))
resultRemainder := add(resultRemainder, 0x20)
subject := add(subject, 0x20)
}
result := sub(result, 0x20)
let last := add(add(result, 0x20), k) // Zeroize the slot after the string.
mstore(last, 0)
mstore(0x40, add(last, 0x20)) // Allocate the memory.
mstore(result, k) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for { let subjectLength := mload(subject) } 1 {} {
if iszero(mload(search)) {
if iszero(gt(from, subjectLength)) {
result := from
break
}
result := subjectLength
break
}
let searchLength := mload(search)
let subjectStart := add(subject, 0x20)
result := not(0) // Initialize to `NOT_FOUND`.
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(add(search, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }
if iszero(lt(searchLength, 0x20)) {
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = indexOf(subject, search, 0);
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let searchLength := mload(search)
if gt(searchLength, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), searchLength)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(subject, search, uint256(int256(-1)));
}
/// @dev Returns true if `search` is found in `subject`, false otherwise.
function contains(string memory subject, string memory search) internal pure returns (bool) {
return indexOf(subject, search) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `search`.
function startsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
iszero(gt(searchLength, mload(subject))),
eq(
keccak256(add(subject, 0x20), searchLength),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns whether `subject` ends with `search`.
function endsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
let subjectLength := mload(subject)
// Whether `search` is not longer than `subject`.
let withinRange := iszero(gt(searchLength, subjectLength))
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
withinRange,
eq(
keccak256(
// `subject + 0x20 + max(subjectLength - searchLength, 0)`.
add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),
searchLength
),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(or(iszero(times), iszero(subjectLength))) {
subject := add(subject, 0x20)
result := mload(0x40)
let output := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(output, o), mload(add(subject, o)))
o := add(o, 0x20)
if iszero(lt(o, subjectLength)) { break }
}
output := add(output, subjectLength)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(output, 0) // Zeroize the slot after the string.
let resultLength := sub(output, add(result, 0x20))
mstore(result, resultLength) // Store the length.
// Allocate the memory.
mstore(0x40, add(result, add(resultLength, 0x20)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(gt(subjectLength, end)) { end := subjectLength }
if iszero(gt(subjectLength, start)) { start := subjectLength }
if lt(start, end) {
result := mload(0x40)
let resultLength := sub(end, start)
mstore(result, resultLength)
subject := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
mstore(add(result, o), mload(add(subject, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(result, 0x20), resultLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(result, and(add(resultLength, 0x3f), w)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start)
internal
pure
returns (string memory result)
{
result = slice(subject, start, uint256(int256(-1)));
}
/// @dev Returns all the indices of `search` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory search)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
if iszero(gt(searchLength, subjectLength)) {
subject := add(subject, 0x20)
search := add(search, 0x20)
result := add(mload(0x40), 0x20)
let subjectStart := subject
let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Append to `result`.
mstore(result, sub(subject, subjectStart))
result := add(result, 0x20)
// Advance `subject` by `searchLength`.
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
let resultEnd := result
// Assign `result` to the free memory pointer.
result := mload(0x40)
// Store the length of `result`.
mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(resultEnd, 0x20))
}
}
}
/// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
let prevIndex := 0
for {} 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let elementLength := sub(index, prevIndex)
mstore(element, elementLength)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(elementLength, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(element, 0x20), elementLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(elementLength, 0x3f), w)))
// Store the `element` into the array.
mstore(indexPtr, element)
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
result := mload(0x40)
let aLength := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLength, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLength := mload(b)
let output := add(result, aLength)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLength, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLength := add(aLength, bLength)
let last := add(add(result, 0x20), totalLength)
// Zeroize the slot after the string.
mstore(last, 0)
// Stores the length.
mstore(result, totalLength)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, and(add(last, 0x1f), w))
}
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
for { let o := length } 1 {} {
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
if iszero(o) { break }
}
result := mload(0x40)
mstore(result, length) // Store the length.
let last := add(add(result, 0x20), length)
mstore(last, 0) // Zeroize the slot after the string.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n)
let o := add(result, 0x20)
mstore(o, s)
mstore(add(o, n), 0)
mstore(0x40, add(result, 0x40))
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(result, c)
result := add(result, 1)
continue
}
let t := shr(248, mload(c))
mstore(result, mload(and(t, 0x1f)))
result := add(result, shr(5, t))
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(result, c)
result := add(result, 1)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), c)
result := add(result, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(result, mload(0x19)) // "\\u00XX".
result := add(result, 6)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), mload(add(c, 8)))
result := add(result, 2)
}
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
result := mload(0x40)
// Allocate 2 words (1 for the length, 1 for the bytes).
mstore(0x40, add(result, 0x40))
// Zeroize the length slot.
mstore(result, 0)
// Store the length and bytes.
mstore(add(result, 0x1f), packed)
// Right pad with zeroes.
mstore(add(add(result, 0x20), mload(result)), 0)
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLength := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes of `a` and `b`.
or(
shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),
mload(sub(add(b, 0x1e), aLength))
),
// `totalLength != 0 && totalLength < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLength, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
resultA := mload(0x40)
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retSize), 0)
// Store the return offset.
mstore(retStart, 0x20)
// End the transaction, returning the string.
return(retStart, retSize)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {DateTimeLib} from "solady/utils/DateTimeLib.sol";
import {LibString} from "solady/utils/LibString.sol";
library DateTimeUtils {
using LibString for string;
/*
* @dev Convert a DER-encoded time to a unix timestamp
* @param x509Time The DER-encoded time
* @return The unix timestamp
*/
function fromDERToTimestamp(bytes memory x509Time) internal pure returns (uint256) {
uint16 yrs;
uint8 mnths;
uint8 dys;
uint8 hrs;
uint8 mins;
uint8 secs;
uint8 offset;
if (x509Time.length == 13) {
if (uint8(x509Time[0]) - 48 < 5) yrs += 2000;
else yrs += 1900;
} else {
yrs += (uint8(x509Time[0]) - 48) * 1000 + (uint8(x509Time[1]) - 48) * 100;
offset = 2;
}
yrs += (uint8(x509Time[offset + 0]) - 48) * 10 + uint8(x509Time[offset + 1]) - 48;
mnths = (uint8(x509Time[offset + 2]) - 48) * 10 + uint8(x509Time[offset + 3]) - 48;
dys += (uint8(x509Time[offset + 4]) - 48) * 10 + uint8(x509Time[offset + 5]) - 48;
hrs += (uint8(x509Time[offset + 6]) - 48) * 10 + uint8(x509Time[offset + 7]) - 48;
mins += (uint8(x509Time[offset + 8]) - 48) * 10 + uint8(x509Time[offset + 9]) - 48;
secs += (uint8(x509Time[offset + 10]) - 48) * 10 + uint8(x509Time[offset + 11]) - 48;
return DateTimeLib.dateTimeToTimestamp(yrs, mnths, dys, hrs, mins, secs);
}
/// @dev iso follows pattern: "YYYY-MM-DDTHH:mm:ssZ"
function fromISOToTimestamp(string memory iso) internal pure returns (uint256) {
require(bytes(iso).length == 20, "invalid iso string length");
uint256 y = stringToUint(iso.slice(0, 4));
uint256 m = stringToUint(iso.slice(5, 7));
uint256 d = stringToUint(iso.slice(8, 10));
uint256 h = stringToUint(iso.slice(11, 13));
uint256 min = stringToUint(iso.slice(14, 16));
uint256 s = stringToUint(iso.slice(17, 19));
return DateTimeLib.dateTimeToTimestamp(y, m, d, h, min, s);
}
// https://ethereum.stackexchange.com/questions/10932/how-to-convert-string-to-int
function stringToUint(string memory s) private pure returns (uint256 result) {
bytes memory b = bytes(s);
result = 0;
for (uint256 i = 0; i < b.length; i++) {
uint256 c = uint256(uint8(b[i]));
if (c >= 48 && c <= 57) {
result = result * 10 + (c - 48);
}
}
}
}// SPDX-License-Identifier: MIT
// Original source: https://github.com/JonahGroendal/asn1-decode
pragma solidity ^0.8.0;
// Inspired by PufferFinance/rave
// https://github.com/JonahGroendal/asn1-decode/blob/5c2d1469fc678513753786acb441e597969192ec/contracts/Asn1Decode.sol
import "./BytesUtils.sol";
library NodePtr {
// Unpack first byte index
function ixs(uint256 self) internal pure returns (uint256) {
return uint80(self);
}
// Unpack first content byte index
function ixf(uint256 self) internal pure returns (uint256) {
return uint80(self >> 80);
}
// Unpack last content byte index
function ixl(uint256 self) internal pure returns (uint256) {
return uint80(self >> 160);
}
// Pack 3 uint80s into a uint256
function getPtr(uint256 _ixs, uint256 _ixf, uint256 _ixl) internal pure returns (uint256) {
_ixs |= _ixf << 80;
_ixs |= _ixl << 160;
return _ixs;
}
}
library Asn1Decode {
using NodePtr for uint256;
using BytesUtils for bytes;
/*
* @dev Get the root node. First step in traversing an ASN1 structure
* @param der The DER-encoded ASN1 structure
* @return A pointer to the outermost node
*/
function root(bytes memory der) internal pure returns (uint256) {
return readNodeLength(der, 0);
}
/*
* @dev Get the root node of an ASN1 structure that's within a bit string value
* @param der The DER-encoded ASN1 structure
* @return A pointer to the outermost node
*/
function rootOfBitStringAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
require(der[ptr.ixs()] == 0x03, "Not type BIT STRING");
return readNodeLength(der, ptr.ixf() + 1);
}
/*
* @dev Get the root node of an ASN1 structure that's within an octet string value
* @param der The DER-encoded ASN1 structure
* @return A pointer to the outermost node
*/
function rootOfOctetStringAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
require(der[ptr.ixs()] == 0x04, "Not type OCTET STRING");
return readNodeLength(der, ptr.ixf());
}
/*
* @dev Get the next sibling node
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return A pointer to the next sibling node
*/
function nextSiblingOf(bytes memory der, uint256 ptr) internal pure returns (uint256) {
return readNodeLength(der, ptr.ixl() + 1);
}
/*
* @dev Get the first child node of the current node
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return A pointer to the first child node
*/
function firstChildOf(bytes memory der, uint256 ptr) internal pure returns (uint256) {
require(der[ptr.ixs()] & 0x20 == 0x20, "Not a constructed type");
return readNodeLength(der, ptr.ixf());
}
/*
* @dev Use for looping through children of a node (either i or j).
* @param i Pointer to an ASN1 node
* @param j Pointer to another ASN1 node of the same ASN1 structure
* @return True iff j is child of i or i is child of j.
*/
function isChildOf(uint256 i, uint256 j) internal pure returns (bool) {
return (((i.ixf() <= j.ixs()) && (j.ixl() <= i.ixl())) || ((j.ixf() <= i.ixs()) && (i.ixl() <= j.ixl())));
}
/*
* @dev Extract value of node from DER-encoded structure
* @param der The der-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return Value bytes of node
*/
function bytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
return der.substring(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
}
/*
* @dev Extract entire node from DER-encoded structure
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return All bytes of node
*/
function allBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
return der.substring(ptr.ixs(), ptr.ixl() + 1 - ptr.ixs());
}
/*
* @dev Extract value of node from DER-encoded structure
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return Value bytes of node as bytes32
*/
function bytes32At(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
return der.readBytesN(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
}
/*
* @dev Extract value of node from DER-encoded structure
* @param der The der-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return Uint value of node
*/
function uintAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
require(der[ptr.ixs()] == 0x02, "Not type INTEGER");
require(der[ptr.ixf()] & 0x80 == 0, "Not positive");
uint256 len = ptr.ixl() + 1 - ptr.ixf();
return uint256(der.readBytesN(ptr.ixf(), len) >> (32 - len) * 8);
}
/*
* @dev Extract value of a positive integer node from DER-encoded structure
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return Value bytes of a positive integer node
*/
function uintBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
require(der[ptr.ixs()] == 0x02, "Not type INTEGER");
require(der[ptr.ixf()] & 0x80 == 0, "Not positive");
uint256 valueLength = ptr.ixl() + 1 - ptr.ixf();
if (der[ptr.ixf()] == 0) {
return der.substring(ptr.ixf() + 1, valueLength - 1);
} else {
return der.substring(ptr.ixf(), valueLength);
}
}
function keccakOfBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
return der.keccak(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
}
function keccakOfAllBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
return der.keccak(ptr.ixs(), ptr.ixl() + 1 - ptr.ixs());
}
/*
* @dev Extract value of bitstring node from DER-encoded structure
* @param der The DER-encoded ASN1 structure
* @param ptr Points to the indices of the current node
* @return Value of bitstring converted to bytes
*/
function bitstringAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
require(der[ptr.ixs()] == 0x03, "Not type BIT STRING");
// Only 00 padded bitstr can be converted to bytestr!
require(der[ptr.ixf()] == 0x00);
uint256 valueLength = ptr.ixl() + 1 - ptr.ixf();
return der.substring(ptr.ixf() + 1, valueLength - 1);
}
function readNodeLength(bytes memory der, uint256 ix) private pure returns (uint256) {
uint256 n = der.length;
require(ix + 1 < n, "Asn1Decode: index out-of-bound");
uint256 length;
uint80 ixFirstContentByte;
uint80 ixLastContentByte;
if ((der[ix + 1] & 0x80) == 0) {
length = uint8(der[ix + 1]);
require(length > 0, "Asn1Decode: length cannot be zero");
ixFirstContentByte = uint80(ix + 2);
ixLastContentByte = uint80(ixFirstContentByte + length - 1);
} else {
uint8 lengthbytesLength = uint8(der[ix + 1] & 0x7F);
bool invalidLengthBytes = lengthbytesLength == 0 || ix + 2 + lengthbytesLength >= n;
if (invalidLengthBytes) {
revert("Asn1Decode: invalid length bytes");
}
if (lengthbytesLength == 1) {
length = der.readUint8(ix + 2);
require(length > 0, "Asn1Decode: length cannot be zero");
} else if (lengthbytesLength == 2) {
length = der.readUint16(ix + 2);
require(length > 0, "Asn1Decode: length cannot be zero");
} else {
length = uint256(der.readBytesN(ix + 2, lengthbytesLength) >> (32 - lengthbytesLength) * 8);
require(length > 0, "Asn1Decode: length cannot be zero");
}
ixFirstContentByte = uint80(ix + 2 + lengthbytesLength);
ixLastContentByte = uint80(ixFirstContentByte + length - 1);
}
if (ixLastContentByte + 1 > n) {
revert("Asn1Decode: out of bound: incorrect content length");
}
return NodePtr.getPtr(ix, ixFirstContentByte, ixLastContentByte);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for date time operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DateTimeLib.sol)
///
/// Conventions:
/// --------------------------------------------------------------------+
/// Unit | Range | Notes |
/// --------------------------------------------------------------------|
/// timestamp | 0..0x1e18549868c76ff | Unix timestamp. |
/// epochDay | 0..0x16d3e098039 | Days since 1970-01-01. |
/// year | 1970..0xffffffff | Gregorian calendar year. |
/// month | 1..12 | Gregorian calendar month. |
/// day | 1..31 | Gregorian calendar day of month. |
/// weekday | 1..7 | The day of the week (1-indexed). |
/// --------------------------------------------------------------------+
/// All timestamps of days are rounded down to 00:00:00 UTC.
library DateTimeLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Weekdays are 1-indexed for a traditional rustic feel.
// "And on the seventh day God finished his work that he had done,
// and he rested on the seventh day from all his work that he had done."
// -- Genesis 2:2
uint256 internal constant MON = 1;
uint256 internal constant TUE = 2;
uint256 internal constant WED = 3;
uint256 internal constant THU = 4;
uint256 internal constant FRI = 5;
uint256 internal constant SAT = 6;
uint256 internal constant SUN = 7;
// Months and days of months are 1-indexed for ease of use.
uint256 internal constant JAN = 1;
uint256 internal constant FEB = 2;
uint256 internal constant MAR = 3;
uint256 internal constant APR = 4;
uint256 internal constant MAY = 5;
uint256 internal constant JUN = 6;
uint256 internal constant JUL = 7;
uint256 internal constant AUG = 8;
uint256 internal constant SEP = 9;
uint256 internal constant OCT = 10;
uint256 internal constant NOV = 11;
uint256 internal constant DEC = 12;
// These limits are large enough for most practical purposes.
// Inputs that exceed these limits result in undefined behavior.
uint256 internal constant MAX_SUPPORTED_YEAR = 0xffffffff;
uint256 internal constant MAX_SUPPORTED_EPOCH_DAY = 0x16d3e098039;
uint256 internal constant MAX_SUPPORTED_TIMESTAMP = 0x1e18549868c76ff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATE TIME OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of days since 1970-01-01 from (`year`,`month`,`day`).
/// See: https://howardhinnant.github.io/date_algorithms.html
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDate} to check if the inputs are supported.
function dateToEpochDay(uint256 year, uint256 month, uint256 day)
internal
pure
returns (uint256 epochDay)
{
/// @solidity memory-safe-assembly
assembly {
year := sub(year, lt(month, 3))
let doy := add(shr(11, add(mul(62719, mod(add(month, 9), 12)), 769)), day)
let yoe := mod(year, 400)
let doe := sub(add(add(mul(yoe, 365), shr(2, yoe)), doy), div(yoe, 100))
epochDay := sub(add(mul(div(year, 400), 146097), doe), 719469)
}
}
/// @dev Returns (`year`,`month`,`day`) from the number of days since 1970-01-01.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDays} to check if the inputs is supported.
function epochDayToDate(uint256 epochDay)
internal
pure
returns (uint256 year, uint256 month, uint256 day)
{
/// @solidity memory-safe-assembly
assembly {
epochDay := add(epochDay, 719468)
let doe := mod(epochDay, 146097)
let yoe :=
div(sub(sub(add(doe, div(doe, 36524)), div(doe, 1460)), eq(doe, 146096)), 365)
let doy := sub(doe, sub(add(mul(365, yoe), shr(2, yoe)), div(yoe, 100)))
let mp := div(add(mul(5, doy), 2), 153)
day := add(sub(doy, shr(11, add(mul(mp, 62719), 769))), 1)
month := byte(mp, shl(160, 0x030405060708090a0b0c0102))
year := add(add(yoe, mul(div(epochDay, 146097), 400)), lt(month, 3))
}
}
/// @dev Returns the unix timestamp from (`year`,`month`,`day`).
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDate} to check if the inputs are supported.
function dateToTimestamp(uint256 year, uint256 month, uint256 day)
internal
pure
returns (uint256 result)
{
unchecked {
result = dateToEpochDay(year, month, day) * 86400;
}
}
/// @dev Returns (`year`,`month`,`day`) from the given unix timestamp.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedTimestamp} to check if the inputs are supported.
function timestampToDate(uint256 timestamp)
internal
pure
returns (uint256 year, uint256 month, uint256 day)
{
(year, month, day) = epochDayToDate(timestamp / 86400);
}
/// @dev Returns the unix timestamp from
/// (`year`,`month`,`day`,`hour`,`minute`,`second`).
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedDateTime} to check if the inputs are supported.
function dateTimeToTimestamp(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (uint256 result) {
unchecked {
result = dateToEpochDay(year, month, day) * 86400 + hour * 3600 + minute * 60 + second;
}
}
/// @dev Returns (`year`,`month`,`day`,`hour`,`minute`,`second`)
/// from the given unix timestamp.
/// Note: Inputs outside the supported ranges result in undefined behavior.
/// Use {isSupportedTimestamp} to check if the inputs are supported.
function timestampToDateTime(uint256 timestamp)
internal
pure
returns (
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
)
{
unchecked {
(year, month, day) = epochDayToDate(timestamp / 86400);
uint256 secs = timestamp % 86400;
hour = secs / 3600;
secs = secs % 3600;
minute = secs / 60;
second = secs % 60;
}
}
/// @dev Returns if the `year` is leap.
function isLeapYear(uint256 year) internal pure returns (bool leap) {
/// @solidity memory-safe-assembly
assembly {
leap := iszero(and(add(mul(iszero(mod(year, 25)), 12), 3), year))
}
}
/// @dev Returns number of days in given `month` of `year`.
function daysInMonth(uint256 year, uint256 month) internal pure returns (uint256 result) {
bool flag = isLeapYear(year);
/// @solidity memory-safe-assembly
assembly {
// `daysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31]`.
// `result = daysInMonths[month - 1] + isLeapYear(year)`.
result :=
add(byte(month, shl(152, 0x1F1C1F1E1F1E1F1F1E1F1E1F)), and(eq(month, 2), flag))
}
}
/// @dev Returns the weekday from the unix timestamp.
/// Monday: 1, Tuesday: 2, ....., Sunday: 7.
function weekday(uint256 timestamp) internal pure returns (uint256 result) {
unchecked {
result = ((timestamp / 86400 + 3) % 7) + 1;
}
}
/// @dev Returns if (`year`,`month`,`day`) is a supported date.
/// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
/// - `1 <= month <= 12`.
/// - `1 <= day <= daysInMonth(year, month)`.
function isSupportedDate(uint256 year, uint256 month, uint256 day)
internal
pure
returns (bool result)
{
uint256 md = daysInMonth(year, month);
/// @solidity memory-safe-assembly
assembly {
let w := not(0)
result :=
and(
lt(sub(year, 1970), sub(MAX_SUPPORTED_YEAR, 1969)),
and(lt(add(month, w), 12), lt(add(day, w), md))
)
}
}
/// @dev Returns if (`year`,`month`,`day`,`hour`,`minute`,`second`) is a supported date time.
/// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
/// - `1 <= month <= 12`.
/// - `1 <= day <= daysInMonth(year, month)`.
/// - `hour < 24`.
/// - `minute < 60`.
/// - `second < 60`.
function isSupportedDateTime(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (bool result) {
if (isSupportedDate(year, month, day)) {
/// @solidity memory-safe-assembly
assembly {
result := and(lt(hour, 24), and(lt(minute, 60), lt(second, 60)))
}
}
}
/// @dev Returns if `epochDay` is a supported unix epoch day.
function isSupportedEpochDay(uint256 epochDay) internal pure returns (bool result) {
unchecked {
result = epochDay < MAX_SUPPORTED_EPOCH_DAY + 1;
}
}
/// @dev Returns if `timestamp` is a supported unix timestamp.
function isSupportedTimestamp(uint256 timestamp) internal pure returns (bool result) {
unchecked {
result = timestamp < MAX_SUPPORTED_TIMESTAMP + 1;
}
}
/// @dev Returns the unix timestamp of the given `n`th weekday `wd`, in `month` of `year`.
/// Example: 3rd Friday of Feb 2022 is `nthWeekdayInMonthOfYearTimestamp(2022, 2, 3, 5)`
/// Note: `n` is 1-indexed for traditional consistency.
/// Invalid weekdays (i.e. `wd == 0 || wd > 7`) result in undefined behavior.
function nthWeekdayInMonthOfYearTimestamp(uint256 year, uint256 month, uint256 n, uint256 wd)
internal
pure
returns (uint256 result)
{
uint256 d = dateToEpochDay(year, month, 1);
uint256 md = daysInMonth(year, month);
/// @solidity memory-safe-assembly
assembly {
let diff := sub(wd, add(mod(add(d, 3), 7), 1))
let date := add(mul(sub(n, 1), 7), add(mul(gt(diff, 6), 7), diff))
result := mul(mul(86400, add(date, d)), and(lt(date, md), iszero(iszero(n))))
}
}
/// @dev Returns the unix timestamp of the most recent Monday.
function mondayTimestamp(uint256 timestamp) internal pure returns (uint256 result) {
uint256 t = timestamp;
/// @solidity memory-safe-assembly
assembly {
let day := div(t, 86400)
result := mul(mul(sub(day, mod(add(day, 3), 7)), 86400), gt(t, 345599))
}
}
/// @dev Returns whether the unix timestamp falls on a Saturday or Sunday.
/// To check whether it is a week day, just take the negation of the result.
function isWeekEnd(uint256 timestamp) internal pure returns (bool result) {
result = weekday(timestamp) > FRI;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DATE TIME ARITHMETIC OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Adds `numYears` to the unix timestamp, and returns the result.
/// Note: The result will share the same Gregorian calendar month,
/// but different Gregorian calendar years for non-zero `numYears`.
/// If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function addYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
result = _offsetted(year + numYears, month, day, timestamp);
}
/// @dev Adds `numMonths` to the unix timestamp, and returns the result.
/// Note: If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function addMonths(uint256 timestamp, uint256 numMonths)
internal
pure
returns (uint256 result)
{
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
month = _sub(month + numMonths, 1);
result = _offsetted(year + month / 12, _add(month % 12, 1), day, timestamp);
}
/// @dev Adds `numDays` to the unix timestamp, and returns the result.
function addDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
result = timestamp + numDays * 86400;
}
/// @dev Adds `numHours` to the unix timestamp, and returns the result.
function addHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
result = timestamp + numHours * 3600;
}
/// @dev Adds `numMinutes` to the unix timestamp, and returns the result.
function addMinutes(uint256 timestamp, uint256 numMinutes)
internal
pure
returns (uint256 result)
{
result = timestamp + numMinutes * 60;
}
/// @dev Adds `numSeconds` to the unix timestamp, and returns the result.
function addSeconds(uint256 timestamp, uint256 numSeconds)
internal
pure
returns (uint256 result)
{
result = timestamp + numSeconds;
}
/// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
/// Note: The result will share the same Gregorian calendar month,
/// but different Gregorian calendar years for non-zero `numYears`.
/// If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function subYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
result = _offsetted(year - numYears, month, day, timestamp);
}
/// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
/// Note: If the Gregorian calendar month of the result has less days
/// than the Gregorian calendar month day of the `timestamp`,
/// the result's month day will be the maximum possible value for the month.
/// (e.g. from 29th Feb to 28th Feb)
function subMonths(uint256 timestamp, uint256 numMonths)
internal
pure
returns (uint256 result)
{
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
uint256 yearMonth = _totalMonths(year, month) - _add(numMonths, 1);
result = _offsetted(yearMonth / 12, _add(yearMonth % 12, 1), day, timestamp);
}
/// @dev Subtracts `numDays` from the unix timestamp, and returns the result.
function subDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
result = timestamp - numDays * 86400;
}
/// @dev Subtracts `numHours` from the unix timestamp, and returns the result.
function subHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
result = timestamp - numHours * 3600;
}
/// @dev Subtracts `numMinutes` from the unix timestamp, and returns the result.
function subMinutes(uint256 timestamp, uint256 numMinutes)
internal
pure
returns (uint256 result)
{
result = timestamp - numMinutes * 60;
}
/// @dev Subtracts `numSeconds` from the unix timestamp, and returns the result.
function subSeconds(uint256 timestamp, uint256 numSeconds)
internal
pure
returns (uint256 result)
{
result = timestamp - numSeconds;
}
/// @dev Returns the difference in Gregorian calendar years
/// between `fromTimestamp` and `toTimestamp`.
/// Note: Even if the true time difference is less than a year,
/// the difference can be non-zero is the timestamps are
/// from different Gregorian calendar years
function diffYears(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
toTimestamp - fromTimestamp;
(uint256 fromYear,,) = epochDayToDate(fromTimestamp / 86400);
(uint256 toYear,,) = epochDayToDate(toTimestamp / 86400);
result = _sub(toYear, fromYear);
}
/// @dev Returns the difference in Gregorian calendar months
/// between `fromTimestamp` and `toTimestamp`.
/// Note: Even if the true time difference is less than a month,
/// the difference can be non-zero is the timestamps are
/// from different Gregorian calendar months.
function diffMonths(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
toTimestamp - fromTimestamp;
(uint256 fromYear, uint256 fromMonth,) = epochDayToDate(fromTimestamp / 86400);
(uint256 toYear, uint256 toMonth,) = epochDayToDate(toTimestamp / 86400);
result = _sub(_totalMonths(toYear, toMonth), _totalMonths(fromYear, fromMonth));
}
/// @dev Returns the difference in days between `fromTimestamp` and `toTimestamp`.
function diffDays(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 86400;
}
/// @dev Returns the difference in hours between `fromTimestamp` and `toTimestamp`.
function diffHours(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 3600;
}
/// @dev Returns the difference in minutes between `fromTimestamp` and `toTimestamp`.
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = (toTimestamp - fromTimestamp) / 60;
}
/// @dev Returns the difference in seconds between `fromTimestamp` and `toTimestamp`.
function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp)
internal
pure
returns (uint256 result)
{
result = toTimestamp - fromTimestamp;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unchecked arithmetic for computing the total number of months.
function _totalMonths(uint256 numYears, uint256 numMonths)
private
pure
returns (uint256 total)
{
unchecked {
total = numYears * 12 + numMonths;
}
}
/// @dev Unchecked arithmetic for adding two numbers.
function _add(uint256 a, uint256 b) private pure returns (uint256 c) {
unchecked {
c = a + b;
}
}
/// @dev Unchecked arithmetic for subtracting two numbers.
function _sub(uint256 a, uint256 b) private pure returns (uint256 c) {
unchecked {
c = a - b;
}
}
/// @dev Returns the offsetted timestamp.
function _offsetted(uint256 year, uint256 month, uint256 day, uint256 timestamp)
private
pure
returns (uint256 result)
{
uint256 dm = daysInMonth(year, month);
if (day >= dm) {
day = dm;
}
result = dateToEpochDay(year, month, day) * 86400 + (timestamp % 86400);
}
}{
"remappings": [
"forge-std/=lib/forge-std/src/",
"solmate/=lib/solmate/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"automata-dcap-attestation/=lib/automata-dcap-attestation/evm/",
"@automata-network/on-chain-pccs/=lib/automata-dcap-attestation/evm/lib/automata-on-chain-pccs/src/",
"solady/=lib/automata-dcap-attestation/evm/lib/automata-on-chain-pccs/lib/solady/src/",
"@sp1-contracts/=lib/automata-dcap-attestation/evm/lib/sp1-contracts/contracts/src/",
"risc0/=lib/automata-dcap-attestation/evm/lib/risc0-ethereum/contracts/src/",
"automata-on-chain-pccs/=lib/automata-dcap-attestation/evm/lib/automata-on-chain-pccs/",
"ds-test/=lib/automata-dcap-attestation/evm/lib/automata-on-chain-pccs/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"risc0-ethereum/=lib/automata-dcap-attestation/evm/lib/risc0-ethereum/",
"sp1-contracts/=lib/automata-dcap-attestation/evm/lib/sp1-contracts/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 44444444
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "none",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "prague",
"viaIR": true
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"EmptyCommitHash","type":"error"},{"inputs":[],"name":"EmptySourceLocators","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"provided","type":"uint256"}],"name":"InvalidNonce","type":"error"},{"inputs":[],"name":"InvalidRegistry","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"UnauthorizedBlockBuilder","type":"error"},{"inputs":[],"name":"WorkloadAlreadyInPolicy","type":"error"},{"inputs":[],"name":"WorkloadNotInPolicy","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"bytes32","name":"workloadId","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"},{"indexed":false,"internalType":"bytes32","name":"blockContentHash","type":"bytes32"},{"indexed":false,"internalType":"string","name":"commitHash","type":"string"}],"name":"BlockBuilderProofVerified","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"registry","type":"address"}],"name":"RegistrySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"workloadId","type":"bytes32"}],"name":"WorkloadAddedToPolicy","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"workloadId","type":"bytes32"}],"name":"WorkloadRemovedFromPolicy","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERIFY_BLOCK_BUILDER_PROOF_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"WorkloadId","name":"workloadId","type":"bytes32"},{"internalType":"string","name":"commitHash","type":"string"},{"internalType":"string[]","name":"sourceLocators","type":"string[]"}],"name":"addWorkloadToPolicy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"bytes32","name":"blockContentHash","type":"bytes32"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"computeStructHash","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"domainSeparator","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"structHash","type":"bytes32"}],"name":"getHashedTypeDataV4","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"WorkloadId","name":"workloadId","type":"bytes32"}],"name":"getWorkloadMetadata","outputs":[{"components":[{"internalType":"string","name":"commitHash","type":"string"},{"internalType":"string[]","name":"sourceLocators","type":"string[]"}],"internalType":"struct IBlockBuilderPolicy.WorkloadMetadata","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_initialOwner","type":"address"},{"internalType":"address","name":"_registry","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"teeAddress","type":"address"}],"name":"isAllowedPolicy","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"WorkloadId","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"teeAddress","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"permitNonce","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"bytes32","name":"blockContentHash","type":"bytes32"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes","name":"eip712Sig","type":"bytes"}],"name":"permitVerifyBlockBuilderProof","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"registry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"WorkloadId","name":"workloadId","type":"bytes32"}],"name":"removeWorkloadFromPolicy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"bytes32","name":"blockContentHash","type":"bytes32"}],"name":"verifyBlockBuilderProof","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bool","name":"isValid","type":"bool"},{"internalType":"bytes","name":"rawQuote","type":"bytes"},{"components":[{"internalType":"bytes16","name":"teeTcbSvn","type":"bytes16"},{"internalType":"bytes","name":"mrSeam","type":"bytes"},{"internalType":"bytes","name":"mrsignerSeam","type":"bytes"},{"internalType":"bytes8","name":"seamAttributes","type":"bytes8"},{"internalType":"bytes8","name":"tdAttributes","type":"bytes8"},{"internalType":"bytes8","name":"xFAM","type":"bytes8"},{"internalType":"bytes","name":"mrTd","type":"bytes"},{"internalType":"bytes","name":"mrConfigId","type":"bytes"},{"internalType":"bytes","name":"mrOwner","type":"bytes"},{"internalType":"bytes","name":"mrOwnerConfig","type":"bytes"},{"internalType":"bytes","name":"rtMr0","type":"bytes"},{"internalType":"bytes","name":"rtMr1","type":"bytes"},{"internalType":"bytes","name":"rtMr2","type":"bytes"},{"internalType":"bytes","name":"rtMr3","type":"bytes"},{"internalType":"bytes","name":"reportData","type":"bytes"}],"internalType":"struct TD10ReportBody","name":"parsedReportBody","type":"tuple"},{"internalType":"bytes","name":"extendedRegistrationData","type":"bytes"},{"internalType":"bytes32","name":"quoteHash","type":"bytes32"}],"internalType":"struct IFlashtestationRegistry.RegisteredTEE","name":"registration","type":"tuple"}],"name":"workloadIdForTDRegistration","outputs":[{"internalType":"WorkloadId","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"}]Contract Creation Code
0x60a0806040523460295730608052613263908161002e8239608051818181610a3801526110790152f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c80632dd8abfe14611e4c578063485cc955146116b05780634d37fc7a146113365780634f1ef286146110105780634f3a415a14610ab057806352d1902d146109f35780635c40e542146109095780636931164e146108cd578063715018a6146107f3578063730169231461079b5780637b1039991461074a5780637dec71a9146106f95780637ecebe001461069657806384b0196e146104f15780638da5cb5b14610481578063abd45d21146102fc578063ad3cb1cc1461027b578063b33d59da14610237578063d2753561146101e8578063f2fde38b1461019f5763f698da2514610100575f80fd5b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602061013861310e565b610140613178565b60405190838201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261019060c082612063565b519020604051908152f35b5f80fd5b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576101e66101d9611feb565b6101e1612d2c565b612b6a565b005b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576040610229610224611feb565b6127d1565b825191151582526020820152f35b3461019b5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576101e6610271611fad565b6024359033612c57565b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576102f86040516102ba604082612063565b600581527f352e302e30000000000000000000000000000000000000000000000000000000602082015260405191829160208352602083019061215f565b0390f35b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576060602060405161033b81612047565b82815201526004355f525f60205260405f2060016040519161035c83612047565b61036581612695565b835201805461037381612349565b916103816040519384612063565b81835260208301905f5260205f205f915b838310610464576103c1868660208201908152604051928392602084525160406020850152606084019061215f565b9051907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0838203016040840152815180825260208201916020808360051b8301019401925f915b8383106104155786860387f35b919395509193602080610452837fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08660019603018752895161215f565b97019301930190928695949293610408565b60016020819261047385612695565b815201920192019190610392565b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602073ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005416604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054158061066d575b1561060f576105b36105586124b1565b6105606125c2565b60206105c1604051926105738385612063565b5f84525f3681376040519586957f0f00000000000000000000000000000000000000000000000000000000000000875260e08588015260e087019061215f565b90858203604087015261215f565b4660608501523060808501525f60a085015283810360c08501528180845192838152019301915f5b8281106105f857505050500390f35b8351855286955093810193928101926001016105e9565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4549503731323a20556e696e697469616c697a656400000000000000000000006044820152fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015415610548565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5773ffffffffffffffffffffffffffffffffffffffff6106e2611feb565b165f526002602052602060405f2054604051908152f35b3461019b5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576020610742610735611fad565b6044359060243590612463565b604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760206040517f93b3c192de39a93da71b94fb9fadb8e913f752a2e9ea950a33266a81fcbf2ffc8152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57610829612d2c565b5f73ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300547fffffffffffffffffffffffff000000000000000000000000000000000000000081167f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760206107426004356123c6565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57600435610943612d2c565b805f525f60205261095760405f20546122f8565b156109cb57805f525f602052600160405f2061097281612377565b018054905f8155816109a6575b827f56c387a9be1bf0e0e4f852c577a225db98e8253ad401d1b4ea73926f27d6af095f80a2005b5f5260205f20908101905b8181101561097f57806109c5600192612377565b016109b1565b7f22faf042000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5773ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163003610a885760206040517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b7fe07c8dba000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461019b5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760043560243567ffffffffffffffff811161019b57610b02903690600401611fbd565b919060443567ffffffffffffffff811161019b573660238201121561019b5780600401359167ffffffffffffffff831161019b5760248360051b8301019036821161019b57610b4f612d2c565b8515610fe8578315610fc057845f525f602052610b6f60405f20546122f8565b610f9857610b8b9060405196610b8488612047565b36916120de565b8552610b9683612349565b92610ba46040519485612063565b83526024820191602084015b828410610f57575050505060208301908152815f525f60205260405f20925192835167ffffffffffffffff8111610e2057610beb82546122f8565b601f8111610f27575b506020601f8211600114610e85579080610c469260019596975f92610e7a575b50507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b81555b019051805190680100000000000000008211610e20578254828455808310610e4d575b50602001915f5260205f20915f905b828210610ca957847fcbb92e241e191fed6d0b0da0a918c7dcf595e77d868e2e3bf9e6b0b91589c7ad5f80a2005b805180519067ffffffffffffffff8211610e2057610cc786546122f8565b601f8111610de5575b50602090601f8311600114610d3f5792610d25836001959460209487965f92610d345750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b87555b01940191019092610c7b565b015190508b80610c14565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0831691875f52815f20925f5b818110610dcd5750936020936001969387969383889510610d96575b505050811b018755610d28565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690558a8080610d89565b92936020600181928786015181550195019301610d6d565b610e1090875f5260205f20601f850160051c81019160208610610e16575b601f0160051c0190612361565b87610cd0565b9091508190610e03565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b835f528260205f2091820191015b818110610e685750610c6c565b80610e74600192612377565b01610e5b565b015190508780610c14565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0821695835f52815f20965f5b818110610f0f5750916001959697918487959410610ed8575b505050811b018155610c49565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055868080610ecb565b83830151895560019098019760209384019301610eb2565b610f5190835f5260205f20601f840160051c81019160208510610e1657601f0160051c0190612361565b85610bf4565b833567ffffffffffffffff811161019b5782013660438201121561019b57602091610f8d839236906044602482013591016120de565b815201930192610bb0565b7f72477348000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f6890d9d4000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f8423f262000000000000000000000000000000000000000000000000000000005f5260045ffd5b60407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57611042611feb565b60243567ffffffffffffffff811161019b57611062903690600401612114565b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168030149081156112f4575b50610a88576110b1612d2c565b73ffffffffffffffffffffffffffffffffffffffff8216916040517f52d1902d000000000000000000000000000000000000000000000000000000008152602081600481875afa5f91816112c0575b5061113157837f4c9c8ce3000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8592036112955750813b1561126a57807fffffffffffffffffffffffff00000000000000000000000000000000000000007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611239575f808360206101e695519101845af43d15611231573d91611215836120a4565b926112236040519485612063565b83523d5f602085013e6131bd565b6060916131bd565b50503461124257005b7fb398979f000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4c9c8ce3000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7faa1d49a4000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b9091506020813d6020116112ec575b816112dc60209383612063565b8101031261019b57519085611100565b3d91506112cf565b905073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc54161415836110a4565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760043567ffffffffffffffff811161019b5760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc823603011261019b57604051906113b08261200e565b8060040135801515810361019b578252602481013567ffffffffffffffff811161019b576113e49060043691840101612114565b6020830152604481013567ffffffffffffffff811161019b5781016101e07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc823603011261019b57604051906114398261202a565b60048101357fffffffffffffffffffffffffffffffff000000000000000000000000000000008116810361019b578252602481013567ffffffffffffffff811161019b5761148d9060043691840101612114565b6020830152604481013567ffffffffffffffff811161019b576114b69060043691840101612114565b60408301526114c760648201612132565b60608301526114d860848201612132565b60808301526114e960a48201612132565b60a083015260c481013567ffffffffffffffff811161019b576115129060043691840101612114565b60c083015260e481013567ffffffffffffffff811161019b5761153b9060043691840101612114565b60e083015261010481013567ffffffffffffffff811161019b576115659060043691840101612114565b61010083015261012481013567ffffffffffffffff811161019b576115909060043691840101612114565b61012083015261014481013567ffffffffffffffff811161019b576115bb9060043691840101612114565b61014083015261016481013567ffffffffffffffff811161019b576115e69060043691840101612114565b61016083015261018481013567ffffffffffffffff811161019b576116119060043691840101612114565b6101808301526101a481013567ffffffffffffffff811161019b5761163c9060043691840101612114565b6101a08301526101c48101359067ffffffffffffffff821161019b5760046116679236920101612114565b6101c0820152604083015260648101359167ffffffffffffffff831161019b5760846107429261169f60209560043691840101612114565b6060840152013560808201526121a2565b3461019b5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576116e7611feb565b60243573ffffffffffffffffffffffffffffffffffffffff811680910361019b577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460ff8160401c16159267ffffffffffffffff821680159081611e44575b6001149081611e3a575b159081611e31575b50611e0957818460017fffffffffffffffffffffffffffffffffffffffffffffffff00000000000000006117c19516177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055611db4575b506117b9613028565b6101e1613028565b6117c9613028565b6040918251926117d98185612063565b601284527f426c6f636b4275696c646572506f6c696379000000000000000000000000000060208501528051936118108286612063565b600185527f31000000000000000000000000000000000000000000000000000000000000006020860152611842613028565b61184a613028565b80519067ffffffffffffffff8211610e20576118867fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102546122f8565b601f8111611d47575b50602090601f8311600114611c67576118dc92915f9183610e7a5750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102555b835167ffffffffffffffff8111610e205761193a7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103546122f8565b601f8111611bfa575b50602094601f8211600114611b1c576119939293949582915f92611b115750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101558215611ae957827fffffffffffffffffffffffff0000000000000000000000000000000000000000600154161760015551917f27fe5f0c1c3b1ed427cc63d0f05759ffdecf9aec9e18d31ef366fc8a6cb5dc3b5f80a2611a5857005b60207fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2917fffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005560018152a1005b7f11a1e697000000000000000000000000000000000000000000000000000000005f5260045ffd5b015190508680610c14565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08216957fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f52805f20915f5b888110611be257508360019596979810611bab575b505050811b017fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103556119b6565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055858080611b7e565b91926020600181928685015181550194019201611b69565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f52611c61907f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b75601f840160051c81019160208510610e1657601f0160051c0190612361565b85611943565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08316917fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f52815f20925f5b818110611d2f5750908460019594939210611cf8575b505050811b017fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102556118ff565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055868080611ccb565b92936020600181928786015181550195019301611cb5565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f52611dae907f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d601f850160051c81019160208610610e1657601f0160051c0190612361565b8661188f565b7fffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055846117b0565b7ff92ee8a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b90501585611759565b303b159150611751565b859150611747565b3461019b5760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57611e83611fad565b602435604435916064359267ffffffffffffffff841161019b57611ed7611ed1611eb4611ee0963690600401611fbd565b9190611ec9611ec4868989612463565b6123c6565b9236916120de565b90612d98565b90959195612dd2565b73ffffffffffffffffffffffffffffffffffffffff841690815f52600260205260405f2054808203611f7f5750505f52600260205260405f20928354937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8514611f525760016101e695019055612c57565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b7f06427aeb000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b6004359060ff8216820361019b57565b9181601f8401121561019b5782359167ffffffffffffffff831161019b576020838186019501011161019b57565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361019b57565b60a0810190811067ffffffffffffffff821117610e2057604052565b6101e0810190811067ffffffffffffffff821117610e2057604052565b6040810190811067ffffffffffffffff821117610e2057604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117610e2057604052565b67ffffffffffffffff8111610e2057601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b9291926120ea826120a4565b916120f86040519384612063565b82948184528183011161019b578281602093845f960137010152565b9080601f8301121561019b5781602061212f933591016120de565b90565b35907fffffffffffffffff0000000000000000000000000000000000000000000000008216820361019b57565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602080948051918291828752018686015e5f8582860101520116010190565b6040015160c081015190610140810151610160820151916101808101516101a082015160e08301519060a08401517fffffffffffffffff0000000000000000000000000000000000000000000000001678030000000000000000000000000000000000000000000000001893608001517fffffffff2fffffff00000000000000000000000000000000000000000000000016926040519687966020880199805160208192018c5e880160208101915f83528051926020849201905e016020015f815281516020819301825e015f815281516020819301825e015f815281516020819301825e015f815281516020819301825e01917fffffffffffffffff0000000000000000000000000000000000000000000000001682526008820152037ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0810182526010016122f29082612063565b51902090565b90600182811c9216801561233f575b602083101461231257565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b91607f1691612307565b67ffffffffffffffff8111610e205760051b60200190565b81811061236c575050565b5f8155600101612361565b61238181546122f8565b908161238b575050565b81601f5f931160011461239d5750555b565b818352602083206123b991601f0160051c810190600101612361565b8082528160208120915555565b6042906123d161310e565b6123d9613178565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261242a60c082612063565b51902090604051917f19010000000000000000000000000000000000000000000000000000000000008352600283015260228201522090565b916040519160ff60208401947f93b3c192de39a93da71b94fb9fadb8e913f752a2e9ea950a33266a81fcbf2ffc865216604084015260608301526080820152608081526122f260a082612063565b604051905f827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10254916124e3836122f8565b80835292600181169081156125855750600114612507575b61239b92500383612063565b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f90815290917f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d5b81831061256957505090602061239b928201016124fb565b6020919350806001915483858901015201910190918492612551565b6020925061239b9491507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001682840152151560051b8201016124fb565b604051905f827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10354916125f4836122f8565b808352926001811690811561258557506001146126175761239b92500383612063565b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b81831061267957505090602061239b928201016124fb565b6020919350806001915483858901015201910190918492612661565b9060405191825f8254926126a8846122f8565b808452936001811690811561271157506001146126cd575b5061239b92500383612063565b90505f9291925260205f20905f915b8183106126f557505090602061239b928201015f6126c0565b60209193508060019154838589010152019101909184926126dc565b6020935061239b9592507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0091501682840152151560051b8201015f6126c0565b5190811515820361019b57565b81601f8201121561019b57805190612775826120a4565b926127836040519485612063565b8284526020838301011161019b57815f9260208093018386015e8301015290565b51907fffffffffffffffff0000000000000000000000000000000000000000000000008216820361019b57565b5f73ffffffffffffffffffffffffffffffffffffffff602481600154169360405194859384927f727310620000000000000000000000000000000000000000000000000000000084521660048301525afa908115612b5f575f9161286c575b5080511561286557612841906121a2565b805f525f60205261285560405f20546122f8565b61286057505f905f90565b600191565b505f905f90565b90503d805f833e61287d8183612063565b81019060408183031261019b5761289381612751565b5060208101519067ffffffffffffffff821161019b57019060a08282031261019b57604051916128c28361200e565b6128cb81612751565b8352602081015167ffffffffffffffff811161019b57826128ed91830161275e565b6020840152604081015167ffffffffffffffff811161019b5781016101e08184031261019b57604051906129208261202a565b80517fffffffffffffffffffffffffffffffff000000000000000000000000000000008116810361019b578252602081015167ffffffffffffffff811161019b578461296d91830161275e565b6020830152604081015167ffffffffffffffff811161019b578461299291830161275e565b60408301526129a3606082016127a4565b60608301526129b4608082016127a4565b60808301526129c560a082016127a4565b60a083015260c081015167ffffffffffffffff811161019b57846129ea91830161275e565b60c083015260e081015167ffffffffffffffff811161019b5784612a0f91830161275e565b60e083015261010081015167ffffffffffffffff811161019b5784612a3591830161275e565b61010083015261012081015167ffffffffffffffff811161019b5784612a5c91830161275e565b61012083015261014081015167ffffffffffffffff811161019b5784612a8391830161275e565b61014083015261016081015167ffffffffffffffff811161019b5784612aaa91830161275e565b61016083015261018081015167ffffffffffffffff811161019b5784612ad191830161275e565b6101808301526101a081015167ffffffffffffffff811161019b5784612af891830161275e565b6101a08301526101c08101519067ffffffffffffffff821161019b57612b209185910161275e565b6101c08201526040840152606081015167ffffffffffffffff811161019b57608092612b4d91830161275e565b6060840152015160808201525f612830565b6040513d5f823e3d90fd5b73ffffffffffffffffffffffffffffffffffffffff168015612c2b5773ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054827fffffffffffffffffffffffff00000000000000000000000000000000000000008216177f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3565b7f1e4fbdf7000000000000000000000000000000000000000000000000000000005f525f60045260245ffd5b91612c6183612eaa565b929015612cea57827f3fa039a23466a52e08acb25376ac7d81de184fa6549ffffb2fc920c47cb623ed949260ff612ce59373ffffffffffffffffffffffffffffffffffffffff965f525f602052612cba60405f20612695565b936040519788971687526020870152166040850152606084015260a0608084015260a083019061215f565b0390a1565b73ffffffffffffffffffffffffffffffffffffffff847f4c547670000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b73ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054163303612d6c57565b7f118cdaa7000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b8151919060418303612dc857612dc19250602082015190606060408401519301515f1a9061307f565b9192909190565b50505f9160029190565b6004811015612e7d5780612de4575050565b60018103612e14577ff645eedf000000000000000000000000000000000000000000000000000000005f5260045ffd5b60028103612e4857507ffce698f7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b600314612e525750565b7fd78bce0c000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b73ffffffffffffffffffffffffffffffffffffffff600154166040517fa8af4ff500000000000000000000000000000000000000000000000000000000815260408160248173ffffffffffffffffffffffffffffffffffffffff8716958660048301525afa908115612b5f575f905f92612fe7575b5015612fde57815f52600360205260405f209160405193612f3f85612047565b60018454948587520154806020870152838515159182612fd4575b505015612f82575050505f525f602052612f7760405f20546122f8565b156128655751600191565b909250612f91919493506127d1565b93819291612fa0575b50509190565b60019060405192612fb084612047565b868452602084019182525f52600360205260405f2092518355519101555f80612f9a565b149050835f612f5a565b5050505f905f90565b9150506040813d604011613020575b8161300360409383612063565b8101031261019b57602061301682612751565b910151905f612f1f565b3d9150612ff6565b60ff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460401c161561305757565b7fd7e6bcf8000000000000000000000000000000000000000000000000000000005f5260045ffd5b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411613103579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15612b5f575f5173ffffffffffffffffffffffffffffffffffffffff8116156130f957905f905f90565b505f906001905f90565b5050505f9160039190565b6131166124b1565b8051908115613126576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1005480156131535790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b6131806125c2565b8051908115613190576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015480156131535790565b906131fa57508051156131d257602081519101fd5b7fd6bda275000000000000000000000000000000000000000000000000000000005f5260045ffd5b8151158061324d575b61320b575090565b73ffffffffffffffffffffffffffffffffffffffff907f9996b315000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b50803b1561320356fea164736f6c634300081c000a
Deployed Bytecode
0x60806040526004361015610011575f80fd5b5f3560e01c80632dd8abfe14611e4c578063485cc955146116b05780634d37fc7a146113365780634f1ef286146110105780634f3a415a14610ab057806352d1902d146109f35780635c40e542146109095780636931164e146108cd578063715018a6146107f3578063730169231461079b5780637b1039991461074a5780637dec71a9146106f95780637ecebe001461069657806384b0196e146104f15780638da5cb5b14610481578063abd45d21146102fc578063ad3cb1cc1461027b578063b33d59da14610237578063d2753561146101e8578063f2fde38b1461019f5763f698da2514610100575f80fd5b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602061013861310e565b610140613178565b60405190838201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261019060c082612063565b519020604051908152f35b5f80fd5b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576101e66101d9611feb565b6101e1612d2c565b612b6a565b005b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576040610229610224611feb565b6127d1565b825191151582526020820152f35b3461019b5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576101e6610271611fad565b6024359033612c57565b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576102f86040516102ba604082612063565b600581527f352e302e30000000000000000000000000000000000000000000000000000000602082015260405191829160208352602083019061215f565b0390f35b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576060602060405161033b81612047565b82815201526004355f525f60205260405f2060016040519161035c83612047565b61036581612695565b835201805461037381612349565b916103816040519384612063565b81835260208301905f5260205f205f915b838310610464576103c1868660208201908152604051928392602084525160406020850152606084019061215f565b9051907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0838203016040840152815180825260208201916020808360051b8301019401925f915b8383106104155786860387f35b919395509193602080610452837fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08660019603018752895161215f565b97019301930190928695949293610408565b60016020819261047385612695565b815201920192019190610392565b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602073ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005416604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054158061066d575b1561060f576105b36105586124b1565b6105606125c2565b60206105c1604051926105738385612063565b5f84525f3681376040519586957f0f00000000000000000000000000000000000000000000000000000000000000875260e08588015260e087019061215f565b90858203604087015261215f565b4660608501523060808501525f60a085015283810360c08501528180845192838152019301915f5b8281106105f857505050500390f35b8351855286955093810193928101926001016105e9565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4549503731323a20556e696e697469616c697a656400000000000000000000006044820152fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015415610548565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5773ffffffffffffffffffffffffffffffffffffffff6106e2611feb565b165f526002602052602060405f2054604051908152f35b3461019b5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576020610742610735611fad565b6044359060243590612463565b604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760206040517f93b3c192de39a93da71b94fb9fadb8e913f752a2e9ea950a33266a81fcbf2ffc8152f35b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57610829612d2c565b5f73ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300547fffffffffffffffffffffffff000000000000000000000000000000000000000081167f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760206107426004356123c6565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57600435610943612d2c565b805f525f60205261095760405f20546122f8565b156109cb57805f525f602052600160405f2061097281612377565b018054905f8155816109a6575b827f56c387a9be1bf0e0e4f852c577a225db98e8253ad401d1b4ea73926f27d6af095f80a2005b5f5260205f20908101905b8181101561097f57806109c5600192612377565b016109b1565b7f22faf042000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461019b575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5773ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000e3aeb7ab94de0b98f3b61953ed1345cad4d564ec163003610a885760206040517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b7fe07c8dba000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461019b5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760043560243567ffffffffffffffff811161019b57610b02903690600401611fbd565b919060443567ffffffffffffffff811161019b573660238201121561019b5780600401359167ffffffffffffffff831161019b5760248360051b8301019036821161019b57610b4f612d2c565b8515610fe8578315610fc057845f525f602052610b6f60405f20546122f8565b610f9857610b8b9060405196610b8488612047565b36916120de565b8552610b9683612349565b92610ba46040519485612063565b83526024820191602084015b828410610f57575050505060208301908152815f525f60205260405f20925192835167ffffffffffffffff8111610e2057610beb82546122f8565b601f8111610f27575b506020601f8211600114610e85579080610c469260019596975f92610e7a575b50507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b81555b019051805190680100000000000000008211610e20578254828455808310610e4d575b50602001915f5260205f20915f905b828210610ca957847fcbb92e241e191fed6d0b0da0a918c7dcf595e77d868e2e3bf9e6b0b91589c7ad5f80a2005b805180519067ffffffffffffffff8211610e2057610cc786546122f8565b601f8111610de5575b50602090601f8311600114610d3f5792610d25836001959460209487965f92610d345750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b87555b01940191019092610c7b565b015190508b80610c14565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0831691875f52815f20925f5b818110610dcd5750936020936001969387969383889510610d96575b505050811b018755610d28565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690558a8080610d89565b92936020600181928786015181550195019301610d6d565b610e1090875f5260205f20601f850160051c81019160208610610e16575b601f0160051c0190612361565b87610cd0565b9091508190610e03565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b835f528260205f2091820191015b818110610e685750610c6c565b80610e74600192612377565b01610e5b565b015190508780610c14565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0821695835f52815f20965f5b818110610f0f5750916001959697918487959410610ed8575b505050811b018155610c49565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055868080610ecb565b83830151895560019098019760209384019301610eb2565b610f5190835f5260205f20601f840160051c81019160208510610e1657601f0160051c0190612361565b85610bf4565b833567ffffffffffffffff811161019b5782013660438201121561019b57602091610f8d839236906044602482013591016120de565b815201930192610bb0565b7f72477348000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f6890d9d4000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f8423f262000000000000000000000000000000000000000000000000000000005f5260045ffd5b60407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57611042611feb565b60243567ffffffffffffffff811161019b57611062903690600401612114565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000e3aeb7ab94de0b98f3b61953ed1345cad4d564ec168030149081156112f4575b50610a88576110b1612d2c565b73ffffffffffffffffffffffffffffffffffffffff8216916040517f52d1902d000000000000000000000000000000000000000000000000000000008152602081600481875afa5f91816112c0575b5061113157837f4c9c8ce3000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8592036112955750813b1561126a57807fffffffffffffffffffffffff00000000000000000000000000000000000000007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611239575f808360206101e695519101845af43d15611231573d91611215836120a4565b926112236040519485612063565b83523d5f602085013e6131bd565b6060916131bd565b50503461124257005b7fb398979f000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4c9c8ce3000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7faa1d49a4000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b9091506020813d6020116112ec575b816112dc60209383612063565b8101031261019b57519085611100565b3d91506112cf565b905073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc54161415836110a4565b3461019b5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b5760043567ffffffffffffffff811161019b5760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc823603011261019b57604051906113b08261200e565b8060040135801515810361019b578252602481013567ffffffffffffffff811161019b576113e49060043691840101612114565b6020830152604481013567ffffffffffffffff811161019b5781016101e07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc823603011261019b57604051906114398261202a565b60048101357fffffffffffffffffffffffffffffffff000000000000000000000000000000008116810361019b578252602481013567ffffffffffffffff811161019b5761148d9060043691840101612114565b6020830152604481013567ffffffffffffffff811161019b576114b69060043691840101612114565b60408301526114c760648201612132565b60608301526114d860848201612132565b60808301526114e960a48201612132565b60a083015260c481013567ffffffffffffffff811161019b576115129060043691840101612114565b60c083015260e481013567ffffffffffffffff811161019b5761153b9060043691840101612114565b60e083015261010481013567ffffffffffffffff811161019b576115659060043691840101612114565b61010083015261012481013567ffffffffffffffff811161019b576115909060043691840101612114565b61012083015261014481013567ffffffffffffffff811161019b576115bb9060043691840101612114565b61014083015261016481013567ffffffffffffffff811161019b576115e69060043691840101612114565b61016083015261018481013567ffffffffffffffff811161019b576116119060043691840101612114565b6101808301526101a481013567ffffffffffffffff811161019b5761163c9060043691840101612114565b6101a08301526101c48101359067ffffffffffffffff821161019b5760046116679236920101612114565b6101c0820152604083015260648101359167ffffffffffffffff831161019b5760846107429261169f60209560043691840101612114565b6060840152013560808201526121a2565b3461019b5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b576116e7611feb565b60243573ffffffffffffffffffffffffffffffffffffffff811680910361019b577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460ff8160401c16159267ffffffffffffffff821680159081611e44575b6001149081611e3a575b159081611e31575b50611e0957818460017fffffffffffffffffffffffffffffffffffffffffffffffff00000000000000006117c19516177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055611db4575b506117b9613028565b6101e1613028565b6117c9613028565b6040918251926117d98185612063565b601284527f426c6f636b4275696c646572506f6c696379000000000000000000000000000060208501528051936118108286612063565b600185527f31000000000000000000000000000000000000000000000000000000000000006020860152611842613028565b61184a613028565b80519067ffffffffffffffff8211610e20576118867fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102546122f8565b601f8111611d47575b50602090601f8311600114611c67576118dc92915f9183610e7a5750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102555b835167ffffffffffffffff8111610e205761193a7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103546122f8565b601f8111611bfa575b50602094601f8211600114611b1c576119939293949582915f92611b115750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101558215611ae957827fffffffffffffffffffffffff0000000000000000000000000000000000000000600154161760015551917f27fe5f0c1c3b1ed427cc63d0f05759ffdecf9aec9e18d31ef366fc8a6cb5dc3b5f80a2611a5857005b60207fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2917fffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005560018152a1005b7f11a1e697000000000000000000000000000000000000000000000000000000005f5260045ffd5b015190508680610c14565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08216957fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f52805f20915f5b888110611be257508360019596979810611bab575b505050811b017fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103556119b6565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055858080611b7e565b91926020600181928685015181550194019201611b69565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f52611c61907f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b75601f840160051c81019160208510610e1657601f0160051c0190612361565b85611943565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08316917fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f52815f20925f5b818110611d2f5750908460019594939210611cf8575b505050811b017fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102556118ff565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c19169055868080611ccb565b92936020600181928786015181550195019301611cb5565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f52611dae907f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d601f850160051c81019160208610610e1657601f0160051c0190612361565b8661188f565b7fffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055846117b0565b7ff92ee8a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b90501585611759565b303b159150611751565b859150611747565b3461019b5760807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261019b57611e83611fad565b602435604435916064359267ffffffffffffffff841161019b57611ed7611ed1611eb4611ee0963690600401611fbd565b9190611ec9611ec4868989612463565b6123c6565b9236916120de565b90612d98565b90959195612dd2565b73ffffffffffffffffffffffffffffffffffffffff841690815f52600260205260405f2054808203611f7f5750505f52600260205260405f20928354937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8514611f525760016101e695019055612c57565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b7f06427aeb000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b6004359060ff8216820361019b57565b9181601f8401121561019b5782359167ffffffffffffffff831161019b576020838186019501011161019b57565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361019b57565b60a0810190811067ffffffffffffffff821117610e2057604052565b6101e0810190811067ffffffffffffffff821117610e2057604052565b6040810190811067ffffffffffffffff821117610e2057604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117610e2057604052565b67ffffffffffffffff8111610e2057601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b9291926120ea826120a4565b916120f86040519384612063565b82948184528183011161019b578281602093845f960137010152565b9080601f8301121561019b5781602061212f933591016120de565b90565b35907fffffffffffffffff0000000000000000000000000000000000000000000000008216820361019b57565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602080948051918291828752018686015e5f8582860101520116010190565b6040015160c081015190610140810151610160820151916101808101516101a082015160e08301519060a08401517fffffffffffffffff0000000000000000000000000000000000000000000000001678030000000000000000000000000000000000000000000000001893608001517fffffffff2fffffff00000000000000000000000000000000000000000000000016926040519687966020880199805160208192018c5e880160208101915f83528051926020849201905e016020015f815281516020819301825e015f815281516020819301825e015f815281516020819301825e015f815281516020819301825e01917fffffffffffffffff0000000000000000000000000000000000000000000000001682526008820152037ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0810182526010016122f29082612063565b51902090565b90600182811c9216801561233f575b602083101461231257565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b91607f1691612307565b67ffffffffffffffff8111610e205760051b60200190565b81811061236c575050565b5f8155600101612361565b61238181546122f8565b908161238b575050565b81601f5f931160011461239d5750555b565b818352602083206123b991601f0160051c810190600101612361565b8082528160208120915555565b6042906123d161310e565b6123d9613178565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261242a60c082612063565b51902090604051917f19010000000000000000000000000000000000000000000000000000000000008352600283015260228201522090565b916040519160ff60208401947f93b3c192de39a93da71b94fb9fadb8e913f752a2e9ea950a33266a81fcbf2ffc865216604084015260608301526080820152608081526122f260a082612063565b604051905f827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10254916124e3836122f8565b80835292600181169081156125855750600114612507575b61239b92500383612063565b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1025f90815290917f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d5b81831061256957505090602061239b928201016124fb565b6020919350806001915483858901015201910190918492612551565b6020925061239b9491507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001682840152151560051b8201016124fb565b604051905f827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10354916125f4836122f8565b808352926001811690811561258557506001146126175761239b92500383612063565b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1035f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b81831061267957505090602061239b928201016124fb565b6020919350806001915483858901015201910190918492612661565b9060405191825f8254926126a8846122f8565b808452936001811690811561271157506001146126cd575b5061239b92500383612063565b90505f9291925260205f20905f915b8183106126f557505090602061239b928201015f6126c0565b60209193508060019154838589010152019101909184926126dc565b6020935061239b9592507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0091501682840152151560051b8201015f6126c0565b5190811515820361019b57565b81601f8201121561019b57805190612775826120a4565b926127836040519485612063565b8284526020838301011161019b57815f9260208093018386015e8301015290565b51907fffffffffffffffff0000000000000000000000000000000000000000000000008216820361019b57565b5f73ffffffffffffffffffffffffffffffffffffffff602481600154169360405194859384927f727310620000000000000000000000000000000000000000000000000000000084521660048301525afa908115612b5f575f9161286c575b5080511561286557612841906121a2565b805f525f60205261285560405f20546122f8565b61286057505f905f90565b600191565b505f905f90565b90503d805f833e61287d8183612063565b81019060408183031261019b5761289381612751565b5060208101519067ffffffffffffffff821161019b57019060a08282031261019b57604051916128c28361200e565b6128cb81612751565b8352602081015167ffffffffffffffff811161019b57826128ed91830161275e565b6020840152604081015167ffffffffffffffff811161019b5781016101e08184031261019b57604051906129208261202a565b80517fffffffffffffffffffffffffffffffff000000000000000000000000000000008116810361019b578252602081015167ffffffffffffffff811161019b578461296d91830161275e565b6020830152604081015167ffffffffffffffff811161019b578461299291830161275e565b60408301526129a3606082016127a4565b60608301526129b4608082016127a4565b60808301526129c560a082016127a4565b60a083015260c081015167ffffffffffffffff811161019b57846129ea91830161275e565b60c083015260e081015167ffffffffffffffff811161019b5784612a0f91830161275e565b60e083015261010081015167ffffffffffffffff811161019b5784612a3591830161275e565b61010083015261012081015167ffffffffffffffff811161019b5784612a5c91830161275e565b61012083015261014081015167ffffffffffffffff811161019b5784612a8391830161275e565b61014083015261016081015167ffffffffffffffff811161019b5784612aaa91830161275e565b61016083015261018081015167ffffffffffffffff811161019b5784612ad191830161275e565b6101808301526101a081015167ffffffffffffffff811161019b5784612af891830161275e565b6101a08301526101c08101519067ffffffffffffffff821161019b57612b209185910161275e565b6101c08201526040840152606081015167ffffffffffffffff811161019b57608092612b4d91830161275e565b6060840152015160808201525f612830565b6040513d5f823e3d90fd5b73ffffffffffffffffffffffffffffffffffffffff168015612c2b5773ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054827fffffffffffffffffffffffff00000000000000000000000000000000000000008216177f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3565b7f1e4fbdf7000000000000000000000000000000000000000000000000000000005f525f60045260245ffd5b91612c6183612eaa565b929015612cea57827f3fa039a23466a52e08acb25376ac7d81de184fa6549ffffb2fc920c47cb623ed949260ff612ce59373ffffffffffffffffffffffffffffffffffffffff965f525f602052612cba60405f20612695565b936040519788971687526020870152166040850152606084015260a0608084015260a083019061215f565b0390a1565b73ffffffffffffffffffffffffffffffffffffffff847f4c547670000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b73ffffffffffffffffffffffffffffffffffffffff7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054163303612d6c57565b7f118cdaa7000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b8151919060418303612dc857612dc19250602082015190606060408401519301515f1a9061307f565b9192909190565b50505f9160029190565b6004811015612e7d5780612de4575050565b60018103612e14577ff645eedf000000000000000000000000000000000000000000000000000000005f5260045ffd5b60028103612e4857507ffce698f7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b600314612e525750565b7fd78bce0c000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b73ffffffffffffffffffffffffffffffffffffffff600154166040517fa8af4ff500000000000000000000000000000000000000000000000000000000815260408160248173ffffffffffffffffffffffffffffffffffffffff8716958660048301525afa908115612b5f575f905f92612fe7575b5015612fde57815f52600360205260405f209160405193612f3f85612047565b60018454948587520154806020870152838515159182612fd4575b505015612f82575050505f525f602052612f7760405f20546122f8565b156128655751600191565b909250612f91919493506127d1565b93819291612fa0575b50509190565b60019060405192612fb084612047565b868452602084019182525f52600360205260405f2092518355519101555f80612f9a565b149050835f612f5a565b5050505f905f90565b9150506040813d604011613020575b8161300360409383612063565b8101031261019b57602061301682612751565b910151905f612f1f565b3d9150612ff6565b60ff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460401c161561305757565b7fd7e6bcf8000000000000000000000000000000000000000000000000000000005f5260045ffd5b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411613103579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15612b5f575f5173ffffffffffffffffffffffffffffffffffffffff8116156130f957905f905f90565b505f906001905f90565b5050505f9160039190565b6131166124b1565b8051908115613126576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1005480156131535790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b6131806125c2565b8051908115613190576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015480156131535790565b906131fa57508051156131d257602081519101fd5b7fd6bda275000000000000000000000000000000000000000000000000000000005f5260045ffd5b8151158061324d575b61320b575090565b73ffffffffffffffffffffffffffffffffffffffff907f9996b315000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b50803b1561320356fea164736f6c634300081c000a
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.