抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

前言

最近在做 damn defi 靶场的时候,遇到了一些题涉及到 GnosisSafe 相关知识的题。查缺补漏,先来学习学习 GnosisSafe 合约。

解读 GnosisSafe的父合约

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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "./base/ModuleManager.sol";
import "./base/OwnerManager.sol";
import "./base/FallbackManager.sol";
import "./base/GuardManager.sol";
import "./common/EtherPaymentFallback.sol";
import "./common/Singleton.sol";
import "./common/SignatureDecoder.sol";
import "./common/SecuredTokenTransfer.sol";
import "./common/StorageAccessible.sol";
import "./interfaces/ISignatureValidator.sol";
import "./external/GnosisSafeMath.sol";

/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafe is
EtherPaymentFallback,
Singleton,
ModuleManager,
OwnerManager,
SignatureDecoder,
SecuredTokenTransfer,
ISignatureValidatorConstants,
FallbackManager,
StorageAccessible,
GuardManager
{

首先不难看出,该合约继承了一大堆合约,没办法只能先把他的一系列父合约看完。

1. EtherPaymentFallback.sol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
/// @author Richard Meissner - <richard@gnosis.pm>
contract EtherPaymentFallback {
// 接收到ETH时触发
event SafeReceived(address indexed sender, uint256 value);

/// @dev Fallback function accepts Ether transactions.
// 回调函数,用于接收ETH
receive() external payable {
emit SafeReceived(msg.sender, msg.value);
}
}

该合约比较简单,只有一个用于接收ETH的回调函数,继承该合约后,子类可以接收其他合约转发的ETH。

2. Singleton.sol

1
2
3
4
5
6
7
8
9
10
11
12
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title Singleton - Base for singleton contracts (should always be first super contract)
/// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
/// @author Richard Meissner - <richard@gnosis.io>
contract Singleton {
// singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
// It should also always be ensured that the address is stored alone (uses a full word)
address private singleton;
}

该合约就只有一个全局私有的地址变量。它是用于在代理模式中确保与逻辑合约中的变量位置保持一致。

3. ModuleManager.sol

该合约又继承了两个合约,先看他的两个父合约。

3.1 SelfAuthorized.sol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title SelfAuthorized - authorizes current contract to perform actions
/// @author Richard Meissner - <richard@gnosis.pm>
contract SelfAuthorized {

// 执行判断语句,规定调用者地址 须为 本合约地址
function requireSelfCall() private view {
require(msg.sender == address(this), "GS031");
}

// 修饰器,调用 requireSelfCall 函数,被该修饰器修饰的函数的调用者须为该合约才可以调用
modifier authorized() {
// This is a function call as it minimized the bytecode size
requireSelfCall();
_;
}
}

该合约主要是提供了一个修饰器,用于限制某些函数的调用者身份必须为本合约才行。

3.2 Executor.sol

该合约继承了 Enum.sol , 先看 Enum.sol

3.2.1 Enum.sol
1
2
3
4
5
6
7
8
9
10
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title Enum - Collection of enums
/// @author Richard Meissner - <richard@gnosis.pm>
contract Enum {
// 这是一个枚举类型的,定义了两种操作类型 call 和 delegatecall
enum Operation {Call, DelegateCall}
}

这个枚举类型定义了两个操作类型,分别是 CallDelegateCall。它们分别表示不同的智能合约调用方式:

  • Call:表示通过合约地址直接调用另一个合约的函数。在这种调用方式下,调用者的上下文(例如合约地址和发送者地址)会被保留。
  • DelegateCall:表示通过合约地址委托调用另一个合约的函数。在这种调用方式下,调用者的上下文会被传递给被调用的合约,以便该合约可以访问调用者的状态和权限。

这个枚举类型常用于智能合约中的多签名钱包等场景中,以指定不同的操作类型。例如,多签名钱包可以使用 Call 操作来执行标准的转账操作,而使用 DelegateCall 操作来执行复杂的合约逻辑,以确保调用者的权限和状态得到保护。

在使用这个枚举类型时,可以通过以下方式来访问枚举值:

1
Operation op = Operation.Call;

其中,op 是一个 Operation 类型的变量,它可以被赋值为 CallDelegateCall

看完 Enum.sol,我们在看会 Executor.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
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";

/// @title Executor - A contract that can execute transactions
/// @author Richard Meissner - <richard@gnosis.pm>
contract Executor {

function execute(
address to, // 目的地址
uint256 value, // msg.value
bytes memory data, // 操作的ABI编码
Enum.Operation operation, // 这里是指 Enum合约中的两种操作方式,call 和 delegatecall
uint256 txGas // gas
) internal returns (bool success) {
// 如果 operation 是委托调用则执行delegatecall,反之则执行call
if (operation == Enum.Operation.DelegateCall) {
// solhint-disable-next-line no-inline-assembly
assembly {
success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
}
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
}


​ 该函数乍一看,使用了内联汇编中的 call 和 delegatecall,用于执行交易,比如函数的调用等。虽然两个参数是一样的,但是原理截然不同,可以看我写的一篇 文章

总之, 该合约给我们提供了两种执行方式,一种是直接调用 call另一种是委托调用 delegatecal

看完 ModuleManager.sol的两个父合约,我们看回 ModuleManager.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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "./Executor.sol";

/// @title Module Manager - A contract that manages modules that can execute transactions via this contract
/// @author Stefan George - <stefan@gnosis.pm>
/// @author Richard Meissner - <richard@gnosis.pm>
contract ModuleManager is SelfAuthorized, Executor {
event EnabledModule(address module);
event DisabledModule(address module);
event ExecutionFromModuleSuccess(address indexed module);
event ExecutionFromModuleFailure(address indexed module);

// address(0x1) = 0x0000000000000000000000000000000000000001
address internal constant SENTINEL_MODULES = address(0x1);

mapping(address => address) internal modules;

// 设置模块
/** 该函数可以简单理解为, 使用委托调用的方式 调用 to 中的函数 (data为函数的ABI编码) */
function setupModules(address to, bytes memory data) internal {
// 判断 SENTINEL_MODULES 是否被执行过
require(modules[SENTINEL_MODULES] == address(0), "GS100");
// 将 SENTINEL_MODULES 放入映射中,代表操作已被执行,将不能调用该函数
modules[SENTINEL_MODULES] = SENTINEL_MODULES;
// 目的地址不能是 0 地址
if (to != address(0))
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
}

/// @dev Allows to add a module to the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Enables the module `module` for the Safe.
/// @param module Module to be whitelisted.
function enableModule(address module) public authorized {
// Module address cannot be null or sentinel.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
// Module cannot be added twice.
// 未给modules[module]赋值的情况下,modules[module] = address(0)
require(modules[module] == address(0), "GS102");
// 表示 module 已经被添加过了,不是 address(0)了
modules[module] = modules[SENTINEL_MODULES];
// 重置 SENTINEL_MODULES 的映射
modules[SENTINEL_MODULES] = module;
emit EnabledModule(module);
}

/// @dev Allows to remove a module from the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Disables the module `module` for the Safe.
/// @param prevModule Module that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) public authorized {
// Validate module address and check that it corresponds to module index.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
// 验证 prevModule 是不是 module的前一个模块
require(modules[prevModule] == module, "GS103");
// 将 module现在的身份转交到 preModule上
modules[prevModule] = modules[module];
// 移除 module 的身份
modules[module] = address(0);
emit DisabledModule(module);
}

/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
// 允许模块执行安全事务,无需任何进一步确认
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
/** 调用 Executor合约中的 execute函数,调用 to 中的一些操作 */
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public virtual returns (bool success) {
// Only whitelisted modules are allowed.
// 只有被添加到白名单才可以被执行
require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
// Execute transaction without further confirmations.
success = execute(to, value, data, operation, gasleft());
if (success) emit ExecutionFromModuleSuccess(msg.sender);
else emit ExecutionFromModuleFailure(msg.sender);
}

/// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
/** 和 execTransactionFromModule 差不多只是多了个返回值returnData */
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public returns (bool success, bytes memory returnData) {
success = execTransactionFromModule(to, value, data, operation);
// solhint-disable-next-line no-inline-assembly
// 如下操作是为了得到 returnDate
assembly {
// Load free memory location
let ptr := mload(0x40)
// We allocate memory for the return data by setting the free memory location to
// current free memory location + data size + 32 bytes for data size value
mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
// Store the size
mstore(ptr, returndatasize())
// Store the data
returndatacopy(add(ptr, 0x20), 0, returndatasize())
// Point the return data to the correct memory location
returnData := ptr
}
}

/// @dev Returns if an module is enabled
/// @return True if the module is enabled
/** 判断 该module 是否被添加到白名单之中 */
function isModuleEnabled(address module) public view returns (bool) {
return SENTINEL_MODULES != module && modules[module] != address(0);
}

/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
/** 得到一个模块的映射链 */
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
// Init array with max page size
array = new address[](pageSize);

// Populate return array
uint256 moduleCount = 0;
address currentModule = modules[start];
while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
array[moduleCount] = currentModule;
currentModule = modules[currentModule];
moduleCount++;
}
next = currentModule;
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(array, moduleCount)
}
}
}

解读 enableModule函数:

将一个模块加入白名单,查看这个函数的逻辑可以发现,它将原哨兵模块(SENTINEL_MODULES) 对应的地址赋值给最新的模块,然后将哨兵模块的值设置为最新添加的模块。

实际调用此函数,说明其用法:

1
2
3
4
5
6
7
8
9
10
/** 伪代码, 调用 enableMoudule 函数*/
enableModule(0x3);
enableModule(0x4);
enableModule(0x5);

/** 我们得到的结果 */
modules[0x3] = 0x1;
modules[0x4] = 0x3;
modules[0x5] = 0x4;
modules[0x1] = 0x5;

以上就是连续调用 该函数的赋值过程及结果。

解读 disableModule 函数:

实际调用函数实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/** 函数调用,假设执行如下两条执行 */
disableModule(0x3,0x1);
disableModule(0x4,0x3);
// 第一条
modules[0x3] = modules[0x1] = 0x5, modules[0x1] = 0x0
// 剩下的模块链
modules[0x3] = 0x5;
modules[0x4] = 0x3;
modules[0x5] = 0x4;
// 第二条
modules[0x4] = modules[0x3] = 0x5, modules[0x3] = 0x0
// 剩下的模块链
modules[0x4] = 0x5;
modules[0x5] = 0x4;

以上就是连续调用 该函数的赋值过程及结果。

注:以上两个函数的都有authorized修饰符修饰,限制了函数调用者的身份。

解读 execTransactionFromModule 函数:

该函数实际上就是在调用 Executor合约中的 execute函数,但是该函数的调用者需要被添加到白名单中。

解读 execTransactionFromModuleReturnData函数:

同上一个函数差不多,只是多了一个返回值 returnData,细看其中的获取返回值的内联汇编部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
assembly {
// Load free memory location
let ptr := mload(0x40)
// We allocate memory for the return data by setting the free memory location to
// current free memory location + data size + 32 bytes for data size value
mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
// Store the size
mstore(ptr, returndatasize())
// Store the data
returndatacopy(add(ptr, 0x20), 0, returndatasize())
// Point the return data to the correct memory location
returnData := ptr
}
  1. 得到自由内存指针地址(存在0x40)。
  2. 将自由内存指针地址重新设定在当前地址 + 数据大小 + 长度前缀 的地址,多出来的空间(长度前缀 + 数据大小 )为是了构造 返回值returnData
  3. 写入长度前缀,从旧自由内存指针地址开始写入一个word(32字节),值为返回的数据大小。这里的返回数据哪来的呢?因为本函数调用了execTransactionFromModule函数,虽然execTransactionFromModule函数是个public函数,但是我们这里却只是内部跳转,并没有涉及到消息调用,因此你可以认为是execTransactionFromModule的代码直接复制了过来。而execTransactionFromModule又调用了execute,这同样是一个内部调用,因此返回值来源于execute的执行结果。 注意,这里只有消息调用(合约之间或者EOA与合约之间)才会有returndata,它并不是普通函数之间相互调用的返回值(函数返回值是Solidity语言)。
  4. 将returndata的内容复制到内存中,returndatacopy操作码我们已经多次见到,为什么从add(ptr, 0x20)开始呢,因为ptr开始的32字节我们在上一步存入了长度前缀。
  5. 最后设定返回Solidity返回数据returnData的内存地址,从prt开始分别为它的长度前缀和实际数据。

解读 getModulesPaginated 函数:

分页获取白名单模块,返回一个白名单数组。这里为什么要采用分页呢?因为理论上,可以注册个无数模块,因此返回的数据可以无限大。然而却是有gasLimit的,所以数组过大会导致调用失败,因此采用了分页模式,可以调整返回的数组大小和起始位置。

这里view类型的函数同样也会受到gas限制,同样也会gas超限。

本函数的逻辑使用了一个while从后向前循环模块链,取出分页大小的模块。如果不足(没有注册或者为哨兵模块),则立刻终止。

一个比较实用的技巧是最后的内嵌汇编,用来改变返回数组的大小。

1
2
3
assembly {
mstore(array, moduleCount)
}

我们知道,数组在汇编中的内存layout也是值为内存地址,开始32字节存的是数组长度,后面再接数据内容。

由于我们分页获取的数组可能未填充满,比如取10个,我们只有4个。因此后面6个元素为空的。此时我们返回空元素的话会浪费空间。因此,可以直接修改返回的数据大小为4,这里就示例了一种直接修改方法。

直接将数组地址开始的32字节(存储数组大小)赋值为实际数组大小。
这是一个很实用的技巧,我们平常在遇到数组不能填充满时也可以使用此技巧。

修改大小后本来返回10个元素的数组变成了返回4个元素的数组,而有效内容是相同的

1
2
3
4
5
6
7
8
9
10
11
// 假如我们的模块链如下
modules[0x3] = 0x1;
modules[0x4] = 0x3;
modules[0x5] = 0x4;
modules[0x1] = 0x5;

// 调用此函数
getModulesPaginated(0x4,3)

// 返回的array结果
array = [0x3,0x1,0x5]

4. OwnerManager.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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";

/// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
/// @author Stefan George - <stefan@gnosis.pm>
/// @author Richard Meissner - <richard@gnosis.pm>
contract OwnerManager is SelfAuthorized {
event AddedOwner(address owner);
event RemovedOwner(address owner);
event ChangedThreshold(uint256 threshold);

address internal constant SENTINEL_OWNERS = address(0x1);

// 存储某地址的owner的映射
mapping(address => address) internal owners;
uint256 internal ownerCount; // owner数量
uint256 internal threshold; // 门槛

/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
// Threshold can only be 0 at initialization.
// Check ensures that setup function can only be called once.
// 确保此函数只能被执行一次
require(threshold == 0, "GS200");
// Validate that threshold is smaller than number of added owners.
require(_threshold <= _owners.length, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
// Initializing Safe owners.
address currentOwner = SENTINEL_OWNERS;
/** 形成了一个环状链, SENTINEL_OWNERS -> ... -> SENTINEL_OWNERS */
for (uint256 i = 0; i < _owners.length; i++) {
// Owner address cannot be null.
address owner = _owners[i];
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204"); // 限制了一个地址只能被添加一次
owners[currentOwner] = owner;
currentOwner = owner;
}
// 此时遍历到了最后一个索引,将 owners[last]指向SENTINEL_OWNERS
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = _owners.length;
threshold = _threshold;
}

/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
/// @param owner New owner address.
/// @param _threshold New threshold.
/** 和数据结构中单向循环链表的添加方式差不多 */
function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}

/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
/// @param prevOwner Owner that pointed to the owner to be removed in the linked list
/// @param owner Owner address to be removed.
/// @param _threshold New threshold.
/** 数据结构单向循环链表 */
function removeOwner(
address prevOwner,
address owner,
uint256 _threshold
) public authorized {
// Only allow to remove an owner, if threshold can still be reached.
require(ownerCount - 1 >= _threshold, "GS201");
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == owner, "GS205");
owners[prevOwner] = owners[owner]; // pre 指向 owner.next
owners[owner] = address(0); // 移除指针
ownerCount--;
emit RemovedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}

/// @dev Allows to swap/replace an owner from the Safe with another address.
/// This can only be done via a Safe transaction.
/// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "GS204");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == oldOwner, "GS205");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}

/// @dev Allows to update the number of required confirmations by Safe owners.
/// This can only be done via a Safe transaction.
/// @notice Changes the threshold of the Safe to `_threshold`.
/// @param _threshold New threshold.
function changeThreshold(uint256 _threshold) public authorized {
// Validate that threshold is smaller than number of owners.
require(_threshold <= ownerCount, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
threshold = _threshold;
emit ChangedThreshold(threshold);
}

function getThreshold() public view returns (uint256) {
return threshold;
}

function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}

/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);

// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
}

**解读setupOwners**:

模拟一下,假定初始owner列表为[0x2,0x3,0x4],初始门槛为3签2,那么两个参数分别为[0x2,0x3,0x4]与2。

执行setupOwners后的结果应该为:

1
2
3
4
5
6
owners[0x1]=0x2
owners[0x2]=0x3
owners[0x3]=0x4
owners[0x4]=0x1
ownerCount = 3
threshold = 2

可以看到他们形成了一个闭环地址链。

注意For循环中有require来验证地址不能被添加2次,也不能添加零地址和哨兵地址(添加哨兵地址会使哨兵作用失效)。

最后记录了当前owners的数量,因为owners是个mapping,如果想得到它的记录数量必须使用一个新的状态变量来记录。

**解读addOwnerWithThreshold**:

这里的添加方式是:单个添加,哨兵指向新owner,新owner指向 owners[SENTINEL_OWNERS],如果学过数据结构的话,很容易理解。

模拟一下,在上个函数的基础上,调用两次该函数,参数分别是:0x5 和 0x6

1
2
3
4
5
6
7
8
9
// 如下是运行结果
owners[0x1]=0x6
owners[0x2]=0x3
owners[0x3]=0x4
owners[0x4]=0x1
owners[0x5]=0x2
owners[0x6]=0x5
ownerCount = 5
threshold = 2

这里有5个owner地址,因为哨兵地址0x1不算。它们和哨兵地址形成了一个闭环。SENTINEL_OWNERS可以理解为一个工具人,用来形成闭环的介质,方便代码的实现。

**解读removeOwner **:

类似数据结构单向循环链表的删除节点操作。

模拟一下,remove 0x03 0x04 3 。得到的结果如下:

1
2
3
4
5
6
7
owners[0x1]=0x6
owners[0x2]=0x3
owners[0x3]=0x1
owners[0x5]=0x2
owners[0x6]=0x5
ownerCount = 4
threshold = 3

这里owner少了一个0x4,所以只有4个了,它们仍然和哨兵地址形成了一个闭环。

**解读swapOwner**:

类似数据结构中单向循环链表的替换操作。

要求是newOwner不能为address(0),比较简单,不过多赘述。

**解读getOwners**:

以数组形式返回整个 owners映射链,其中也包含了哨兵 SENTINEL_OWNERS

5. SignatureDecoder.sol

该合约提供了一个解析签名的函数,名为signatureSplit,将签名解码为 r, s, v。我们可以通过r, s, v以太坊签名消息来求得公钥

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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title SignatureDecoder - Decodes signatures that a encoded as bytes
/// @author Richard Meissner - <richard@gnosis.pm>
contract SignatureDecoder {
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
/// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
/// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
/// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos)
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
let signaturePos := mul(0x41, pos)
r := mload(add(signatures, add(signaturePos, 0x20)))
s := mload(add(signatures, add(signaturePos, 0x40)))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
}
}
}

相关知识: 链接

6. SecuredTokenTransfer.sol

该合约提供了了一个转账的方法,本质是调用 ("transfer(address,uint256)")函数,这里采用了内联汇编的方法(其目的是为了能够得到返回值),比较简单,不熟悉的可以去看看 官方文档

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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title SecuredTokenTransfer - Secure token transfer
/// @author Richard Meissner - <richard@gnosis.pm>
contract SecuredTokenTransfer {
/// @dev Transfers a token and returns if it was a success
/// @param token Token that should be transferred
/// @param receiver Receiver to whom the token should be transferred
/// @param amount The amount of tokens that should be transferred
function transferToken(
address token,
address receiver,
uint256 amount
) internal returns (bool transferred) {
// 0xa9059cbb - keccack("transfer(address,uint256)")
bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
// solhint-disable-next-line no-inline-assembly
assembly {
// We write the return value to scratch space.
// See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
switch returndatasize()
case 0 {
transferred := success
}
case 0x20 {
transferred := iszero(or(iszero(success), iszero(mload(0))))
}
default {
transferred := 0
}
}
}
}

7. ISignatureValidator.sol

这是一个抽象函数,实现者必须要实现其 isValidSignature方法,且当成功调用 isValidSignature此函数时,必须要返回一个 bytes4 类型的值,且该值必须是 EIP1271_MAGIC_VALUE0x20c13b0b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

contract ISignatureValidatorConstants {
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
}

abstract contract ISignatureValidator is ISignatureValidatorConstants {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x20c13b0b when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
}

8. FallbackManager.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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "../common/SelfAuthorized.sol";

/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <richard@gnosis.pm>
contract FallbackManager is SelfAuthorized {
event ChangedFallbackHandler(address handler);

// keccak256("fallback_manager.handler.address")
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;

// 内部函数,使用内联汇编方式修改状态变量 FALLBACK_HANDLER_STORAGE_SLOT
function internalSetFallbackHandler(address handler) internal {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, handler)
}
}

/// @dev Allows to add a contract to handle fallback calls.
/// Only fallback calls without value and with data will be forwarded.
/// This can only be done via a Safe transaction.
/// @param handler contract to handle fallbacks calls.
// 设置新的 handeler,但只能是本合约对象才能调用
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}

// solhint-disable-next-line payable-fallback,no-complex-fallback
/** 回调函数,执行data中的命令(函数) */
fallback() external {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
let handler := sload(slot)
if iszero(handler) {
return(0, 0)
}
calldatacopy(0, 0, calldatasize())
// The msg.sender address is shifted to the left by 12 bytes to remove the padding
// Then the address without padding is stored right after the calldata
mstore(calldatasize(), shl(96, caller()))
// Add 20 bytes for the address appended add the end
let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
returndatacopy(0, 0, returndatasize())
if iszero(success) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}

解读fallback():

和代理合约很像,该函数的功能是调用 handler 中 data 指定的命令。

代理合约相关知识,可移步到 这里

9. StorageAccessible.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
```

> **解读`getStorageAt`:**
>
> 挨个读取合约中slot的值。
>
> 举例说明:
>
> ```solidity
> // SPDX-License-Identifier: MIT
> pragma solidity ^0.8.0;
>
> contract StorageAt {
>
> address private solt0 = msg.sender;
> uint private solt1 = 9;
> string private solt2 = unicode"不良人";
> bytes private solt3 = "biyou";
>
> function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
> bytes memory result = new bytes(length * 32); // 创建一个长度为 length * 32的数组
> for (uint256 index = 0; index < length; index++) {
> // solhint-disable-next-line no-inline-assembly
> assembly {
> let word := sload(add(offset, index)) // 每次移动32bytes
> mstore(add(add(result, 0x20), mul(index, 0x20)), word)
> }
> }
> return result;
> }
> }

运行结果:

image-20230723200433752

解读simulateAndRevert

  1. 执行一个委托调用操作,使用 delegatecall 指令将当前合约的上下文传递给目标合约,并将 calldataPayload 作为调用数据传递给目标合约。
  2. 使用 mstore 指令将调用结果的布尔值(表示调用是否成功)存储在内存地址 0x00 处。
  3. 使用 mstore 指令将调用结果的字节数(即 returndatasize())存储在内存地址 0x20 处。
  4. 使用 returndatacopy 指令将调用结果的字节流(即 returndata)从返回数据缓冲区复制到内存地址 0x40 处。
  5. 使用 revert 指令将当前合约的执行回滚,并将调用结果作为回滚数据返回。具体来说,将内存地址 0x00 处的布尔值、内存地址 0x20 处的字节数和内存地址 0x40 处的字节流作为回滚数据返回。

(该函数是AI解读,暂时有点搞不懂)

10. GuardManager.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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";

interface Guard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;

function checkAfterExecution(bytes32 txHash, bool success) external;
}

/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <richard@gnosis.pm>
contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;

/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}

function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}

解读:

这个合约很简单,有点内联汇编知识的应该很容易理解。

setGuard:使用汇编语言修改状态变量;

getGuard: 使用汇编语言读取状态变量。

到此,GnosisSafe继承的所有父合约都过了一遍。一天也差不多了过去了,水平有限,出错也是难免的,欢迎大佬们给我纠错。

解读GnosisSafe合约

这是一个代理合约。

1. 源码

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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "./base/ModuleManager.sol";
import "./base/OwnerManager.sol";
import "./base/FallbackManager.sol";
import "./base/GuardManager.sol";
import "./common/EtherPaymentFallback.sol";
import "./common/Singleton.sol";
import "./common/SignatureDecoder.sol";
import "./common/SecuredTokenTransfer.sol";
import "./common/StorageAccessible.sol";
import "./interfaces/ISignatureValidator.sol";
import "./external/GnosisSafeMath.sol";

/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafe is
EtherPaymentFallback,
Singleton,
ModuleManager,
OwnerManager,
SignatureDecoder,
SecuredTokenTransfer,
ISignatureValidatorConstants,
FallbackManager,
StorageAccessible,
GuardManager
{
using GnosisSafeMath for uint256;

string public constant VERSION = "1.3.0";

// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
// 签名是使用 EIP712 签名标志
bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;

// keccak256(
// "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
// );
bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;

event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
event SignMsg(bytes32 indexed msgHash);
event ExecutionFailure(bytes32 txHash, uint256 payment);
event ExecutionSuccess(bytes32 txHash, uint256 payment);

uint256 public nonce;
bytes32 private _deprecatedDomainSeparator;
// Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
mapping(bytes32 => uint256) public signedMessages;
// Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
mapping(address => mapping(bytes32 => uint256)) public approvedHashes;

// This constructor ensures that this contract can only be used as a master copy for Proxy contracts
// 此构造函数确保此协定只能用作代理协定的主副本
constructor() {
// By setting the threshold it is not possible to call setup anymore,
// so we create a Safe with 0 owners and threshold 1.
// This is an unusable Safe, perfect for the singleton
threshold = 1; // 设置门槛为1,本身将不能调用自身的setup函数
}

/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external {
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
// 如果该合约被初始化了,则 setupOwners 无法调用成功
setupOwners(_owners, _threshold);
// 如果 fallbackHandler 不为0地址,则修改 fallbackHandler的值
if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
// As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
setupModules(to, data); // 初始化Module,并执行委托调用

if (payment > 0) {
// To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
// baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
// paymentToken如果是代币地址,则调用transfer函数,如果是address(0),则是发送 ETH
handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
}
emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
}

/// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
/// Note: The fees are always transferred, even if the user transaction fails.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param safeTxGas Gas that should be used for the Safe transaction.
/// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Gas price that should be used for the payment calculation.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) public payable virtual returns (bool success) {
bytes32 txHash;
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
bytes memory txHashData =
encodeTransactionData( // 将交易信息打包好
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
nonce
);
// Increase nonce and execute transaction.
nonce++; // 随机数自增
txHash = keccak256(txHashData); // 再对交易信息进行一次hash
checkSignatures(txHash, txHashData, signatures);
}
address guard = getGuard();
{
if (guard != address(0)) {
Guard(guard).checkTransaction(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
signatures,
msg.sender
);
}
}
// We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
// We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
uint256 gasUsed = gasleft();
// If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
// We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
gasUsed = gasUsed.sub(gasleft());
// If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
// This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
// We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
uint256 payment = 0;
if (gasPrice > 0) {
payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
}
if (success) emit ExecutionSuccess(txHash, payment);
else emit ExecutionFailure(txHash, payment);
}
{
if (guard != address(0)) {
Guard(guard).checkAfterExecution(txHash, success);
}
}
}

function handlePayment(
uint256 gasUsed,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver
) private returns (uint256 payment) {
// solhint-disable-next-line avoid-tx-origin
address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
if (gasToken == address(0)) {
// For ETH we will only adjust the gas price to not be higher than the actual used gas price
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
require(receiver.send(payment), "GS011");
} else {
payment = gasUsed.add(baseGas).mul(gasPrice);
require(transferToken(gasToken, receiver, payment), "GS012");
}
}

/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
*/
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
// Load threshold to avoid multiple storage loads
uint256 _threshold = threshold;
// Check that a threshold is set
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}

/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
* @param requiredSignatures Amount of required valid signatures.
*/
function checkNSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures,
uint256 requiredSignatures
) public view {
// Check that the provided signature data is not too short
require(signatures.length >= requiredSignatures.mul(65), "GS020");
// There cannot be an owner with address 0.
address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
// If v is 0 then it is a contract signature
// When handling contract signatures the address of the contract is encoded into r
currentOwner = address(uint160(uint256(r)));

// Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
// This check is not completely accurate, since it is possible that more signatures than the threshold are send.
// Here we only check that the pointer is not pointing inside the part that is being processed
require(uint256(s) >= requiredSignatures.mul(65), "GS021");

// Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
require(uint256(s).add(32) <= signatures.length, "GS022");

// Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
uint256 contractSignatureLen;
// solhint-disable-next-line no-inline-assembly
assembly {
contractSignatureLen := mload(add(add(signatures, s), 0x20))
}
require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");

// Check signature
bytes memory contractSignature;
// solhint-disable-next-line no-inline-assembly
assembly {
// The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
contractSignature := add(add(signatures, s), 0x20)
}
require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
} else if (v == 1) {
// If v is 1 then it is an approved hash
// When handling approved hashes the address of the approver is encoded into r
currentOwner = address(uint160(uint256(r)));
// Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
} else if (v > 30) {
// If v > 30 then default va (27,28) has been adjusted for eth_sign flow
// To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s);
} else {
// Default is the ecrecover flow with the provided data hash
// Use ecrecover with the messageHash for EOA signatures
currentOwner = ecrecover(dataHash, v, r, s);
}
require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
lastOwner = currentOwner;
}
}

/// @dev Allows to estimate a Safe transaction.
/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
function requiredTxGas(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) external returns (uint256) {
uint256 startGas = gasleft();
// We don't provide an error message here, as we use it to return the estimate
require(execute(to, value, data, operation, gasleft()));
uint256 requiredGas = startGas - gasleft();
// Convert response to string and return via error message
revert(string(abi.encodePacked(requiredGas)));
}

/**
* @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
* @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
*/
function approveHash(bytes32 hashToApprove) external {
require(owners[msg.sender] != address(0), "GS030");
approvedHashes[msg.sender][hashToApprove] = 1;
emit ApproveHash(hashToApprove, msg.sender);
}

/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}

function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
}

/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Gas that should be used for the safe transaction.
/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
function encodeTransactionData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 safeTxHash =
keccak256(
abi.encode(
SAFE_TX_TYPEHASH,
to,
value,
keccak256(data),
operation,
safeTxGas,
baseGas,
gasPrice,
gasToken,
refundReceiver,
_nonce
)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
}

/// @dev Returns hash to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param baseGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash.
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
}
}

2. 解读函数

2.1 constructor

构造器的作用是修改阈值,使本合约将不能调用自身的 setupOwners函数,以及 setup函数。

2.2 setup

该函数用于初始化,初始化owner以及module。

2.3 handlePayment

该函数用于转账操作,如果 paymentToken是 0 地址,则执行转ETH的操作;反之,则执行 paymentTokentransfer操作。

2.4 execTransaction

执行多签事务。允许执行由所需数量的所有者确认的安全交易,然后向提交交易的帐户付款。

2.5 encodeTransactionData

该函数用于处理交易数据,将交易所需的数据,入 msg.value, gas,gaslimit等进行打包,再求hash,最后返回一个bytes数组。abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash) ,其中,bytes1(0x19)bytes1(0x01) 分别表示 EIP-191 的版本号和标准消息类型,domainSeparator 函数返回一个字节串,用于标识特定的多签钱包合约,safeTxHash 是一个 uint256 类型的值,表示交易的哈希值。

2.6 checkSignatures

检查签名,签名篇到时候单独去学习一下。反正这个函数就是用来检查签名的。

2.7 requiredTxGas

用于计算消耗了多少gas

2. 8 approveHash

授权。

参考链接

link1

最后,作者水平有限,有错请大佬们及时指出😁

评论



政策 · 统计 | 本站使用 Volantis 主题设计