Michael.W基于Foundry精读Openzeppelin第60期——Clones.sol

  • Michael.W
  • 更新于 2024-06-26 20:45
  • 阅读 954

Clones库是最小代理合约的工厂合约实现,也称之为克隆工厂。ERC1167指定了一种将全部调用都delegatecall到一个已知固定地址的最小字节码实现,它可以以一种不可变且成本极低的方式克隆目标合约。

0. 版本

[openzeppelin]:v4.8.3,[forge-std]:v1.5.6

0.1 Clones.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/proxy/Clones.sol

Clones库是最小代理合约的工厂合约实现,也称之为克隆工厂。ERC1167指定了一种将全部调用都delegatecall到一个已知固定地址的最小字节码实现,它可以以一种不可变且成本极低的方式克隆目标合约。本库分别提供了使用opcode CREATE和CREATE2部署最小代理合约的方法以及CREATE2部署合约的地址预计算工具。

ERC1167详情参见:https://eips.ethereum.org/EIPS/eip-1167

1. 目标合约

封装Clones library成为一个可调用合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/proxy/MockClones.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/proxy/Clones.sol";

contract MockClones {
    using Clones for address;

    function clone(address implementation) external returns (address) {
        return implementation.clone();
    }

    function cloneDeterministic(address implementation, bytes32 salt) external returns (address) {
        return implementation.cloneDeterministic(salt);
    }

    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) external pure returns (address){
        return implementation.predictDeterministicAddress(salt, deployer);
    }

    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) external view returns (address){
        return implementation.predictDeterministicAddress(salt);
    }
}

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/Clones/Clones.t.sol

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/Clones/Implement.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

contract Implement {
    uint public i;
    address public addr;
    uint[3] public fixedArray;
    uint[] public dynamicArray;
    mapping(uint => uint) public map;

    event ImplementReceive(uint value);
    event ImplementFallback(uint value);

    function setUint(uint target) external {
        i = target;
    }

    function setUintPayable(uint target) external payable {
        i = target;
    }

    function setAddress(address target) external {
        addr = target;
    }

    function setAddressPayable(address target) external payable {
        addr = target;
    }

    function setFixedArray(uint[3] memory target) external {
        fixedArray = target;
    }

    function setFixedArrayPayable(uint[3] memory target) external payable {
        fixedArray = target;
    }

    function setDynamicArray(uint[] memory target) external {
        dynamicArray = target;
    }

    function setDynamicArrayPayable(uint[] memory target) external payable {
        dynamicArray = target;
    }

    function setMapping(uint key, uint value) external {
        map[key] = value;
    }

    function setMappingPayable(uint key, uint value) external payable {
        map[key] = value;
    }

    function triggerRevert() external pure {
        revert("Implement: revert");
    }

    function triggerRevertPayable() external payable {
        revert("Implement: revert");
    }

    function getPure() external pure returns (string memory){
        return "pure return value";
    }

    receive() external payable {
        emit ImplementReceive(msg.value);
    }

    fallback() external payable {
        emit ImplementFallback(msg.value);
    }
}

2. 代码精读

2.1 clone(address implementation) internal

使用opcode CREATE来部署一个最小代理合约(implementation是其背后的逻辑合约地址)并返回该合约地址。该方法等同于克隆一个implementation合约。

    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        // 内联汇编
        assembly {
            // shr(0xe8, shl(0x60, implementation)):implementation地址左移96位后再右移232位,构造出一个"低24位为implementation地址高24位,其余高位均为0"的数
            // or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000):将implementation地址高24位接到0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000尾部
            // mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)):
            // 将拼接后的字节码存入position 0开始的内存中,该word中存储的数值为:
            // 0x0000000000000000003d602d80600a3d3981f3363d3d373d3d3d363d73 + implementation地址的高24位
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))

            // or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3):implementation地址左移120位后尾部追加0x5af43d82803e903d91602b57fd5bf3
            // mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)):
            // 将拼接后的字节码存入position 0x20开始的内存中,该word中存储的数值为
            // implementation地址的后256-120=136位 + 0x5af43d82803e903d91602b57fd5bf3
            // 注:此时内存前两个word中存储的内容合为0x0000000000000000003d602d80600a3d3981f3363d3d373d3d3d363d73 + implementation地址 + 0x5af43d82803e903d91602b57fd5bf3
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))

            // 使用opcode CREATE来部署合约。返回新部署的合约地址。
            // 第一个参数:部署合约传入的eth value
            // 第二个参数:bytecode在内存中的起始position,即第9个字节开始
            // 第三个参数:bytecode在内存中的字节长度,即55个字节
            instance := create(0, 0x09, 0x37)
        }
        // 如果返回地址为0地址表示部署失败
        require(instance != address(0), "ERC1167: create failed");
    }

foundry代码验证:

contract ClonesTest is Test {
    MockClones private _testing = new MockClones();
    Implement private _implement = new Implement();

    function test_Clone() external {
        address minimalProxyAddrCloneByOpCreate = _testing.clone(address(_implement));
        testsForMinimalProxyClone(minimalProxyAddrCloneByOpCreate);
    }

    event ImplementReceive(uint value);
    event ImplementFallback(uint value);

    function testsForMinimalProxyClone(address minimalProxyAddress) private {
        Implement minimalProxy = Implement(payable(minimalProxyAddress));
        uint proxyBalance = minimalProxyAddress.balance;
        uint ethValue = 1 wei;
        assertEq(proxyBalance, 0);

        // case 1: test for both writing slot and return data in type uint256
        assertEq(minimalProxy.i(), 0);
        assertEq(_implement.i(), 0);

        // call without eth value
        minimalProxy.setUint(1024);
        assertEq(minimalProxy.i(), 1024);
        assertEq(_implement.i(), 0);

        // call with eth value
        minimalProxy.setUintPayable{value: ethValue}(2048);
        assertEq(minimalProxy.i(), 2048);
        assertEq(_implement.i(), 0);
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // case 2: test for both writing slot and return data in type address
        assertEq(minimalProxy.addr(), address(0));
        assertEq(_implement.addr(), address(0));

        // call without eth value
        minimalProxy.setAddress(address(1024));
        assertEq(minimalProxy.addr(), address(1024));
        assertEq(_implement.addr(), address(0));

        // call with eth value
        minimalProxy.setAddressPayable{value: ethValue}(address(2048));
        assertEq(minimalProxy.addr(), address(2048));
        assertEq(_implement.addr(), address(0));
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // case 3: test for both writing slot and return data in type fixed array
        assertEq(minimalProxy.fixedArray(0), 0);
        assertEq(_implement.fixedArray(0), 0);

        // call without eth value
        uint[3] memory targetFixedArray = [uint(1024), 2048, 4096];
        minimalProxy.setFixedArray(targetFixedArray);
        for (uint i; i < targetFixedArray.length; ++i) {
            assertEq(minimalProxy.fixedArray(i), targetFixedArray[i]);
            assertEq(_implement.fixedArray(i), 0);
        }

        // call with eth value
        targetFixedArray = [uint(2048), 4096, 8192];
        minimalProxy.setFixedArrayPayable{value: ethValue}(targetFixedArray);
        for (uint i; i < targetFixedArray.length; ++i) {
            assertEq(minimalProxy.fixedArray(i), targetFixedArray[i]);
            assertEq(_implement.fixedArray(i), 0);
        }
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // case 4: test for both writing slot and return data in type dynamic array
        // revert when make a staticcall to an uninitialized dynamic array with the length 0
        vm.expectRevert();
        minimalProxy.dynamicArray(0);
        vm.expectRevert();
        _implement.dynamicArray(0);

        // call without eth value
        uint[] memory targetDynamicArray = new uint[](3);
        targetDynamicArray[0] = 1024;
        targetDynamicArray[1] = 2048;
        targetDynamicArray[2] = 4096;

        minimalProxy.setDynamicArray(targetDynamicArray);
        for (uint i; i < targetDynamicArray.length; ++i) {
            assertEq(minimalProxy.dynamicArray(i), targetDynamicArray[i]);
            vm.expectRevert();
            assertEq(_implement.dynamicArray(i), 0);
        }

        // call with eth value
        targetDynamicArray[0] = 2048;
        targetDynamicArray[1] = 4096;
        targetDynamicArray[2] = 8192;

        minimalProxy.setDynamicArrayPayable{value: ethValue}(targetDynamicArray);
        for (uint i; i < targetDynamicArray.length; ++i) {
            assertEq(minimalProxy.dynamicArray(i), targetDynamicArray[i]);
            vm.expectRevert();
            assertEq(_implement.dynamicArray(i), 0);
        }
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // case 5: test for both writing slot and return data in type mapping
        uint key = 1024;
        uint value = 2048;
        assertEq(minimalProxy.map(key), 0);
        assertEq(_implement.map(key), 0);

        // call without eth value
        minimalProxy.setMapping(key, value);
        assertEq(minimalProxy.map(key), value);
        assertEq(_implement.map(key), 0);

        // call with eth value
        key += 1024;
        minimalProxy.setMappingPayable{value: ethValue}(key, value);
        assertEq(minimalProxy.map(key), value);
        assertEq(_implement.map(key), 0);
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // case 6: test for reverting with msg
        // call without eth value
        vm.expectRevert("Implement: revert");
        minimalProxy.triggerRevert();
        vm.expectRevert("Implement: revert");
        _implement.triggerRevert();

        // call with eth value
        vm.expectRevert("Implement: revert");
        minimalProxy.triggerRevertPayable{value: ethValue}();
        vm.expectRevert("Implement: revert");
        _implement.triggerRevertPayable{value: ethValue}();

        // case 7: test for calling pure (staticcall)
        assertEq(minimalProxy.getPure(), "pure return value");
        assertEq(_implement.getPure(), "pure return value");

        // case 8: test call with eth value
        // go into receive() without calldata
        vm.expectEmit(minimalProxyAddress);
        emit ImplementReceive(ethValue);
        (bool ok,) = minimalProxyAddress.call{value: ethValue}("");
        assertTrue(ok);
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);
        proxyBalance = minimalProxyAddress.balance;

        // go into fallback() with calldata of unknown function selector
        vm.expectEmit(minimalProxyAddress);
        emit ImplementFallback(ethValue);
        bytes memory calldata_ = abi.encodeWithSignature("unknown()");
        (ok,) = minimalProxyAddress.call{value: ethValue}(calldata_);
        assertTrue(ok);
        assertEq(minimalProxyAddress.balance, proxyBalance + ethValue);

        // case 9: test call without eth value
        // go into receive() without calldata
        vm.expectEmit(minimalProxyAddress);
        emit ImplementReceive(0);
        (ok,) = minimalProxyAddress.call("");
        assertTrue(ok);

        // go into fallback() with calldata of unknown function selector
        vm.expectEmit(minimalProxyAddress);
        emit ImplementFallback(0);
        (ok,) = minimalProxyAddress.call(calldata_);
        assertTrue(ok);
    }
}

2.2 cloneDeterministic(address implementation, bytes32 salt)

使用opcode CREATE2来部署一个最小代理合约(implementation是其背后的逻辑合约地址,salt为使用CREATE2时传入的随机数)并返回该合约地址。该方法等同于克隆一个implementation合约。

    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        // 内联汇编
        assembly {
            // shr(0xe8, shl(0x60, implementation)):implementation地址左移96位后再右移232位,构造出一个"低24位为implementation地址高24位,其余高位均为0"的数
            // or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000):将implementation地址高24位接到0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000尾部
            // mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)):
            // 将拼接后的字节码存入position 0开始的内存中,该word中存储的数值为:
            // 0x0000000000000000003d602d80600a3d3981f3363d3d373d3d3d363d73 + implementation地址的高24位
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))

            // or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3):implementation地址左移120位后尾部追加0x5af43d82803e903d91602b57fd5bf3
            // mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)):
            // 将拼接后的字节码存入position 0x20开始的内存中,该word中存储的数值为
            // implementation地址的后256-120=136位 + 0x5af43d82803e903d91602b57fd5bf3
            // 注:此时内存前两个word中存储的内容合为0x0000000000000000003d602d80600a3d3981f3363d3d373d3d3d363d73 + implementation地址 + 0x5af43d82803e903d91602b57fd5bf3
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))

            // 使用opcode CREATE2来部署合约。返回新部署的合约地址。
            // 第一个参数:部署合约传入的eth value
            // 第二个参数:bytecode在内存中的起始position,即第9个字节开始
            // 第三个参数:bytecode在内存中的字节长度,即55个字节
            // 第四个参数:随机数
            instance := create2(0, 0x09, 0x37, salt)
        }
        // 如果返回地址为0地址表示部署失败
        require(instance != address(0), "ERC1167: create2 failed");
    }

foundry代码验证:

contract ClonesTest is Test {
    MockClones private _testing = new MockClones();
    Implement private _implement = new Implement();

    function test_CloneDeterministic() external {
        bytes32 salt = keccak256("salt");
        address minimalProxyAddrCloneByOpCreate2 = _testing.cloneDeterministic(address(_implement), salt);
        testsForMinimalProxyClone(minimalProxyAddrCloneByOpCreate2);

        // revert if clone by opcode CREATE2 with the same salt again
        vm.expectRevert("ERC1167: create2 failed");
        _testing.cloneDeterministic(address(_implement), salt);
    }
}

2.3 predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal && predictDeterministicAddress(address implementation, bytes32 salt) internal

  • predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal:预计算使用地址为deployer的合约(该合约使用了Clones库)的cloneDeterministic(address,bytes32) internal方法部署的最小代理合约地址;
  • predictDeterministicAddress(address implementation, bytes32 salt) internal:预计算调用本合约(本合约使用了Clones库)的cloneDeterministic(address,bytes32) internal方法部署的最小代理合约地址。
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        // 内联汇编
        assembly {
            // 获取内存中的空闲指针
            let ptr := mload(0x40)
            // 将deployer写入position ptr+56开始的一个word的内存中([ptr+56, ptr+88])
            // 此时,20个字节deployer地址具体存储在[ptr+68, prt+88]内存中
            mstore(add(ptr, 0x38), deployer)
            // 将0x5af43d82803e903d91602b57fd5bf3ff写入position ptr+36开始的一个word的内存中([ptr+36, ptr+68])
            // 此时,0x5af43d82803e903d91602b57fd5bf3ff具体存储在[ptr+52, prt+68]内存中
            // 注:0x5af43d82803e903d91602b57fd5bf3为最小代理合约的runtime code,0xff为计算CREATE2部署合约地址的起始标志位
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            // 将逻辑合约地址写入position ptr+20开始的一个word的内存中([ptr+20, ptr+52])
            // 此时,20个字节的逻辑合约地址具体存储在[ptr+32, prt+52]内存中
            mstore(add(ptr, 0x14), implementation)
            // 将0x3d602d80600a3d3981f3363d3d373d3d3d363d73写入position ptr开始的一个word的内存中([ptr, ptr+32])
            // 此时,0x3d602d80600a3d3981f3363d3d373d3d3d363d73具体存储在[ptr+12, prt+32]内存中
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            // 该时刻[ptr+12, ptr+67]的内存中已经拼成了最小代理合约的creation code:
            /*********************************************************************************
                                              [MEMORY]
             | ptr ~ ptr+11 | ptr+12            ~                 ptr+31 | ptr+32 ~ ptr+51 | 
               00  ~   00     0x3d602d80600a3d3981f3363d3d373d3d3d363d73      逻辑合约地址
             ---------------------------------------------------------------------------------
             | ptr+52          ~          ptr+66 | ptr+67
                0x5af43d82803e903d91602b57fd5bf3    0xff
            **********************************************************************************/

            // 将salt写入position ptr+88开始的一个word的内存中([ptr+88, ptr+120])
            mstore(add(ptr, 0x58), salt)
            // keccak256(add(ptr, 0x0c), 0x37):计算[ptr+12, ptr+67]内存中数据的hash值,即计算最小代理合约的creation code的hash
            // 将最小代理合约的creation code hash写入position ptr+120开始的一个word的内存中([ptr+120, ptr+152])
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            // 该时刻[ptr+67, ptr+152]的内存中内容如下:
            /*********************************************************************************
                                               [MEMORY]
            | ptr+67 | ptr+68 ~ ptr+87 | ptr+88 ~ ptr+119 | ptr+120        ~         ptr+151 | 
               0xff      deployer地址          salt值         最小代理合约的creation code hash   
            **********************************************************************************/
            // 计算[ptr+67, ptr+67+85]内存中数据的hash值
            // 将这个256位的hash值转成address(即截取低160为)就是CREATE2将部署出的合约地址
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    function predictDeterministicAddress(address implementation, bytes32 salt)
        internal
        view
        returns (address predicted)
    {
        // deployer为本合约地址,调用predictDeterministicAddress(address,bytes32,address)
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

foundry代码验证:

contract ClonesTest is Test {
    MockClones private _testing = new MockClones();
    Implement private _implement = new Implement();

    function test_PredictDeterministicAddress() external {
        address implementationAddr = address(_implement);
        bytes32 salt = keccak256("salt");
        // test for predictDeterministicAddress(address,bytes32)
        assertEq(
            _testing.predictDeterministicAddress(implementationAddr, salt),
            _testing.cloneDeterministic(implementationAddr, salt)
        );

        // test for predictDeterministicAddress(address,bytes32,address)
        salt = keccak256("other salt");
        assertEq(
            _testing.predictDeterministicAddress(implementationAddr, salt, address(_testing)),
            _testing.cloneDeterministic(implementationAddr, salt)
        );
    }
}

3 最小代理合约的bytecode解析

从Clones库中的的clone()可知,进入opcode CREATE的bytecode参数为:

0x3d602d80600a3d3981f3 + 0x363d3d373d3d3d363d73 + implementation地址 + 0x5af43d82803e903d91602b57fd5bf3

以上bytecode可以等同理解为是最小代理合约的creation code。

部署后的最小代理合约的runtime code为:

0x363d3d373d3d3d363d73 + implementation地址 + 0x5af43d82803e903d91602b57fd5bf3

3.1 最小代理合约的creation code解析

creation code其实就是:

0x3d602d80600a3d3981f3 + runtime code

0x3d602d80600a3d3981f3翻译成操作码及执行后对应stack空间如下:

          OPCODE           |       STACK
[00]    RETURNDATASIZE     | [0]
[01]    PUSH1   2d         | [2d, 0]
[03]    DUP1               | [2d, 2d, 0]
[04]    PUSH1   0a     | [a, 2d, 2d, 0]
[06]    RETURNDATASIZE     | [0, a, 2d, 2d, 0]
[07]    CODECOPY           | [2d, 0]
[08]    DUP2               | [0, 2d, 0]
[09]    RETURN             | []

对应内联汇编代码为:

    assembly{
        // 将creation code从position 10(0xa)开始复制45(0x2d)个字节到内存中
        // 内存存储的起始position为returndatasize()
        codecopy(returndatasize(), 0x0a, 0x2d)
        // 结束执行,返回数据是内存中[returndatasize(): returndatasize()+45]的内容,即最小代理的runtime code
        return (returndatasize(), 0x2d)
    }

综上,creation code多出来的bytecode的逻辑其实就是将runtime code写入内存中,并返回runtime code。return后,evm会更新全局状态,包括新合约的runtime code、地址等,即runtime code上链。

3.2 最小代理合约的runtime code解析

最小代理合约的runtime code为:

0x363d3d373d3d3d363d73 + implementation地址 + 0x5af43d82803e903d91602b57fd5bf3

runtime code翻译成操作码及执行后对应stack空间如下:

注:
    cs:当前call携带的calldata字节长度
    rs1:最近一次的return data字节长度(delegatecall之前)
    rs2:最近一次的return data字节长度(delegatecall之后)
    i_addr: implementation地址
    gas: 目前剩余的可用gas
    res: delegatecall的执行结果(调用成功为1,失败为0)

            OPCODE        |       STACK
[00]    CALLDATASIZE      | [cs]
[01]    RETURNDATASIZE    | [rs1, cs]                       
[02]    RETURNDATASIZE    | [rs1, rs1, cs]  
[03]    CALLDATACOPY      | []
[04]    RETURNDATASIZE    | [rs1]
[05]    RETURNDATASIZE    | [rs1, rs1]
[06]    RETURNDATASIZE    | [rs1, rs1, rs1]
[07]    CALLDATASIZE      | [cs, rs1, rs1, rs1] 
[08]    RETURNDATASIZE    | [rs1, cs, rs1, rs1, rs1] 
[09]    PUSH20  i_addr    | [i_addr, rs1, cs, rs1, rs1, rs1]
[1e]    GAS               | [gas, i_addr, rs1, cs, rs1, rs1, rs1]
[1f]    DELEGATECALL      | [res, rs1]
[20]    RETURNDATASIZE    | [rs2, res, rs1]
[21]    DUP3              | [rs1, rs2, res, rs1]
[22]    DUP1              | [rs1, rs1, rs2, res, rs1]
[23]    RETURNDATACOPY    | [res, rs1]
[24]    SWAP1             | [rs1, res]
[25]    RETURNDATASIZE    | [rs2, rs1, res]
[26]    SWAP2             | [res, rs1, rs2]
[27]    PUSH1   2b        | [2b, res, rs1, rs2]
[29]    JUMPI             | [rs1, rs2]
# 如果res为0,执行REVERT
[2a]    REVERT            | []
# 如果res非0,执行JUMPDEST
[2b]    JUMPDEST      | [rs1, rs2]
[2c]    RETURN            | []

对应内联汇编代码为:

    assembly{
            // 逻辑合约地址
            let i_addr := {硬编码逻辑合约地址}
            // delegatecall之前最近一次的return data字节长度
            let rs1 := returndatasize()
            // 将本次的calldata复制到[rs1, rs1+calldatasize()]的内存中
        calldatacopy(rs1, rs1, calldatasize())
            // delegatecall到逻辑合约。
            // 携带的calldata来自[rs1, rs1+calldatasize()]的内存,返回值存储在[rs1,rs1]的内存中。
        let res := delegatecall(gas(), i_addr, rs1, calldatasize(), rs1, rs1)
            // 获取delegatecall后的return data字节长度
        let rs2 := returndatasize()
            // 将delegatecall的return data复制到[rs1, rs1+rs2]的内存中
        returndatacopy(rs1, rs1, rs2)
            // 判断delegatecall是否成功
        switch res
        // 不成功
        case 0 {
            // revert,携带的msg为delegatecall的return data
            revert(rs1, rs2)
        }
        // 成功
        default {
            // 终止执行,返回delegatecall的return data
            return (rs1, rs2)
        }
     }

3.3 利用Foundry debugger验证最小代理合约被call时的行为

在Foundry debugger中观察当最小代理合约被call时的行为:

$ forge test --debug "test_CallClone"

image-20240626200111123.png

按j键执行opcode CALL,evm的context会立刻切换到最小代理合约内:

image-20240626201000557.png

之后会按照3.2中分析的那样:最小代理合约会delegatecall到它背后的逻辑合约(携带当前call的calldata):

image-20240626201820489.png ps: 本人热爱图灵,热爱中本聪,热爱V神。 以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。 同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下! 如果需要转发,麻烦注明作者。十分感谢!

1.jpeg

公众号名称:后现代泼痞浪漫主义奠基人

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Michael.W
Michael.W
0x93E7...0000
狂热的区块链爱好者