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

Add social recovery example module #86

Merged
merged 12 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 8 additions & 7 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,25 @@
"url": "https://github.com/rhinestonewtf/modulekit/issues"
},
"devDependencies": {
"@ERC4337/account-abstraction": "github:kopy-kat/account-abstraction#develop",
"@ERC4337/account-abstraction-v0.6": "github:eth-infinitism/account-abstraction#v0.6.0",
"@openzeppelin/contracts": "5.0.1",
"@prb/math": "^4.0.2",
"@rhinestone/modulekit": "workspace:*",
"@rhinestone/safe7579": "workspace:*",
"@rhinestone/sessionkeymanager": "workspace:*",
"@prb/math": "^4.0.2",
"erc4337-validation": "github:rhinestonewtf/erc4337-validation",
"@ERC4337/account-abstraction": "github:kopy-kat/account-abstraction#develop",
"@safe-global/safe-contracts": "^1.4.1",
"@ERC4337/account-abstraction-v0.6": "github:eth-infinitism/account-abstraction#v0.6.0",
"forge-std": "github:foundry-rs/forge-std",
"checknsignatures": "github:kopy-kat/checknsignatures",
"ds-test": "github:dapphub/ds-test",
"erc4337-validation": "github:rhinestonewtf/erc4337-validation",
"erc7579": "github:erc7579/erc7579-implementation",
"forge-std": "github:foundry-rs/forge-std",
"prettier": "^2.8.8",
"sentinellist": "github:zeroknots/sentinellist",
"solady": "github:vectorized/solady",
"solarray": "github:sablier-labs/solarray",
"solmate": "github:transmissions11/solmate",
"solhint": "^4.1.1",
"prettier": "^2.8.8"
"solmate": "github:transmissions11/solmate"
},
"files": [
"artifacts",
Expand Down
1 change: 1 addition & 0 deletions examples/remappings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ modulekit/=node_modules/@rhinestone/modulekit/packages/modulekit/
erc4337-validation/=node_modules/erc4337-validation/src/
@ERC4337/=node_modules/@ERC4337/
@prb/math/=node_modules/@prb/math/
checknsignatures/=node_modules/checknsignatures/src/
163 changes: 163 additions & 0 deletions examples/src/SocialRecovery/SocialRecovery.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.23;

import { ERC7579ValidatorBase } from "modulekit/src/Modules.sol";
import { PackedUserOperation } from "modulekit/src/external/ERC4337.sol";
import { SentinelListLib } from "sentinellist/SentinelList.sol";
import { CheckSignatures } from "checknsignatures/CheckNSignatures.sol";
import { IERC7579Account } from "modulekit/src/Accounts.sol";
import { ModeLib, CallType, ModeCode, CALLTYPE_SINGLE } from "erc7579/lib/ModeLib.sol";
import { ExecutionLib } from "erc7579/lib/ExecutionLib.sol";

contract SocialRecovery is ERC7579ValidatorBase {
using SentinelListLib for SentinelListLib.SentinelList;

/*//////////////////////////////////////////////////////////////////////////
CONSTANTS & STORAGE
//////////////////////////////////////////////////////////////////////////*/

error UnsopportedOperation();
error InvalidGuardian(address guardian);
error ThresholdNotSet();

SentinelListLib.SentinelList guardians;
mapping(address account => uint256) thresholds;

/*//////////////////////////////////////////////////////////////////////////
CONFIG
//////////////////////////////////////////////////////////////////////////*/

function onInstall(bytes calldata data) external override {
// Get the threshold and guardians from the data
(uint256 threshold, address[] memory _guardians) = abi.decode(data, (uint256, address[]));
kopy-kat marked this conversation as resolved.
Show resolved Hide resolved

// Make sure the threshold is set
if (threshold == 0) {
revert ThresholdNotSet();
}

// Set threshold
thresholds[msg.sender] = threshold;

// Initialize the guardian list
guardians.init();

// Add guardians to the list
uint256 guardiansLength = _guardians.length;
for (uint256 i = 0; i < guardiansLength; i++) {
address _guardian = _guardians[i];
if (_guardian == address(0)) {
revert InvalidGuardian(_guardian);
}
guardians.push(_guardian);
}
}

function onUninstall(bytes calldata) external override {
// todo
}

function isInitialized(address smartAccount) external view returns (bool) {
return thresholds[smartAccount] != 0;
}

/*//////////////////////////////////////////////////////////////////////////
MODULE LOGIC
//////////////////////////////////////////////////////////////////////////*/

function validateUserOp(
PackedUserOperation calldata userOp,
bytes32 userOpHash
)
external
override
returns (ValidationData)
{
// Get the threshold and check that its set
uint256 threshold = thresholds[msg.sender];
if (threshold == 0) {
return VALIDATION_FAILED;
}

// Recover the signers from the signatures
address[] memory signers =
kopy-kat marked this conversation as resolved.
Show resolved Hide resolved
CheckSignatures.recoverNSignatures(userOpHash, userOp.signature, threshold);

// Check if the signers are guardians
SentinelListLib.SentinelList storage _guardians = guardians;
uint256 validSigners;
for (uint256 i = 0; i < signers.length; i++) {
if (_guardians.contains(signers[i])) {
validSigners++;
}
}

// Check if the execution is allowed
bool isAllowedExecution;
bytes4 selector = bytes4(userOp.callData[0:4]);
if (selector == IERC7579Account.execute.selector) {
// Decode and check the execution
// Only single executions to installed validators are allowed
isAllowedExecution = _decodeAndCheckExecution(userOp.callData);
}

// Check if the threshold is met and the execution is allowed and return the result
if (validSigners >= threshold && isAllowedExecution) {
return VALIDATION_SUCCESS;
}
return VALIDATION_FAILED;
}

function isValidSignatureWithSender(
address,
bytes32 hash,
bytes calldata data
)
external
view
override
returns (bytes4)
{
// ERC-1271 not supported for recovery
revert UnsopportedOperation();
}

/*//////////////////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////////////////*/

function _decodeAndCheckExecution(bytes calldata callData)
internal
returns (bool isAllowedExecution)
{
// Get the mode and call type
ModeCode mode = ModeCode.wrap(bytes32(callData[4:36]));
CallType calltype = ModeLib.getCallType(mode);

if (calltype == CALLTYPE_SINGLE) {
// Decode the calldata
(address to,,) = ExecutionLib.decodeSingle(callData[100:]);

// Check if the module is installed as a validator
return IERC7579Account(msg.sender).isModuleInstalled(TYPE_VALIDATOR, to, "");
} else {
return false;
}
}

/*//////////////////////////////////////////////////////////////////////////
METADATA
//////////////////////////////////////////////////////////////////////////*/

function name() external pure returns (string memory) {
return "SocialRecoveryValidator";
}

function version() external pure returns (string memory) {
return "0.0.1";
}

function isModuleType(uint256 typeID) external pure override returns (bool) {
return typeID == TYPE_VALIDATOR;
}
}
137 changes: 137 additions & 0 deletions examples/test/SocialRecovery/SocialRecovery.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import "forge-std/Test.sol";
import "modulekit/src/ModuleKit.sol";
import "modulekit/src/Mocks.sol";

import { SocialRecovery } from "src/SocialRecovery/SocialRecovery.sol";
import { Solarray } from "solarray/Solarray.sol";

import { MODULE_TYPE_VALIDATOR } from "modulekit/src/external/ERC7579.sol";

contract DemoValidator {
uint256 counter;

function onInstall(bytes calldata) external { }

function count() public {
counter++;
}

function getCount() public view returns (uint256) {
return counter;
}
}

contract SocialRecoveryTest is RhinestoneModuleKit, Test {
using ModuleKitHelpers for *;
using ModuleKitUserOp for *;
using ModuleKitSCM for *;

AccountInstance internal instance;

MockTarget internal target;
MockERC20 internal token;

DemoValidator internal validator1;
DemoValidator internal validator2;

Account internal signer1;
Account internal signer2;
Account internal signer3;

SocialRecovery internal socialRecovery;

function setUp() public {
instance = makeAccountInstance("1");
vm.deal(instance.account, 1 ether);

signer1 = makeAccount("signer1");
signer2 = makeAccount("signer2");
signer3 = makeAccount("signer3");

socialRecovery = new SocialRecovery();

validator1 = new DemoValidator();
validator2 = new DemoValidator();

address[] memory signers = Solarray.addresses(signer1.addr, signer2.addr, signer3.addr);

instance.installModule({
moduleTypeId: MODULE_TYPE_VALIDATOR,
module: address(socialRecovery),
data: abi.encode(uint256(2), signers)
});

instance.installModule({
moduleTypeId: MODULE_TYPE_VALIDATOR,
module: address(validator1),
data: ""
});
}

function sign(
uint256[] memory signerPrivKeys,
bytes32 dataHash
)
internal
returns (bytes memory signatures)
{
uint8 v;
bytes32 r;
bytes32 s;

for (uint256 i; i < signerPrivKeys.length; i++) {
uint256 privKey = signerPrivKeys[i];
(v, r, s) = vm.sign(privKey, dataHash);
signatures = abi.encodePacked(signatures, abi.encodePacked(r, s, v));
}
}

function testRecover() public {
UserOpData memory userOpData = instance.getExecOps({
target: address(validator1),
value: 0,
callData: abi.encodeWithSelector(DemoValidator.count.selector),
txValidator: address(socialRecovery)
});

uint256[] memory privKeys = Solarray.uint256s(signer1.key, signer2.key);
bytes memory signature = sign(privKeys, userOpData.userOpHash);
userOpData.userOp.signature = signature;
userOpData.execUserOps();

assertEq(validator1.getCount(), 1);
}

function testRecover__RevertWhen__InvalidTarget() public {
UserOpData memory userOpData = instance.getExecOps({
target: address(validator2),
value: 0,
callData: abi.encodeWithSelector(DemoValidator.count.selector),
txValidator: address(socialRecovery)
});

uint256[] memory privKeys = Solarray.uint256s(signer1.key, signer2.key);
bytes memory signature = sign(privKeys, userOpData.userOpHash);
userOpData.userOp.signature = signature;
vm.expectRevert();
userOpData.execUserOps();
}

function testRecover__RevertWhen__InvalidSignatures() public {
UserOpData memory userOpData = instance.getExecOps({
target: address(validator1),
value: 0,
callData: abi.encodeWithSelector(DemoValidator.count.selector),
txValidator: address(socialRecovery)
});

uint256[] memory privKeys = Solarray.uint256s(signer1.key, uint256(3));
bytes memory signature = sign(privKeys, userOpData.userOpHash);
userOpData.userOp.signature = signature;
vm.expectRevert();
userOpData.execUserOps();
}
}
Loading
Loading