From bbb03bf2e4cffc56fd14b2d80313188226cf9b44 Mon Sep 17 00:00:00 2001 From: Lyova Potyomkin Date: Wed, 27 Nov 2024 20:46:21 +0200 Subject: [PATCH] chore: replace helpers with imported libs --- package.json | 55 +- pnpm-lock.yaml | 8 + src/handlers/ERC1271Handler.sol | 2 +- src/helpers/Base64.sol | 203 ----- src/helpers/EIP712.sol | 1058 --------------------------- src/validators/WebAuthValidator.sol | 4 +- 6 files changed, 39 insertions(+), 1291 deletions(-) delete mode 100644 src/helpers/Base64.sol delete mode 100644 src/helpers/EIP712.sol diff --git a/package.json b/package.json index 426736fb..3c45626b 100644 --- a/package.json +++ b/package.json @@ -25,36 +25,28 @@ "@commitlint/cli": "19.5.0", "@commitlint/config-conventional": "19.5.0", "@eslint/js": "9.11.1", - "@simplewebauthn/browser": "^10.0.0", - "@simplewebauthn/server": "^10.0.1", - "@simplewebauthn/types": "^10.0.0", - "@stylistic/eslint-plugin": "2.8.0", - "@swc-node/register": "1.10.9", - "@swc/core": "1.7.26", - "cspell": "8.14.4", - "eslint": "9.11.1", - "eslint-plugin-simple-import-sort": "12.1.1", - "globals": "15.9.0", - "husky": "9.1.6", - "lint-staged": "15.2.10", - "markdownlint-cli2": "0.14.0", - "nuxt": "3.13.2", - "nx": "19.8.6", - "prettier": "3.3.3", - "typescript": "5.6.2", - "typescript-eslint": "8.7.0", - "viem": "^2.21.14", "@ethersproject/contracts": "5.7.0", "@ethersproject/providers": "5.7.2", "@hexagon/base64": "1.1.28", "@levischuck/tiny-cbor": "0.2.2", "@matterlabs/hardhat-zksync": "1.2.0", "@matterlabs/hardhat-zksync-deploy": "1.5.0", + "@matterlabs/zksync-contracts": "^0.6.1", + "@nomad-xyz/excessively-safe-call": "^0.0.1-rc.1", "@nomicfoundation/hardhat-chai-matchers": "2.0.8", "@nomicfoundation/hardhat-ethers": "3.0.8", + "@nomicfoundation/hardhat-toolbox": "^5.0.0", "@nomicfoundation/hardhat-verify": "2.0.11", + "@openzeppelin/contracts": "4.9.6", + "@openzeppelin/contracts-upgradeable": "4.9", "@peculiar/asn1-ecc": "2.3.14", "@peculiar/asn1-schema": "2.3.13", + "@simplewebauthn/browser": "^10.0.0", + "@simplewebauthn/server": "^10.0.1", + "@simplewebauthn/types": "^10.0.0", + "@stylistic/eslint-plugin": "2.8.0", + "@swc-node/register": "1.10.9", + "@swc/core": "1.7.26", "@typechain/ethers-v6": "0.5.1", "@typechain/hardhat": "9.1.0", "@types/chai": "4.3.20", @@ -62,24 +54,33 @@ "@types/ini": "4.1.1", "@types/mocha": "10.0.8", "@types/node": "20.16.10", + "bigint-conversion": "^2.4.3", "chai": "4.5.0", + "cspell": "8.14.4", "dotenv": "16.4.5", "elliptic": "6.5.7", + "eslint": "9.11.1", + "eslint-plugin-simple-import-sort": "12.1.1", "ethers": "6.13.2", + "globals": "15.9.0", + "hardhat": "^2.22.12", + "husky": "9.1.6", "ini": "5.0.0", + "lint-staged": "15.2.10", + "markdownlint-cli2": "0.14.0", "mocha": "10.7.3", + "nuxt": "3.13.2", + "nx": "19.8.6", + "prettier": "3.3.3", + "prettier-plugin-solidity": "^1.4.1", "ts-node": "10.9.2", "typechain": "8.3.2", + "typescript": "5.6.2", + "typescript-eslint": "8.7.0", + "viem": "^2.21.14", "zksync-ethers": "6.15.0", - "@matterlabs/zksync-contracts": "^0.6.1", - "@nomad-xyz/excessively-safe-call": "^0.0.1-rc.1", - "@nomicfoundation/hardhat-toolbox": "^5.0.0", - "@openzeppelin/contracts": "4.9.6", - "@openzeppelin/contracts-upgradeable": "4.9", - "bigint-conversion": "^2.4.3", - "hardhat": "^2.22.12", "zksync-sso": "0.0.0-beta.2", - "prettier-plugin-solidity": "^1.4.1" + "solady": "^0.0.273" }, "packageManager": "pnpm@9.11.0" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3a407592..7213fd8d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -161,6 +161,9 @@ importers: prettier-plugin-solidity: specifier: ^1.4.1 version: 1.4.1(prettier@3.3.3) + solady: + specifier: ^0.0.273 + version: 0.0.273 ts-node: specifier: 10.9.2 version: 10.9.2(@swc/core@1.7.26(@swc/helpers@0.5.15))(@types/node@20.16.10)(typescript@5.6.2) @@ -5939,6 +5942,9 @@ packages: smob@1.5.0: resolution: {integrity: sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==} + solady@0.0.273: + resolution: {integrity: sha512-pzIl6AR7Qmlcxh8CNzcdlw7NCp4HnIZgrl4zecGCDSO6e3jWNm7jKkt8uxu7xjmqJ5z7LVgmVAK2QOmnCEvKNA==} + solc@0.8.26: resolution: {integrity: sha512-yiPQNVf5rBFHwN6SIf3TUUvVAFKcQqmSUFeq+fb6pNRCo0ZCgpYOZDi3BVoezCPIAcKrVYd/qXlBLUP9wVrZ9g==} engines: {node: '>=10.0.0'} @@ -13632,6 +13638,8 @@ snapshots: smob@1.5.0: {} + solady@0.0.273: {} + solc@0.8.26(debug@4.3.7): dependencies: command-exists: 1.2.9 diff --git a/src/handlers/ERC1271Handler.sol b/src/handlers/ERC1271Handler.sol index 25bbb749..41bb5885 100644 --- a/src/handlers/ERC1271Handler.sol +++ b/src/handlers/ERC1271Handler.sol @@ -5,7 +5,7 @@ import { IERC1271Upgradeable } from "@openzeppelin/contracts-upgradeable/interfa import { SignatureDecoder } from "../libraries/SignatureDecoder.sol"; import { ValidationHandler } from "./ValidationHandler.sol"; -import { EIP712 } from "../helpers/EIP712.sol"; +import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; /// @title ERC1271Handler /// @author Matter Labs diff --git a/src/helpers/Base64.sol b/src/helpers/Base64.sol deleted file mode 100644 index b4f452fe..00000000 --- a/src/helpers/Base64.sol +++ /dev/null @@ -1,203 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v5.0.0) (utils/Base64.sol) - -pragma solidity ^0.8.24; - -/** - * @dev Provides a set of functions to operate with Base64 strings. - */ -library Base64 { - /** - * @dev Base64 Encoding/Decoding Table - * See sections 4 and 5 of https://datatracker.ietf.org/doc/html/rfc4648 - */ - string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - string internal constant _TABLE_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - - /** - * @dev Converts a `bytes` to its Bytes64 `string` representation. - */ - function encode(bytes memory data) internal pure returns (string memory) { - return _encode(data, _TABLE, true); - } - - /** - * @dev Converts a `bytes` to its Bytes64Url `string` representation. - */ - function encodeURL(bytes memory data) internal pure returns (string memory) { - return _encode(data, _TABLE_URL, false); - } - - /** - * @dev Internal table-agnostic conversion - */ - function _encode(bytes memory data, string memory table, bool withPadding) private pure returns (string memory) { - /** - * Inspired by Brecht Devos (Brechtpd) implementation - MIT license - * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol - */ - if (data.length == 0) return ""; - - // If padding is enabled, the final length should be `bytes` data length divided by 3 rounded up and then - // multiplied by 4 so that it leaves room for padding the last chunk - // - `data.length + 2` -> Round up - // - `/ 3` -> Number of 3-bytes chunks - // - `4 *` -> 4 characters for each chunk - // If padding is disabled, the final length should be `bytes` data length multiplied by 4/3 rounded up as - // opposed to when padding is required to fill the last chunk. - // - `4 *` -> 4 characters for each chunk - // - `data.length + 2` -> Round up - // - `/ 3` -> Number of 3-bytes chunks - uint256 resultLength = withPadding ? 4 * ((data.length + 2) / 3) : (4 * data.length + 2) / 3; - - string memory result = new string(resultLength); - - /// @solidity memory-safe-assembly - assembly { - // Prepare the lookup table (skip the first "length" byte) - let tablePtr := add(table, 1) - - // Prepare result pointer, jump over length - let resultPtr := add(result, 0x20) - let dataPtr := data - let endPtr := add(data, mload(data)) - - // In some cases, the last iteration will read bytes after the end of the data. We cache the value, and - // set it to zero to make sure no dirty bytes are read in that section. - let afterPtr := add(endPtr, 0x20) - let afterCache := mload(afterPtr) - mstore(afterPtr, 0x00) - - // Run over the input, 3 bytes at a time - for {} lt(dataPtr, endPtr) {} { - // Advance 3 bytes - dataPtr := add(dataPtr, 3) - let input := mload(dataPtr) - - // To write each character, shift the 3 byte (24 bits) chunk - // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) - // and apply logical AND with 0x3F to bitmask the least significant 6 bits. - // Use this as an index into the lookup table, mload an entire word - // so the desired character is in the least significant byte, and - // mstore8 this least significant byte into the result and continue. - - mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - - mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) - resultPtr := add(resultPtr, 1) // Advance - } - - // Reset the value that was cached - mstore(afterPtr, afterCache) - - if withPadding { - // When data `bytes` is not exactly 3 bytes long - // it is padded with `=` characters at the end - switch mod(mload(data), 3) - case 1 { - mstore8(sub(resultPtr, 1), 0x3d) - mstore8(sub(resultPtr, 2), 0x3d) - } - case 2 { - mstore8(sub(resultPtr, 1), 0x3d) - } - } - } - - return result; - } - - /// @dev Decodes base64 encoded `data`. - /// @notice Library to encode strings in Base64. - /// author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol) - /// author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol) - /// author Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos - . - /// - /// Supports: - /// - RFC 4648 (both standard and file-safe mode). - /// - RFC 3501 (63: ','). - /// - /// Does not support: - /// - Line breaks. - /// - /// Note: For performance reasons, - /// this function will NOT revert on invalid `data` inputs. - /// Outputs for invalid inputs will simply be undefined behaviour. - /// It is the user's responsibility to ensure that the `data` - /// is a valid base64 encoded string. - function decode(string memory data) internal pure returns (bytes memory result) { - /// @solidity memory-safe-assembly - assembly { - let dataLength := mload(data) - - if dataLength { - let decodedLength := mul(shr(2, dataLength), 3) - - for {} 1 {} { - // If padded. - if iszero(and(dataLength, 3)) { - let t := xor(mload(add(data, dataLength)), 0x3d3d) - // forgefmt: disable-next-item - decodedLength := sub(decodedLength, add(iszero(byte(30, t)), iszero(byte(31, t)))) - break - } - // If non-padded. - decodedLength := add(decodedLength, sub(and(dataLength, 3), 1)) - break - } - result := mload(0x40) - - // Write the length of the bytes. - mstore(result, decodedLength) - - // Skip the first slot, which stores the length. - let ptr := add(result, 0x20) - let end := add(ptr, decodedLength) - - // Load the table into the scratch space. - // Constants are optimized for smaller bytecode with zero gas overhead. - // `m` also doubles as the mask of the upper 6 bits. - let m := 0xfc000000fc00686c7074787c8084888c9094989ca0a4a8acb0b4b8bcc0c4c8cc - mstore(0x5b, m) - mstore(0x3b, 0x04080c1014181c2024282c3034383c4044484c5054585c6064) - mstore(0x1a, 0xf8fcf800fcd0d4d8dce0e4e8ecf0f4) - - for {} 1 {} { - // Read 4 bytes. - data := add(data, 4) - let input := mload(data) - - // Write 3 bytes. - // forgefmt: disable-next-item - mstore( - ptr, - or( - and(m, mload(byte(28, input))), - shr( - 6, - or( - and(m, mload(byte(29, input))), - shr(6, or(and(m, mload(byte(30, input))), shr(6, mload(byte(31, input))))) - ) - ) - ) - ) - ptr := add(ptr, 3) - if iszero(lt(ptr, end)) { - break - } - } - mstore(0x40, add(end, 0x20)) // Allocate the memory. - mstore(end, 0) // Zeroize the slot after the bytes. - mstore(0x60, 0) // Restore the zero slot. - } - } - } -} diff --git a/src/helpers/EIP712.sol b/src/helpers/EIP712.sol deleted file mode 100644 index 00505f43..00000000 --- a/src/helpers/EIP712.sol +++ /dev/null @@ -1,1058 +0,0 @@ -// SPDX-License-Identifier: MIT -// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol) - -pragma solidity ^0.8.24; - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol) - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol) - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) - -/** - * @dev Standard math utilities missing in the Solidity language. - */ -library Math { - /** - * @dev Muldiv operation overflow. - */ - error MathOverflowedMulDiv(); - - enum Rounding { - Floor, // Toward negative infinity - Ceil, // Toward positive infinity - Trunc, // Toward zero - Expand // Away from zero - } - - /** - * @dev Returns the addition of two unsigned integers, with an overflow flag. - */ - function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - uint256 c = a + b; - if (c < a) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the subtraction of two unsigned integers, with an overflow flag. - */ - function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b > a) return (false, 0); - return (true, a - b); - } - } - - /** - * @dev Returns the multiplication of two unsigned integers, with an overflow flag. - */ - function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) return (true, 0); - uint256 c = a * b; - if (c / a != b) return (false, 0); - return (true, c); - } - } - - /** - * @dev Returns the division of two unsigned integers, with a division by zero flag. - */ - function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a / b); - } - } - - /** - * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. - */ - function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { - unchecked { - if (b == 0) return (false, 0); - return (true, a % b); - } - } - - /** - * @dev Returns the largest of two numbers. - */ - function max(uint256 a, uint256 b) internal pure returns (uint256) { - return a > b ? a : b; - } - - /** - * @dev Returns the smallest of two numbers. - */ - function min(uint256 a, uint256 b) internal pure returns (uint256) { - return a < b ? a : b; - } - - /** - * @dev Returns the average of two numbers. The result is rounded towards - * zero. - */ - function average(uint256 a, uint256 b) internal pure returns (uint256) { - // (a + b) / 2 can overflow. - return (a & b) + (a ^ b) / 2; - } - - /** - * @dev Returns the ceiling of the division of two numbers. - * - * This differs from standard division with `/` in that it rounds 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. - return a / b; - } - - // (a + b - 1) / b can overflow on addition, so we distribute. - return a == 0 ? 0 : (a - 1) / b + 1; - } - - /** - * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or - * denominator == 0. - * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by - * Uniswap Labs also under MIT license. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { - unchecked { - // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use - // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 - // variables such that product = prod1 * 2^256 + prod0. - uint256 prod0 = x * y; // Least significant 256 bits of the product - uint256 prod1; // Most significant 256 bits of the product - assembly { - let mm := mulmod(x, y, not(0)) - prod1 := sub(sub(mm, prod0), lt(mm, prod0)) - } - - // Handle non-overflow cases, 256 by 256 division. - if (prod1 == 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 prod0 / denominator; - } - - // Make sure the result is less than 2^256. Also prevents denominator == 0. - if (denominator <= prod1) { - revert MathOverflowedMulDiv(); - } - - /////////////////////////////////////////////// - // 512 by 256 division. - /////////////////////////////////////////////// - - // Make division exact by subtracting the remainder from [prod1 prod0]. - uint256 remainder; - assembly { - // Compute remainder using mulmod. - remainder := mulmod(x, y, denominator) - - // Subtract 256 bit number from 512 bit number. - prod1 := sub(prod1, gt(remainder, prod0)) - prod0 := sub(prod0, remainder) - } - - // Factor powers of two out of denominator and compute largest power of two divisor of denominator. - // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. - - uint256 twos = denominator & (0 - denominator); - assembly { - // Divide denominator by twos. - denominator := div(denominator, twos) - - // Divide [prod1 prod0] by twos. - prod0 := div(prod0, twos) - - // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. - twos := add(div(sub(0, twos), twos), 1) - } - - // Shift in bits from prod1 into prod0. - prod0 |= prod1 * twos; - - // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such - // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for - // four bits. That is, denominator * inv = 1 mod 2^4. - uint256 inverse = (3 * denominator) ^ 2; - - // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also - // works in modular arithmetic, doubling the correct bits in each step. - inverse *= 2 - denominator * inverse; // inverse mod 2^8 - inverse *= 2 - denominator * inverse; // inverse mod 2^16 - inverse *= 2 - denominator * inverse; // inverse mod 2^32 - inverse *= 2 - denominator * inverse; // inverse mod 2^64 - inverse *= 2 - denominator * inverse; // inverse mod 2^128 - inverse *= 2 - denominator * inverse; // inverse mod 2^256 - - // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. - // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is - // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 - // is no longer required. - result = prod0 * inverse; - return result; - } - } - - /** - * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. - */ - function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { - uint256 result = mulDiv(x, y, denominator); - if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { - result += 1; - } - return result; - } - - /** - * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded - * towards zero. - * - * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). - */ - function sqrt(uint256 a) internal pure returns (uint256) { - if (a == 0) { - return 0; - } - - // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. - // - // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have - // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. - // - // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` - // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` - // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` - // - // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. - uint256 result = 1 << (log2(a) >> 1); - - // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, - // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at - // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision - // into the expected uint128 result. - unchecked { - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - result = (result + a / result) >> 1; - return min(result, a / result); - } - } - - /** - * @notice Calculates sqrt(a), following the selected rounding direction. - */ - function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = sqrt(a); - return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); - } - } - - /** - * @dev Return the log in base 2 of a positive value rounded towards zero. - * Returns 0 if given 0. - */ - function log2(uint256 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 128; - } - if (value >> 64 > 0) { - value >>= 64; - result += 64; - } - if (value >> 32 > 0) { - value >>= 32; - result += 32; - } - if (value >> 16 > 0) { - value >>= 16; - result += 16; - } - if (value >> 8 > 0) { - value >>= 8; - result += 8; - } - if (value >> 4 > 0) { - value >>= 4; - result += 4; - } - if (value >> 2 > 0) { - value >>= 2; - result += 2; - } - if (value >> 1 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 2, following the selected rounding direction, of a positive value. - * Returns 0 if given 0. - */ - function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { - unchecked { - uint256 result = log2(value); - return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); - } - } - - /** - * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); - } - } - - /** - * @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 value) internal pure returns (uint256) { - uint256 result = 0; - unchecked { - if (value >> 128 > 0) { - value >>= 128; - result += 16; - } - if (value >> 64 > 0) { - value >>= 64; - result += 8; - } - if (value >> 32 > 0) { - value >>= 32; - result += 4; - } - if (value >> 16 > 0) { - value >>= 16; - result += 2; - } - if (value >> 8 > 0) { - result += 1; - } - } - return result; - } - - /** - * @dev Return the log in base 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); - } - } - - /** - * @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; - } -} - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol) - -/** - * @dev Standard signed math utilities missing in the Solidity language. - */ -library SignedMath { - /** - * @dev Returns the largest of two signed numbers. - */ - function max(int256 a, int256 b) internal pure returns (int256) { - return a > b ? a : b; - } - - /** - * @dev Returns the smallest of two signed numbers. - */ - function min(int256 a, int256 b) internal pure returns (int256) { - return 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 { - // must be unchecked in order to support `n = type(int256).min` - return uint256(n >= 0 ? n : -n); - } - } -} - -/** - * @dev String operations. - */ -library Strings { - bytes16 private constant HEX_DIGITS = "0123456789abcdef"; - uint8 private constant ADDRESS_LENGTH = 20; - - /** - * @dev The `value` string doesn't fit in the specified `length`. - */ - error StringsInsufficientHexLength(uint256 value, uint256 length); - - /** - * @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; - /// @solidity memory-safe-assembly - assembly { - ptr := add(buffer, add(32, length)) - } - while (true) { - ptr--; - /// @solidity memory-safe-assembly - assembly { - mstore8(ptr, byte(mod(value, 10), 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 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 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[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] - * specifications. - */ -library MessageHashUtils { - /** - * @dev Returns the keccak256 digest of an EIP-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://eth.wiki/json-rpc/API#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) { - /// @solidity memory-safe-assembly - assembly { - 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 EIP-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://eth.wiki/json-rpc/API#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 EIP-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 Returns the keccak256 digest of an EIP-712 typed data (EIP-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) { - /// @solidity memory-safe-assembly - assembly { - let ptr := mload(0x40) - mstore(ptr, hex"19_01") - mstore(add(ptr, 0x02), domainSeparator) - mstore(add(ptr, 0x22), structHash) - digest := keccak256(ptr, 0x42) - } - } -} - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol) - -// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol) -// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. - -/** - * @dev Library for reading and writing primitive types to specific storage slots. - * - * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. - * This library helps with reading and writing to such slots without the need for inline assembly. - * - * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. - * - * Example usage to set ERC1967 implementation slot: - * ```solidity - * contract ERC1967 { - * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - * - * function _getImplementation() internal view returns (address) { - * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - * } - * - * function _setImplementation(address newImplementation) internal { - * require(newImplementation.code.length > 0); - * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - * } - * } - * ``` - */ -library StorageSlot { - struct AddressSlot { - address value; - } - - struct BooleanSlot { - bool value; - } - - struct Bytes32Slot { - bytes32 value; - } - - struct Uint256Slot { - uint256 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) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BooleanSlot` with member `value` located at `slot`. - */ - function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. - */ - function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Uint256Slot` with member `value` located at `slot`. - */ - function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { - /// @solidity memory-safe-assembly - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `StringSlot` with member `value` located at `slot`. - */ - function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - 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) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } - - /** - * @dev Returns an `BytesSlot` with member `value` located at `slot`. - */ - function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { - /// @solidity memory-safe-assembly - assembly { - 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) { - /// @solidity memory-safe-assembly - assembly { - r.slot := store.slot - } - } -} - -// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | -// | length | 0x BB | -type ShortString is bytes32; - -/** - * @dev This library provides functions to convert short memory strings - * into a `ShortString` type that can be used as an immutable variable. - * - * Strings of arbitrary length can be optimized using this library if - * they are short enough (up to 31 bytes) by packing them with their - * length (1 byte) in a single EVM word (32 bytes). Additionally, a - * fallback mechanism can be used for every other case. - * - * Usage example: - * - * ```solidity - * contract Named { - * using ShortStrings for *; - * - * ShortString private immutable _name; - * string private _nameFallback; - * - * constructor(string memory contractName) { - * _name = contractName.toShortStringWithFallback(_nameFallback); - * } - * - * function name() external view returns (string memory) { - * return _name.toStringWithFallback(_nameFallback); - * } - * } - * ``` - */ -library ShortStrings { - // Used as an identifier for strings longer than 31 bytes. - bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; - - error StringTooLong(string str); - error InvalidShortString(); - - /** - * @dev Encode a string of at most 31 chars into a `ShortString`. - * - * This will trigger a `StringTooLong` error is the input string is too long. - */ - function toShortString(string memory str) internal pure returns (ShortString) { - bytes memory bstr = bytes(str); - if (bstr.length > 31) { - revert StringTooLong(str); - } - return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); - } - - /** - * @dev Decode a `ShortString` back to a "normal" string. - */ - function toString(ShortString sstr) internal pure returns (string memory) { - uint256 len = byteLength(sstr); - // using `new string(len)` would work locally but is not memory safe. - string memory str = new string(32); - /// @solidity memory-safe-assembly - assembly { - mstore(str, len) - mstore(add(str, 0x20), sstr) - } - return str; - } - - /** - * @dev Return the length of a `ShortString`. - */ - function byteLength(ShortString sstr) internal pure returns (uint256) { - uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; - if (result > 31) { - revert InvalidShortString(); - } - return result; - } - - /** - * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. - */ - function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { - if (bytes(value).length < 32) { - return toShortString(value); - } else { - StorageSlot.getStringSlot(store).value = value; - return ShortString.wrap(FALLBACK_SENTINEL); - } - } - - /** - * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. - */ - function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { - if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { - return toString(value); - } else { - return store; - } - } - - /** - * @dev Return the length of a string that was encoded to `ShortString` or written to storage using - * {setWithFallback}. - * - * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of - * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. - */ - function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { - if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { - return byteLength(value); - } else { - return bytes(store).length; - } - } -} - -// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol) - -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 - ); -} - -/** - * @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: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain - * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the - * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. - * - * @custom:oz-upgrades-unsafe-allow state-variable-immutable - */ -abstract contract EIP712 is IERC5267 { - using ShortStrings for *; - - bytes32 private constant TYPE_HASH = - keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); - - // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to - // invalidate the cached domain separator if the chain id changes. - bytes32 private immutable _cachedDomainSeparator; - uint256 private immutable _cachedChainId; - address private immutable _cachedThis; - - bytes32 private immutable _hashedName; - bytes32 private immutable _hashedVersion; - - ShortString private immutable _name; - ShortString private immutable _version; - string private _nameFallback; - string private _versionFallback; - - /** - * @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]. - */ - constructor(string memory name, string memory version) { - _name = name.toShortStringWithFallback(_nameFallback); - _version = version.toShortStringWithFallback(_versionFallback); - _hashedName = keccak256(bytes(name)); - _hashedVersion = keccak256(bytes(version)); - - _cachedChainId = block.chainid; - _cachedDomainSeparator = _buildDomainSeparator(); - _cachedThis = address(this); - } - - /** - * @dev Returns the domain separator for the current chain. - */ - function _domainSeparatorV4() internal view returns (bytes32) { - if (address(this) == _cachedThis && block.chainid == _cachedChainId) { - return _cachedDomainSeparator; - } else { - return _buildDomainSeparator(); - } - } - - function _buildDomainSeparator() private view returns (bytes32) { - return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, 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); - } - - /** - * @dev See {IERC-5267}. - */ - function eip712Domain() - public - view - virtual - returns ( - bytes1 fields, - string memory name, - string memory version, - uint256 chainId, - address verifyingContract, - bytes32 salt, - uint256[] memory extensions - ) - { - return ( - hex"0f", // 01111 - _EIP712Name(), - _EIP712Version(), - block.chainid, - address(this), - bytes32(0), - new uint256[](0) - ); - } - - /** - * @dev The name parameter for the EIP712 domain. - * - * NOTE: By default this function reads _name which is an immutable value. - * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). - */ - // solhint-disable-next-line func-name-mixedcase - function _EIP712Name() internal view returns (string memory) { - return _name.toStringWithFallback(_nameFallback); - } - - /** - * @dev The version parameter for the EIP712 domain. - * - * NOTE: By default this function reads _version which is an immutable value. - * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). - */ - // solhint-disable-next-line func-name-mixedcase - function _EIP712Version() internal view returns (string memory) { - return _version.toStringWithFallback(_versionFallback); - } -} diff --git a/src/validators/WebAuthValidator.sol b/src/validators/WebAuthValidator.sol index 826df087..a5cd9feb 100644 --- a/src/validators/WebAuthValidator.sol +++ b/src/validators/WebAuthValidator.sol @@ -4,8 +4,8 @@ pragma solidity ^0.8.24; import { IModuleValidator } from "../interfaces/IModuleValidator.sol"; import { VerifierCaller } from "../helpers/VerifierCaller.sol"; import { JsmnSolLib } from "../libraries/JsmnSolLib.sol"; -import { Strings } from "../helpers/EIP712.sol"; -import { Base64 } from "../helpers/Base64.sol"; +import { Strings } from "@openzeppelin/contracts/utils/Strings.sol"; +import { Base64 } from "solady/src/utils/Base64.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title AAFactory