-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathKernel.sol
493 lines (459 loc) · 20.4 KB
/
Kernel.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PackedUserOperation} from "./interfaces/PackedUserOperation.sol";
import {IAccount, ValidationData, ValidAfter, ValidUntil, parseValidationData} from "./interfaces/IAccount.sol";
import {IEntryPoint} from "./interfaces/IEntryPoint.sol";
import {IAccountExecute} from "./interfaces/IAccountExecute.sol";
import {IERC7579Account} from "./interfaces/IERC7579Account.sol";
import {ModuleLib} from "./utils/ModuleLib.sol";
import {
ValidationManager,
ValidationMode,
ValidationId,
ValidatorLib,
ValidationType,
PermissionId,
PassFlag,
SKIP_SIGNATURE
} from "./core/ValidationManager.sol";
import {HookManager} from "./core/HookManager.sol";
import {ExecutorManager} from "./core/ExecutorManager.sol";
import {SelectorManager} from "./core/SelectorManager.sol";
import {IModule, IValidator, IHook, IExecutor, IFallback, IPolicy, ISigner} from "./interfaces/IERC7579Modules.sol";
import {EIP712} from "solady/utils/EIP712.sol";
import {ExecLib, ExecMode, CallType, ExecType, ExecModeSelector, ExecModePayload} from "./utils/ExecLib.sol";
import {
CALLTYPE_SINGLE,
CALLTYPE_DELEGATECALL,
ERC1967_IMPLEMENTATION_SLOT,
VALIDATION_TYPE_ROOT,
VALIDATION_TYPE_VALIDATOR,
VALIDATION_TYPE_PERMISSION,
MODULE_TYPE_VALIDATOR,
MODULE_TYPE_EXECUTOR,
MODULE_TYPE_FALLBACK,
MODULE_TYPE_HOOK,
MODULE_TYPE_POLICY,
MODULE_TYPE_SIGNER,
EXECTYPE_TRY,
EXECTYPE_DEFAULT,
EXEC_MODE_DEFAULT,
CALLTYPE_DELEGATECALL,
CALLTYPE_SINGLE,
CALLTYPE_BATCH,
CALLTYPE_STATIC
} from "./types/Constants.sol";
contract Kernel is IAccount, IAccountExecute, IERC7579Account, ValidationManager {
error ExecutionReverted();
error InvalidExecutor();
error InvalidFallback();
error InvalidCallType();
error OnlyExecuteUserOp();
error InvalidModuleType();
error InvalidCaller();
error InvalidSelector();
event Received(address sender, uint256 amount);
event Upgraded(address indexed implementation);
IEntryPoint public immutable entrypoint;
// NOTE : when eip 1153 has been enabled, this can be transient storage
mapping(bytes32 userOpHash => IHook) internal executionHook;
constructor(IEntryPoint _entrypoint) {
entrypoint = _entrypoint;
_validationStorage().rootValidator = ValidationId.wrap(bytes21(abi.encodePacked(hex"deadbeef")));
}
modifier onlyEntryPoint() {
if (msg.sender != address(entrypoint)) {
revert InvalidCaller();
}
_;
}
modifier onlyEntryPointOrSelf() {
if (msg.sender != address(entrypoint) && msg.sender != address(this)) {
revert InvalidCaller();
}
_;
}
modifier onlyEntryPointOrSelfOrRoot() {
IValidator validator = ValidatorLib.getValidator(_validationStorage().rootValidator);
if (
msg.sender != address(entrypoint) && msg.sender != address(this) // do rootValidator hook
) {
if (validator.isModuleType(4)) {
bytes memory ret = IHook(address(validator)).preCheck(msg.sender, msg.value, msg.data);
_;
IHook(address(validator)).postCheck(ret, true, hex""); // TODO don't support try catch hook here
} else {
revert InvalidCaller();
}
} else {
_;
}
}
function initialize(ValidationId _rootValidator, IHook hook, bytes calldata validatorData, bytes calldata hookData)
external
{
ValidationStorage storage vs = _validationStorage();
require(ValidationId.unwrap(vs.rootValidator) == bytes21(0), "already initialized");
if (ValidationId.unwrap(_rootValidator) == bytes21(0)) {
revert InvalidValidator();
}
ValidationType vType = ValidatorLib.getType(_rootValidator);
if (vType != VALIDATION_TYPE_VALIDATOR && vType != VALIDATION_TYPE_PERMISSION) {
revert InvalidValidationType();
}
_setRootValidator(_rootValidator);
ValidationConfig memory config = ValidationConfig({nonce: uint32(1), hook: hook});
vs.currentNonce = 1;
_installValidation(_rootValidator, config, validatorData, hookData);
}
function upgradeTo(address _newImplementation) external payable onlyEntryPointOrSelfOrRoot {
assembly {
sstore(ERC1967_IMPLEMENTATION_SLOT, _newImplementation)
}
emit Upgraded(_newImplementation);
}
function _domainNameAndVersion() internal pure override returns (string memory name, string memory version) {
name = "Kernel";
version = "0.3.0-beta";
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
fallback() external payable {
SelectorConfig memory config = _selectorConfig(msg.sig);
bool success;
bytes memory result;
if (address(config.hook) == address(0)) {
revert InvalidSelector();
} else {
// action installed
bytes memory context;
if (address(config.hook) != address(1)) {
context = _doPreHook(config.hook, msg.value, msg.data);
}
// execute action
if (config.callType == CALLTYPE_SINGLE) {
(success, result) = ExecLib.doFallback2771Call(config.target);
} else if (config.callType == CALLTYPE_DELEGATECALL) {
(success, result) = ExecLib.executeDelegatecall(config.target, msg.data);
} else {
revert NotSupportedCallType();
}
if (address(config.hook) != address(1)) {
_doPostHook(config.hook, context, success, result);
}
}
if (!success) {
assembly {
revert(add(result, 0x20), mload(result))
}
} else {
assembly {
return(add(result, 0x20), mload(result))
}
}
}
// validation part
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)
external
payable
override
onlyEntryPoint
returns (ValidationData validationData)
{
ValidationStorage storage vs = _validationStorage();
// ONLY ENTRYPOINT
// Major change for v2 => v3
// 1. instead of packing 4 bytes prefix to userOp.signature to determine the mode, v3 uses userOp.nonce's first 2 bytes to check the mode
// 2. instead of packing 20 bytes in userOp.signature for enable mode to provide the validator address, v3 uses userOp.nonce[2:22]
// 3. In v2, only 1 plugin validator(aside from root validator) can access the selector.
// In v3, you can use more than 1 plugin to use the exact selector, you need to specify the validator address in userOp.nonce[2:22] to use the validator
(ValidationMode vMode, ValidationType vType, ValidationId vId) = ValidatorLib.decodeNonce(userOp.nonce);
if (vType == VALIDATION_TYPE_ROOT) {
vId = vs.rootValidator;
}
validationData = _doValidation(vMode, vId, userOp, userOpHash);
ValidationConfig memory vc = vs.validationConfig[vId];
// allow when nonce is not revoked or vType is sudo
if (vType != VALIDATION_TYPE_ROOT && vc.nonce < vs.validNonceFrom) {
revert InvalidNonce();
}
IHook execHook = vc.hook;
if (address(execHook) == address(0)) {
revert InvalidValidator();
}
executionHook[userOpHash] = execHook;
if (address(execHook) == address(1)) {
// does not require hook
if (vType != VALIDATION_TYPE_ROOT && !vs.allowedSelectors[vId][bytes4(userOp.callData[0:4])]) {
revert InvalidValidator();
}
} else {
// requires hook
if (vType != VALIDATION_TYPE_ROOT && !vs.allowedSelectors[vId][bytes4(userOp.callData[4:8])]) {
revert InvalidValidator();
}
if (bytes4(userOp.callData[0:4]) != this.executeUserOp.selector) {
revert OnlyExecuteUserOp();
}
}
assembly {
if missingAccountFunds {
pop(call(gas(), caller(), missingAccountFunds, callvalue(), callvalue(), callvalue(), callvalue()))
//ignore failure (its EntryPoint's job to verify, not account.)
}
}
}
// --- Execution ---
function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
external
payable
override
onlyEntryPoint
{
bytes memory context;
IHook hook = executionHook[userOpHash];
if (address(hook) != address(1)) {
// removed 4bytes selector
context = _doPreHook(hook, msg.value, userOp.callData[4:]);
}
(bool success, bytes memory ret) = ExecLib.executeDelegatecall(address(this), userOp.callData[4:]);
if (address(hook) != address(1)) {
_doPostHook(hook, context, success, ret);
} else if (!success) {
revert ExecutionReverted();
}
}
function executeFromExecutor(ExecMode execMode, bytes calldata executionCalldata)
external
payable
returns (bytes[] memory returnData)
{
// no modifier needed, checking if msg.sender is registered executor will replace the modifier
IHook hook = _executorConfig(IExecutor(msg.sender)).hook;
if (address(hook) == address(0)) {
revert InvalidExecutor();
}
bytes memory context;
if (address(hook) != address(1)) {
context = _doPreHook(hook, msg.value, msg.data);
}
returnData = ExecLib.execute(execMode, executionCalldata);
if (address(hook) != address(1)) {
_doPostHook(hook, context, true, abi.encode(returnData));
}
}
function execute(ExecMode execMode, bytes calldata executionCalldata) external payable onlyEntryPointOrSelfOrRoot {
ExecLib.execute(execMode, executionCalldata);
}
function isValidSignature(bytes32 hash, bytes calldata signature) external view override returns (bytes4) {
ValidationStorage storage vs = _validationStorage();
(ValidationId vId, bytes calldata sig) = ValidatorLib.decodeSignature(signature);
if (ValidatorLib.getType(vId) == VALIDATION_TYPE_ROOT) {
vId = vs.rootValidator;
}
if (address(vs.validationConfig[vId].hook) == address(0)) {
revert InvalidValidator();
}
if (ValidatorLib.getType(vId) == VALIDATION_TYPE_VALIDATOR) {
IValidator validator = ValidatorLib.getValidator(vId);
return validator.isValidSignatureWithSender(msg.sender, _toWrappedHash(hash), sig);
} else {
PermissionId pId = ValidatorLib.getPermissionId(vId);
PassFlag permissionFlag = vs.permissionConfig[pId].permissionFlag;
if (PassFlag.unwrap(permissionFlag) & PassFlag.unwrap(SKIP_SIGNATURE) != 0) {
revert PermissionNotAlllowedForSignature();
}
return _checkPermissionSignature(pId, msg.sender, hash, sig);
}
}
function installModule(uint256 moduleType, address module, bytes calldata initData)
external
payable
override
onlyEntryPointOrSelfOrRoot
{
if (moduleType == MODULE_TYPE_VALIDATOR) {
ValidationStorage storage vs = _validationStorage();
ValidationId vId = ValidatorLib.validatorToIdentifier(IValidator(module));
ValidationConfig memory config =
ValidationConfig({nonce: vs.currentNonce, hook: IHook(address(bytes20(initData[0:20])))});
bytes calldata validatorData;
bytes calldata hookData;
assembly {
validatorData.offset := add(add(initData.offset, 52), calldataload(add(initData.offset, 20)))
validatorData.length := calldataload(sub(validatorData.offset, 32))
hookData.offset := add(add(initData.offset, 52), calldataload(add(initData.offset, 52)))
hookData.length := calldataload(sub(hookData.offset, 32))
}
_installValidation(vId, config, validatorData, hookData);
//_installHook(config.hook, hookData); hook install is handled inside installvalidation
} else if (moduleType == MODULE_TYPE_EXECUTOR) {
bytes calldata executorData;
bytes calldata hookData;
assembly {
executorData.offset := add(add(initData.offset, 52), calldataload(add(initData.offset, 20)))
executorData.length := calldataload(sub(executorData.offset, 32))
hookData.offset := add(add(initData.offset, 52), calldataload(add(initData.offset, 52)))
hookData.length := calldataload(sub(hookData.offset, 32))
}
IHook hook = IHook(address(bytes20(initData[0:20])));
_installExecutor(IExecutor(module), executorData, hook);
_installHook(hook, hookData);
} else if (moduleType == MODULE_TYPE_FALLBACK) {
bytes calldata selectorData;
bytes calldata hookData;
assembly {
selectorData.offset := add(add(initData.offset, 56), calldataload(add(initData.offset, 24)))
selectorData.length := calldataload(sub(selectorData.offset, 32))
hookData.offset := add(add(initData.offset, 56), calldataload(add(initData.offset, 56)))
hookData.length := calldataload(sub(hookData.offset, 32))
}
_installSelector(bytes4(initData[0:4]), module, IHook(address(bytes20(initData[4:24]))), selectorData);
_installHook(IHook(address(bytes20(initData[4:24]))), hookData);
} else if (moduleType == MODULE_TYPE_HOOK) {
// force call onInstall for hook
// NOTE: for hook, kernel does not support independant hook install,
// hook is expected to be paired with proper validator/executor/selector
IHook(module).onInstall(initData);
} else if (moduleType == MODULE_TYPE_POLICY) {
// force call onInstall for policy
// NOTE: for policy, kernel does not support independant policy install,
// policy is expected to be paired with proper permissionId
// to "ADD" permission, use "installValidations()" function
IPolicy(module).onInstall(initData);
} else if (moduleType == MODULE_TYPE_SIGNER) {
// force call onInstall for signer
// NOTE: for signer, kernel does not support independant signer install,
// signer is expected to be paired with proper permissionId
// to "ADD" permission, use "installValidations()" function
ISigner(module).onInstall(initData);
} else {
revert InvalidModuleType();
}
}
function installValidations(
ValidationId[] calldata vIds,
ValidationConfig[] memory configs,
bytes[] calldata validationData,
bytes[] calldata hookData
) external payable onlyEntryPointOrSelfOrRoot {
_installValidations(vIds, configs, validationData, hookData);
}
function uninstallValidation(ValidationId vId, bytes calldata deinitData, bytes calldata hookDeinitData)
external
payable
onlyEntryPointOrSelfOrRoot
{
IHook hook = _uninstallValidation(vId, deinitData);
_uninstallHook(hook, hookDeinitData);
}
function invalidateNonce(uint32 nonce) external payable onlyEntryPointOrSelfOrRoot {
_invalidateNonce(nonce);
}
function uninstallModule(uint256 moduleType, address module, bytes calldata deInitData)
external
payable
override
onlyEntryPointOrSelfOrRoot
{
if (moduleType == 1) {
ValidationId vId = ValidatorLib.validatorToIdentifier(IValidator(module));
_uninstallValidation(vId, deInitData);
} else if (moduleType == 2) {
_uninstallExecutor(IExecutor(module), deInitData);
} else if (moduleType == 3) {
bytes4 selector = bytes4(deInitData[0:4]);
_uninstallSelector(selector, deInitData[4:]);
} else if (moduleType == 4) {
ValidationId vId = _validationStorage().rootValidator;
if (_validationStorage().validationConfig[vId].hook == IHook(module)) {
// when root validator hook is being removed
// remove hook on root validator to prevent kernel from being locked
_validationStorage().validationConfig[vId].hook = IHook(address(1));
}
// force call onInstall for hook
// NOTE: for hook, kernel does not support independant hook install,
// hook is expected to be paired with proper validator/executor/selector
ModuleLib.uninstallModule(module, deInitData);
} else if (moduleType == 5) {
ValidationId rootValidator = _validationStorage().rootValidator;
bytes32 permissionId = bytes32(deInitData[0:32]);
if (ValidatorLib.getType(rootValidator) == VALIDATION_TYPE_PERMISSION) {
if (permissionId == bytes32(PermissionId.unwrap(ValidatorLib.getPermissionId(rootValidator)))) {
revert RootValidatorCannotBeRemoved();
}
}
// force call onInstall for policy
// NOTE: for policy, kernel does not support independant policy install,
// policy is expected to be paired with proper permissionId
// to "REMOVE" permission, use "uninstallValidation()" function
ModuleLib.uninstallModule(module, deInitData);
} else if (moduleType == 6) {
ValidationId rootValidator = _validationStorage().rootValidator;
bytes32 permissionId = bytes32(deInitData[0:32]);
if (ValidatorLib.getType(rootValidator) == VALIDATION_TYPE_PERMISSION) {
if (permissionId == bytes32(PermissionId.unwrap(ValidatorLib.getPermissionId(rootValidator)))) {
revert RootValidatorCannotBeRemoved();
}
}
// force call onInstall for signer
// NOTE: for signer, kernel does not support independant signer install,
// signer is expected to be paired with proper permissionId
// to "REMOVE" permission, use "uninstallValidation()" function
ModuleLib.uninstallModule(module, deInitData);
} else {
revert InvalidModuleType();
}
}
function supportsModule(uint256 moduleTypeId) external pure override returns (bool) {
if (moduleTypeId < 7) {
return true;
} else {
return false;
}
}
function isModuleInstalled(uint256 moduleType, address module, bytes calldata additionalContext)
external
view
override
returns (bool)
{
if (moduleType == MODULE_TYPE_VALIDATOR) {
return _validationStorage().validationConfig[ValidatorLib.validatorToIdentifier(IValidator(module))].hook
!= IHook(address(0));
} else if (moduleType == MODULE_TYPE_EXECUTOR) {
return address(_executorConfig(IExecutor(module)).hook) != address(0);
} else if (moduleType == MODULE_TYPE_FALLBACK) {
return _selectorConfig(bytes4(additionalContext[0:4])).target == module;
} else {
return false;
}
}
function accountId() external pure override returns (string memory accountImplementationId) {
return "kernel.advanced.v0.3.0-beta";
}
function supportsExecutionMode(ExecMode mode) external pure override returns (bool) {
(CallType callType, ExecType execType, ExecModeSelector selector, ExecModePayload payload) =
ExecLib.decode(mode);
if (
callType != CALLTYPE_BATCH && callType != CALLTYPE_SINGLE && callType != CALLTYPE_DELEGATECALL
&& callType != CALLTYPE_STATIC
) {
return false;
}
if (
ExecType.unwrap(execType) != ExecType.unwrap(EXECTYPE_TRY)
&& ExecType.unwrap(execType) != ExecType.unwrap(EXECTYPE_DEFAULT)
) {
return false;
}
if (ExecModeSelector.unwrap(selector) != ExecModeSelector.unwrap(EXEC_MODE_DEFAULT)) {
return false;
}
if (ExecModePayload.unwrap(payload) != bytes22(0)) {
return false;
}
return true;
}
}