Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sync v0.8 accounts to recent 6900 spec #20

Merged
merged 3 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"clean": "rm -rf cache artifacts typechain-types",
"build": "forge build",
"lint": "solhint -w 127 -c .solhint-src.json './src/**/*.sol' && solhint -w 242 -c .solhint-test.json './test/**/*.sol' && solhint -w 0 -c .solhint-script.json './script/**/*.sol'",
"lint": "solhint -w 112 -c .solhint-src.json './src/**/*.sol' && solhint -w 228 -c .solhint-test.json './test/**/*.sol' && solhint -w 0 -c .solhint-script.json './script/**/*.sol'",
"test": "forge test -vv",
"gasreport": "forge test --gas-report > gas/reports/gas-report.txt",
"coverage": "forge coverage --ir-minimum",
Expand Down
49 changes: 39 additions & 10 deletions src/account/v1/ECDSAAccount.sol
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,42 @@
*/
pragma solidity 0.8.24;

import {SIG_VALIDATION_FAILED} from "../../common/Constants.sol";
import "../CoreAccount.sol";
import "@account-abstraction/contracts/interfaces/IEntryPoint.sol";
import "@account-abstraction/contracts/interfaces/PackedUserOperation.sol";
import {
EIP1271_INVALID_SIGNATURE,
EIP1271_VALID_SIGNATURE,
SIG_VALIDATION_FAILED,
WALLET_VERSION_1
} from "../../common/Constants.sol";

import {BaseERC712CompliantAccount} from "../../erc712/BaseERC712CompliantAccount.sol";
import {CoreAccount} from "../CoreAccount.sol";
import {IEntryPoint} from "@account-abstraction/contracts/interfaces/IEntryPoint.sol";
import {PackedUserOperation} from "@account-abstraction/contracts/interfaces/PackedUserOperation.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

/**
* @dev Upgradable & ownable (by EOA key) contract. One of the most common templates.
*/
contract ECDSAAccount is CoreAccount, UUPSUpgradeable {
contract ECDSAAccount is CoreAccount, UUPSUpgradeable, BaseERC712CompliantAccount {
using ECDSA for bytes32;
using MessageHashUtils for bytes32;

string public constant NAME = "Circle_ECDSAAccount";
bytes32 private constant _HASHED_NAME = keccak256(bytes(NAME));
bytes32 private constant _HASHED_VERSION = keccak256(bytes(WALLET_VERSION_1));
bytes32 private constant _MESSAGE_TYPEHASH = keccak256("CircleECDSAAccountMessage(bytes32 hash)");

/// @inheritdoc UUPSUpgradeable
// The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
// Authorize the owner to upgrade the contract.
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}

Check warning on line 52 in src/account/v1/ECDSAAccount.sol

View workflow job for this annotation

GitHub Actions / lint_and_test

Code contains empty blocks

/// @custom:oz-upgrades-unsafe-allow constructor
// for immutable values in implementations
constructor(IEntryPoint _newEntryPoint) CoreAccount(_newEntryPoint) {

Check warning on line 56 in src/account/v1/ECDSAAccount.sol

View workflow job for this annotation

GitHub Actions / lint_and_test

Explicitly mark visibility in function (Set ignoreConstructors to true if using solidity >=0.7.0)
// lock the implementation contract so it can only be called from proxies
_disableInitializers();
}
Expand Down Expand Up @@ -69,9 +81,26 @@
}

function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4) {
if (!SignatureChecker.isValidSignatureNow(owner(), hash.toEthSignedMessageHash(), signature)) {
return bytes4(0xffffffff);
// use address(this) to prevent replay attacks
bytes32 replaySafeHash = getReplaySafeMessageHash(hash);
if (SignatureChecker.isValidSignatureNow(owner(), replaySafeHash, signature)) {
return EIP1271_VALID_SIGNATURE;
}
return EIP1271_MAGIC_VALUE;
return EIP1271_INVALID_SIGNATURE;
}

/// @inheritdoc BaseERC712CompliantAccount
function _getAccountTypeHash() internal pure override returns (bytes32) {
return _MESSAGE_TYPEHASH;
}

/// @inheritdoc BaseERC712CompliantAccount
function _getAccountName() internal pure override returns (bytes32) {
return _HASHED_NAME;
}

/// @inheritdoc BaseERC712CompliantAccount
function _getAccountVersion() internal pure override returns (bytes32) {
return _HASHED_VERSION;
}
}
10 changes: 10 additions & 0 deletions src/common/CommonStructs.sol
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,13 @@ struct OwnerData {
uint256 publicKeyX; // 32 bytes if used
uint256 publicKeyY; // 32 bytes if used
}

/// @notice Metadata of the ownership of an account.
/// @param numOwners number of owners on the account
/// @param thresholdWeight weight of signatures required to perform an action
/// @param totalWeight total weight of signatures required to perform an action
struct OwnershipMetadata {
uint256 numOwners;
uint256 thresholdWeight;
uint256 totalWeight;
}
53 changes: 53 additions & 0 deletions src/erc712/BaseERC712CompliantAccount.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2024 Circle Internet Group, Inc. All rights reserved.

* SPDX-License-Identifier: GPL-3.0-or-later

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.24;

import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";

abstract contract BaseERC712CompliantAccount {
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 private constant _DOMAIN_SEPARATOR_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

/// @notice Wraps a replay safe hash in an EIP-712 envelope to prevent cross-account replay attacks.
/// domainSeparator = hashStruct(eip712Domain).
/// eip712Domain = (string name,string version,uint256 chainId,address verifyingContract)
/// hashStruct(s) = keccak256(typeHash ‖ encodeData(s)) where typeHash = keccak256(encodeType(typeOf(s)))
/// @param hash Message that should be hashed.
/// @return Replay safe message hash.
function getReplaySafeMessageHash(bytes32 hash) public view returns (bytes32) {
return MessageHashUtils.toTypedDataHash({
domainSeparator: keccak256(
abi.encode(
_DOMAIN_SEPARATOR_TYPEHASH, _getAccountName(), _getAccountVersion(), block.chainid, address(this)
)
),
structHash: keccak256(abi.encode(_getAccountTypeHash(), hash))
});
}

/// @dev Returns the account message typehash.
function _getAccountTypeHash() internal pure virtual returns (bytes32);

/// @dev Returns the account name.
function _getAccountName() internal pure virtual returns (bytes32);

/// @dev Returns the account version.
function _getAccountVersion() internal pure virtual returns (bytes32);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,38 +18,35 @@
*/
pragma solidity 0.8.24;

import {IERC712Compliant} from "../../../../shared/erc712/IERC712Compliant.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";

// @notice Forked from 6900 reference implementation with some modifications.
// @notice Inspired by 6900 reference implementation with some modifications.
// A base contract for modules that use EIP-712 structured data signing.
// Unlike other EIP712 libraries, this base contract uses the salt field (bytes32(uint256(uint160(account))) to hold the
// Unlike other EIP712 libraries, this base contract uses the salt field (bytes32(bytes20(account)) to hold the
// account address
// and uses the verifyingContract field to hold module address.
// This abstract contract does not implement EIP-5267, as the domain retrieval function eip712Domain() does not provide
// a parameter to hold the account address.
// If we use verifyingContract to hold account address, then `msg.sender` would be address(0) for an `eth_call` without
// an override.
abstract contract BaseERC712CompliantModule is IERC712Compliant {
abstract contract BaseERC712CompliantModule {
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)")
bytes32 private constant _DOMAIN_SEPARATOR_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)");

/// @inheritdoc IERC712Compliant
/// @notice domainSeparator = hashStruct(eip712Domain).
/// @notice Wraps a replay safe hash in an EIP-712 envelope to prevent cross-account replay attacks.
/// domainSeparator = hashStruct(eip712Domain).
/// eip712Domain = (string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)
/// The domain separator includes the chainId, module address and account address.
/// hashStruct(s) = keccak256(typeHash ‖ encodeData(s)) where typeHash = keccak256(encodeType(typeOf(s)))
/// @param account SCA to build the message hash for.
/// @param hash Message that should be hashed.
/// @return Replay safe message hash.
function getReplaySafeMessageHash(address account, bytes32 hash) public view returns (bytes32) {
return MessageHashUtils.toTypedDataHash({
domainSeparator: keccak256(
abi.encode(
_DOMAIN_SEPARATOR_TYPEHASH,
_getModuleName(),
_getModuleVersion(),
block.chainid,
address(this),
bytes32(bytes20(account))
_DOMAIN_SEPARATOR_TYPEHASH, _getModuleIdHash(), block.chainid, address(this), bytes32(bytes20(account))
)
),
structHash: keccak256(abi.encode(_getModuleTypeHash(), hash))
Expand All @@ -59,9 +56,6 @@ abstract contract BaseERC712CompliantModule is IERC712Compliant {
/// @dev Returns the module typehash.
function _getModuleTypeHash() internal pure virtual returns (bytes32);

/// @dev Returns the module name.
function _getModuleName() internal pure virtual returns (bytes32);

/// @dev Returns the module version.
function _getModuleVersion() internal pure virtual returns (bytes32);
/// @dev Returns the module id.
function _getModuleIdHash() internal pure virtual returns (bytes32);
}
34 changes: 0 additions & 34 deletions src/msca/6900/shared/erc712/IERC712Compliant.sol

This file was deleted.

59 changes: 30 additions & 29 deletions src/msca/6900/v0.7/account/semi/SingleOwnerMSCA.sol
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import {
EMPTY_FUNCTION_REFERENCE,
SENTINEL_BYTES21,
SIG_VALIDATION_FAILED,
SIG_VALIDATION_SUCCEEDED
SIG_VALIDATION_SUCCEEDED,
WALLET_VERSION_1
} from "../../../../../common/Constants.sol";
import {ExecutionUtils} from "../../../../../utils/ExecutionUtils.sol";
import {
Expand Down Expand Up @@ -58,13 +59,14 @@ import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Re
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

import {BaseERC712CompliantAccount} from "../../../../../erc712/BaseERC712CompliantAccount.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

/**
* @dev Semi-MSCA that enshrines single owner into the account storage.
*/
contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, IERC1271 {
contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, IERC1271, BaseERC712CompliantAccount {
using ExecutionUtils for address;
using ECDSA for bytes32;
using MessageHashUtils for bytes32;
Expand All @@ -78,6 +80,11 @@ contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, I
NATIVE_USER_OP_VALIDATION_OWNER
}

string public constant NAME = "Circle_SingleOwnerMSCA";
bytes32 private constant _HASHED_NAME = keccak256(bytes(NAME));
bytes32 private constant _HASHED_VERSION = keccak256(bytes(WALLET_VERSION_1));
bytes32 private constant _MESSAGE_TYPEHASH = keccak256("CircleSingleOwnerMSCAMessage(bytes32 hash)");

event SingleOwnerMSCAInitialized(address indexed account, address indexed entryPointAddress, address owner);
event OwnershipTransferred(address indexed account, address indexed previousOwner, address indexed newOwner);

Expand Down Expand Up @@ -123,11 +130,14 @@ contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, I
return EIP1271_INVALID_SIGNATURE;
}
return abi.decode(returnData, (bytes4));
} else {
// use address(this) to prevent replay attacks
bytes32 replaySafeHash = getReplaySafeMessageHash(hash);
if (SignatureChecker.isValidSignatureNow(owner, replaySafeHash, signature)) {
return EIP1271_VALID_SIGNATURE;
}
return EIP1271_INVALID_SIGNATURE;
}
if (_verifySignature(owner, hash, signature)) {
return EIP1271_VALID_SIGNATURE;
}
return EIP1271_INVALID_SIGNATURE;
}

/**
Expand Down Expand Up @@ -233,7 +243,7 @@ contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, I
executionDetail.userOpValidationFunction.functionId, userOp, userOpHash
);
} else {
if (_verifySignature(owner, userOpHash, userOp.signature)) {
if (SignatureChecker.isValidSignatureNow(owner, userOpHash.toEthSignedMessageHash(), userOp.signature)) {
currentValidationData = SIG_VALIDATION_SUCCEEDED;
} else {
currentValidationData = SIG_VALIDATION_FAILED;
Expand Down Expand Up @@ -391,27 +401,18 @@ contract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, I
}
}

/**
* @dev For EOA owner, run ecrecover. For smart contract owner, run 1271 staticcall.
*/
function _verifySignature(address owner, bytes32 hash, bytes memory signature) internal view returns (bool) {
// EOA owner (ECDSA)
// if the signature (personal sign) is signed over userOpHash.toEthSignedMessageHash (prepended with
// 'x\x19Ethereum Signed Message:\n32'), then we recover using userOpHash.toEthSignedMessageHash;
// or if the signature (typed data sign) is signed over userOpHash directly, then we recover userOpHash directly
(address recovered, ECDSA.RecoverError error,) = hash.toEthSignedMessageHash().tryRecover(signature);
if (error == ECDSA.RecoverError.NoError && recovered == owner) {
return true;
}
(recovered, error,) = hash.tryRecover(signature);
if (error == ECDSA.RecoverError.NoError && recovered == owner) {
return true;
}
if (SignatureChecker.isValidERC1271SignatureNow(owner, hash, signature)) {
// smart contract owner.isValidSignature should be smart enough to sign over the non-modified hash or over
// the hash that is modified in the way owner would expect
return true;
}
return false;
/// @inheritdoc BaseERC712CompliantAccount
function _getAccountTypeHash() internal pure override returns (bytes32) {
return _MESSAGE_TYPEHASH;
}

/// @inheritdoc BaseERC712CompliantAccount
function _getAccountName() internal pure override returns (bytes32) {
return _HASHED_NAME;
}

/// @inheritdoc BaseERC712CompliantAccount
function _getAccountVersion() internal pure override returns (bytes32) {
return _HASHED_VERSION;
}
}
Loading
Loading