Michael.W基于Foundry精读Openzeppelin第65期——TransparentUpgradeableProxy.sol

  • Michael.W
  • 更新于 2024-07-19 14:00
  • 阅读 687

TransparentUpgradeableProxy库是一个透明代理合约的实现,其背后的逻辑合约可由admin来升级。一般的代理合约本身需要管理函数,当这些函数同其背后的逻辑合约的函数产生selector冲突时可能会暴露潜在的漏洞。透明代理模式解决了以上问题。

0. 版本

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

0.1 TransparentUpgradeableProxy.sol

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

TransparentUpgradeableProxy库是一个透明代理合约的实现,其背后的逻辑合约可由admin来升级。一般的代理合约本身需要管理函数,当这些函数同其背后的逻辑合约的函数产生selector冲突时可能会暴露潜在的漏洞。透明代理模式解决了以上问题,对代理合约的调用遵从:1.非admin的全部调用都会delegatecall到逻辑合约;2.admin只能调用代理合约的管理函数。这意味着admin只能用于触发像升级逻辑合约或改变admin这样的操作(admin无法参与任何逻辑合约的业务),也从机制上杜绝了由selector冲突带来的问题。

建议使用Openzeppelin中ProxyAdmin合约来做admin,通过调用它来实现透明代理合约的管理。

1. 目标合约

继承TransparentUpgradeableProxy合约:

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

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

import "openzeppelin-contracts/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";

interface IMockTransparentUpgradeableProxy {
    event DoIfAdmin(uint);
}

contract MockTransparentUpgradeableProxy is TransparentUpgradeableProxy, IMockTransparentUpgradeableProxy {
    constructor(
        address logic,
        address adminAddress,
        bytes memory data
    )
    TransparentUpgradeableProxy(logic, adminAddress, data)
    {}

    function doIfAdmin(uint arg) external ifAdmin {
        emit DoIfAdmin(arg);
    }

    // has the same selector with function `implementation49979()` in implementation
    // CAUTION: to explain why `ifAdmin` is deprecated
    function proxy71997(uint arg) external ifAdmin {
        emit DoIfAdmin(arg);
    }
}

全部foundry测试合约:

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

寻找参数不同但selector相同的函数签名的脚本:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/transparent/TransparentUpgradeableProxy/TransparentUpgradeableProxy_test.ts

import {ethers} from 'ethers'

// tool to acquire two function signatures with different arguments and same selector
let selectorsA = new Map<string, string>()
let selectorsB = new Map<string, string>()
for (let i = 0; ; i++) {
    const functionSignatureA = `proxy${i}(uint256)`
    const functionSignatureB = `implementation${i}()`
    const selectorA = ethers.keccak256(ethers.toUtf8Bytes(functionSignatureA)).slice(0, 10)
    const selectorB = ethers.keccak256(ethers.toUtf8Bytes(functionSignatureB)).slice(0, 10)
    if (selectorsA.has(selectorB)) {
        console.log(`same selector ${selectorB}: ${selectorsA.get(selectorB)} && ${functionSignatureB}`)
        break
    } else if (selectorsB.has(selectorA)) {
        console.log(`same selector ${selectorA}: ${selectorsB.get(selectorA)} && ${functionSignatureA}`)
        break
    } else {
        selectorsA.set(selectorA, functionSignatureA)
        selectorsB.set(selectorB, functionSignatureB)
    }
}

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/proxy/transparent/TransparentUpgradeableProxy/Implementation.sol

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

interface IImplementation {
    event ChangeStorageUint(uint);
}

contract Implementation is IImplementation {
    // storage
    uint public i;

    function __Implementation_init(uint i_) external {
        i = i_;
    }

    // has the same selector with function `proxy71997(uint)` in proxy
    // NOTE: no one has access to this function
    // CAUTION: to explain why `ifAdmin` is deprecated
    function implementation49979() external {}

    function doIfAdmin(uint arg) external {
        emit ChangeStorageUint(arg);
    }
}

contract ImplementationNew is Implementation {
    // add a function
    function addI(uint i_) external {
        i += i_;
        emit ChangeStorageUint(i);
    }
}

2. 代码精读

2.1 interface ITransparentUpgradeableProxy

透明代理合约在逻辑上向admin暴露了ITransparentUpgradeableProxy的所有方法,但是在代码实现上并未直接实现该接口。所有来自admin的调用会在_fallback()中隐式地路由到对应的管理操作。因此,透明代理合约不会对外暴露任何ABI,保证了代理合约的完全"透明"并从根本上解决了代理合约与逻辑合约之间由selector冲突带来的隐患。

注:强烈不建议在本库上添加任何external函数。如果添加的函数与ITransparentUpgradeableProxy中的函数出现selector冲突将屏蔽掉后者,进而影响透明代理合约的升级。

interface ITransparentUpgradeableProxy is IERC1967 {
    // 返回透明代理合约的当前管理员地址
    function admin() external view returns (address);
    // 返回透明代理合约的当前逻辑合约地址
    function implementation() external view returns (address);
    // 修改透明代理合约的管理员地址
    function changeAdmin(address) external;
    // 升级透明代理合约背后的逻辑合约
    function upgradeTo(address) external;
    // 升级透明代理合约背后的逻辑合约并随后执行一次delegatecall
    function upgradeToAndCall(address, bytes memory) external payable;
}

2.2 constructor(address _logic, address admin_, bytes memory _data) payable

设置_logic为透明代理的逻辑合约地址并以_data为calldata做一次delegatecall进行透明代理合约的初始化。同时,将admin_设置为本透明代理合约的admin。

    constructor(
        address _logic,
        address admin_,
        bytes memory _data
        // 调用ERC1967Proxy的constructor函数
        // 注:ERC1967Proxy的constructor函数详解参见:https://learnblockchain.cn/article/8594
    ) payable ERC1967Proxy(_logic, _data) {
        // 调用ERC1967Upgrade._changeAdmin(),将admin设置为admin_
        // 注:ERC1967Upgrade._changeAdmin()详解参见:https://learnblockchain.cn/article/8581
        _changeAdmin(admin_);
    }

foundry代码验证:

contract TransparentUpgradeableProxyTest is Test {
    Implementation private _implementation = new Implementation();
    MockTransparentUpgradeableProxy private _testing = new MockTransparentUpgradeableProxy(
        address(_implementation),
        address(this),
        abi.encodeCall(_implementation.__Implementation_init, (1024))
    );

    address private _nonAdmin = address(1);

    function test_Constructor() external {
        // check implementation
        ITransparentUpgradeableProxy proxyAsITransparentUpgradeableProxy = ITransparentUpgradeableProxy(address(_testing));
        assertEq(proxyAsITransparentUpgradeableProxy.implementation(), address(_implementation));

        // check admin
        assertEq(proxyAsITransparentUpgradeableProxy.admin(), address(this));

        // check storage
        Implementation proxyAsImplementation = Implementation(address(_testing));
        vm.prank(_nonAdmin);
        assertEq(proxyAsImplementation.i(), 1024);
    }
}

2.3 _fallback() internal

重写Proxy._fallback()函数,为透明代理合约的fallback函数增加路由逻辑。即如果msg.sender是admin就执行对应合约内部的管理函数的调用,否则就执行原本的delegatecall行为。

注:Proxy._fallback()详解参见:https://learnblockchain.cn/article/8469

    function _fallback() internal virtual override {
        if (msg.sender == _getAdmin()) {
            // 如果msg.sender是admin
            // 定义变量ret作为本合约内部逻辑的返回值
            bytes memory ret;
            // 获取本次调用的calldata的前四个字节内容作为selector
            bytes4 selector = msg.sig;
            if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                // 如果call透明代理合约的selector是`upgradeTo(address)`
                // 由于_dispatchUpgradeTo返回"",ret为0x0000000000000000000000000000000000000000000000000000000000000000
                ret = _dispatchUpgradeTo();
            } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                // 如果call透明代理合约的selector是`upgradeToAndCall(address,bytes)`
                // 由于_dispatchUpgradeToAndCall返回"",ret为0x0000000000000000000000000000000000000000000000000000000000000000
                ret = _dispatchUpgradeToAndCall();
            } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                // 如果call透明代理合约的selector是`changeAdmin(address)`
                // 由于_dispatchChangeAdmin返回"",ret为0x0000000000000000000000000000000000000000000000000000000000000000
                ret = _dispatchChangeAdmin();
            } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                // 如果call透明代理合约的selector是`admin()`
                // 执行_dispatchAdmin(),ret为0x0000000000000000000000000000000000000000000000000000000000000020 + admin地址(32字节)
                ret = _dispatchAdmin();
            } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                // 如果call透明代理合约的selector是`implementation()`
                // 执行_dispatchImplementation(),ret为0x0000000000000000000000000000000000000000000000000000000000000020 + 逻辑合约地址(32字节)
                ret = _dispatchImplementation();
            } else {
                // 如果call透明代理合约的selector不属于ITransparentUpgradeableProxy,直接revert
                revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
            }
            assembly {
                // 返回。返回值为内存中[ret+32, ret+32+ret开始第一个字(32字节)的值]的内容。
                // 注:
                // 如果selector是`upgradeTo(address)`&&`upgradeToAndCall(address, bytes)`&&`changeAdmin(address)`,内存中[ret+32, ret+32]为返回值;
                // 如果selector是`admin()`&&`implementation()`,内存中[ret+32, ret+64]为返回值。
                return (add(ret, 0x20), mload(ret))
            }
        } else {
            // 如果msg.sender不是admin,调用Proxy._fallback()进行delegatecall行为
            super._fallback();
        }
    }

    // 返回本代理合约的admin,即admin执行`function admin() external view returns (address)`操作
    function _dispatchAdmin() private returns (bytes memory) {
        // 要求本次的调用不携带eth
        _requireZeroValue();

        // 调用ERC1967Upgrade._getAdmin(),获得当前admin
        // 注:ERC1967Upgrade._getAdmin()详解参见:https://learnblockchain.cn/article/8581
        address admin = _getAdmin();
        // 将admin从address类型编码为bytes memory返回
        // 注:该bytes memory的内部序列为:
        // 0x0000000000000000000000000000000000000000000000000000000000000020 + admin地址(32字节)
        return abi.encode(admin);
    }

    // 返回本代理合约的逻辑合约地址,即admin执行`function implementation() external view returns (address)`操作
    function _dispatchImplementation() private returns (bytes memory) {
        // 要求本次的调用不携带eth
        _requireZeroValue();
        // 调用ERC1967Proxy._implementation(),获得当前代理合约的逻辑合约地址
        // 注:ERC1967Proxy._implementation()详解参见:https://learnblockchain.cn/article/8594
        address implementation = _implementation();
        // 将代理合约地址从address类型编码为bytes memory返回
        // 注:该bytes memory的内部序列为:
        // 0x0000000000000000000000000000000000000000000000000000000000000020 + 逻辑合约地址(32字节)
        return abi.encode(implementation);
    }

    // 修改本代理合约的admin,即admin执行`function changeAdmin(address) external`操作
    function _dispatchChangeAdmin() private returns (bytes memory) {
        // 要求本次的调用不携带eth
        _requireZeroValue();
        // 将calldata中第5到第36字节内容解码为address类型。
        // 即changeAdmin(address)的唯一参数,新admin地址
        address newAdmin = abi.decode(msg.data[4 :], (address));
        // 调用ERC1967Upgrade._changeAdmin(address),将admin修改为newAdmin
        // 注:ERC1967Upgrade._changeAdmin(address)详解参见:https://learnblockchain.cn/article/8581
        _changeAdmin(newAdmin);
        // 返回空bytes
        return "";
    }

    // 升级本代理合约背后的逻辑合约,即admin执行`function upgradeTo(address) external`操作
    function _dispatchUpgradeTo() private returns (bytes memory) {
        // 要求本次的调用不携带eth
        _requireZeroValue();
        // 将calldata中第5到第36字节内容解码为address类型。
        // 即upgradeTo(address)的唯一参数,新逻辑合约地址
        address newImplementation = abi.decode(msg.data[4 :], (address));
        // 调用ERC1967Upgrade._upgradeToAndCall(address,bytes,bool),将背后的逻辑合约地址升级为newImplementation
        // 注:ERC1967Upgrade._upgradeToAndCall(address,bytes,bool)详解参见:https://learnblockchain.cn/article/8581
        _upgradeToAndCall(newImplementation, bytes(""), false);
        // 返回空bytes
        return "";
    }

    // 升级本代理合约背后的逻辑合约并随后执行一次delegatecall,即admin执行`function upgradeToAndCall(address, bytes memory) external payable`操作
    function _dispatchUpgradeToAndCall() private returns (bytes memory) {
        // 将calldata中第5到第36字节内容解码为address类型,作为新逻辑合约地址
        // 将calldata中第37字节及其之后全部内容解码为bytes类型,作为delegatecall的calldata
        // 即解析upgradeToAndCall(address,bytes)的两个参数
        (address newImplementation, bytes memory data) = abi.decode(msg.data[4 :], (address, bytes));
        // 调用ERC1967Upgrade._upgradeToAndCall(address,bytes,bool),将背后的逻辑合约地址升级为newImplementation并以data作为calldata做一个delegatecall
        // 注:ERC1967Upgrade._upgradeToAndCall(address,bytes,bool)详解参见:https://learnblockchain.cn/article/8581
        _upgradeToAndCall(newImplementation, data, true);
        // 返回空bytes
        return "";
    }

    // 用于校验当前call不带value的helper函数。为了保证本代理合约完全透明,所有被ifAmin修饰的函数都必须是payable的(以免逻辑合约中同selector的函数被定义为payable)。
    // 如果不希望被ifAmin修饰的函数是payable的,可以使用本helper函数进行限制。
    function _requireZeroValue() private {
        // 检查当前call不带value,否则revert
        require(msg.value == 0);
    }

foundry代码验证:

contract TransparentUpgradeableProxyTest is Test, IImplementation, IERC1967 {
    Implementation private _implementation = new Implementation();
    ImplementationNew private _implementationNew = new ImplementationNew();
    MockTransparentUpgradeableProxy private _testing = new MockTransparentUpgradeableProxy(
        address(_implementation),
        address(this),
        abi.encodeCall(_implementation.__Implementation_init, (1024))
    );

    address private _nonAdmin = address(1);

    function test_Fallback() external {
        // case 1: admin can only call the functions in ITransparentUpgradeableProxy
        ITransparentUpgradeableProxy proxyAsITransparentUpgradeableProxy = ITransparentUpgradeableProxy(address(_testing));
        // case 1.1: upgradeTo(address)
        vm.expectEmit(address(_testing));
        emit IERC1967.Upgraded(address(_implementationNew));

        proxyAsITransparentUpgradeableProxy.upgradeTo(address(_implementationNew));
        // revert if admin calls with eth value
        uint ethValue = 1 wei;
        vm.expectRevert();
        (bool ok,) = address(_testing).call{value: ethValue}(
            abi.encodeCall(
                proxyAsITransparentUpgradeableProxy.upgradeTo,
                (address(_implementationNew))
            )
        );
        assertTrue(ok);

        // case 1.2: implementation()
        assertEq(proxyAsITransparentUpgradeableProxy.implementation(), address(_implementationNew));
        // revert if admin calls with eth value
        vm.expectRevert();
        (ok,) = address(_testing).call{value: ethValue}(
            abi.encodeCall(
                proxyAsITransparentUpgradeableProxy.implementation,
                ()
            )
        );
        assertTrue(ok);

        // case 1.3: changeAdmin(address)
        address newAdmin = address(1024);
        vm.expectEmit(address(_testing));
        emit IERC1967.AdminChanged(address(this), newAdmin);

        proxyAsITransparentUpgradeableProxy.changeAdmin(newAdmin);
        // revert if admin calls with eth value
        vm.startPrank(newAdmin);
        vm.expectRevert();
        (ok,) = address(_testing).call{value: ethValue}(
            abi.encodeCall(
                proxyAsITransparentUpgradeableProxy.changeAdmin,
                (newAdmin)
            )
        );
        assertTrue(ok);

        // case 1.4: admin()
        assertEq(proxyAsITransparentUpgradeableProxy.admin(), newAdmin);
        // revert if admin calls with eth value
        vm.expectRevert();
        (ok,) = address(_testing).call{value: ethValue}(
            abi.encodeCall(
                proxyAsITransparentUpgradeableProxy.admin,
                ()
            )
        );
        assertTrue(ok);
        vm.stopPrank();

        // case 1.5: upgradeToAndCall(address,bytes)
        // deploy a new proxy with Implementation as implementation
        proxyAsITransparentUpgradeableProxy = ITransparentUpgradeableProxy(address(
            new MockTransparentUpgradeableProxy(
                address(_implementation),
                address(this),
                abi.encodeCall(_implementation.__Implementation_init, (1024))
            )
        ));

        vm.expectEmit(address(proxyAsITransparentUpgradeableProxy));
        emit IERC1967.Upgraded(address(_implementationNew));

        proxyAsITransparentUpgradeableProxy.upgradeToAndCall(
            address(_implementationNew),
            abi.encodeCall(_implementationNew.__Implementation_init, (2048))
        );

        assertEq(proxyAsITransparentUpgradeableProxy.implementation(), address(_implementationNew));
        // check the storage by non-admin call
        vm.prank(_nonAdmin);
        ImplementationNew proxyAsImplementationNew = ImplementationNew(address(proxyAsITransparentUpgradeableProxy));
        assertEq(proxyAsImplementationNew.i(), 2048);

        // case 1.6: revert if admin calls function out of ITransparentUpgradeableProxy
        vm.expectRevert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
        proxyAsImplementationNew.i();

        // case 2: non-admin can't call the function in ITransparentUpgradeableProxy
        vm.startPrank(_nonAdmin);
        // case 2.1: revert to call upgradeTo(address)
        vm.expectRevert();
        proxyAsITransparentUpgradeableProxy.upgradeTo(address(_implementationNew));
        // case 2.2: revert to call implementation()
        vm.expectRevert();
        proxyAsITransparentUpgradeableProxy.implementation();
        // case 2.3: revert to call changeAdmin(address)
        vm.expectRevert();
        proxyAsITransparentUpgradeableProxy.changeAdmin(address(this));
        // case 2.4: revert to call admin()
        vm.expectRevert();
        proxyAsITransparentUpgradeableProxy.admin();
        // case 2.5: revert to call upgradeToAndCall(address,bytes)
        vm.expectRevert();
        proxyAsITransparentUpgradeableProxy.upgradeToAndCall(
            address(_implementationNew),
            abi.encodeCall(_implementationNew.__Implementation_init, (4096))
        );

        // case 3: all non-admin calls will be delegated to the implementation
        // case 3.1: addI(uint) in ImplementationNew
        vm.expectEmit(address(proxyAsImplementationNew));
        emit IImplementation.ChangeStorageUint(2048 + 1);

        proxyAsImplementationNew.addI(1);
        // case 3.2: doIfAdmin(uint) in ImplementationNew
        vm.expectEmit(address(proxyAsImplementationNew));
        emit IImplementation.ChangeStorageUint(1);

        proxyAsImplementationNew.doIfAdmin(1);
    }
}

2.4 modifier ifAdmin()

该修饰器用于修饰代理合约特有的逻辑函数。当调用这些函数时,会根据msg.sender是否是admin进行路由。

注:该修饰器目前已弃用。因为当被修饰的函数A与逻辑合约的函数B的selector相同且传参不同时,会出现无法将函数B的参数传入的问题。

    modifier ifAdmin() {
        if (msg.sender == _getAdmin()) {
            // 如果msg.sender是当前代理合约的admin,则执行被修饰函数逻辑
            _;
        } else {
            // 如果msg.sender不是当前代理合约的admin,则进行delegatecall行为
            _fallback();
        }
    }

foundry代码验证:

contract TransparentUpgradeableProxyTest is Test, IMockTransparentUpgradeableProxy, IImplementation {
    Implementation private _implementation = new Implementation();
    MockTransparentUpgradeableProxy private _testing = new MockTransparentUpgradeableProxy(
        address(_implementation),
        address(this),
        abi.encodeCall(_implementation.__Implementation_init, (1024))
    );

    address private _nonAdmin = address(1);

    function test_IfAdmin() external {
        // case 1: admin call
        uint arg = 1024;
        vm.expectEmit(address(_testing));
        emit IMockTransparentUpgradeableProxy.DoIfAdmin(arg);

        _testing.doIfAdmin(arg);

        // case 2: non-admin call
        vm.expectEmit(address(_testing));
        emit IImplementation.ChangeStorageUint(arg);

        address nonAdmin = address(1);
        vm.prank(nonAdmin);

        _testing.doIfAdmin(arg);

        // case 3: why is IfAdmin deprecated?
        // Functions in proxy and implementation have the same selector but differ in arguments
        // NOTE:
        //      Functions `proxy71997(uint256)`(in proxy) and `implementation49979()`(in implementation) have the same
        //      selector `0x2daa064d` and different arguments

        // case 3.1 admin call
        vm.expectEmit(address(_testing));
        emit IMockTransparentUpgradeableProxy.DoIfAdmin(arg);

        _testing.proxy71997(arg);

        // case 3.2 revert if non-admin call
        Implementation proxyAsImplementation = Implementation(address(_testing));
        vm.prank(nonAdmin);
        vm.expectRevert();

        proxyAsImplementation.implementation49979();
    }
}

2.5 _admin() internal

返回本代理合约的当前admin地址。

    function _admin() internal view virtual returns (address) {
        // 调用ERC1967Upgrade._getAdmin()方法
        // 注:ERC1967Upgrade._getAdmin()详解参见:https://learnblockchain.cn/article/8594
        return _getAdmin();
    }

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

1.jpeg

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

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

0 条评论

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