← COMP5565 全部讲次
Q04

期中复习题|D 代码推演

英文题干,逐题折叠中文解析、英文参考答案与适用条件。

手机上宽表格可左右滑动;自测答案默认收起,点击题目下方按钮查看。

使用边界:2026-10-13 期中复习,非官方材料;正式范围、题型、时长和开闭卷要求以讲师通知为准。保留课件版本、适用条件与补充标注。

复习资料:密码学、账户与 Gas · 共识、钱包与代币 · Solidity、调用与代理 · DApp 签名与英文作答

先做题再看解析:A 判断题 · B 单选题 · C 计算题 · D 代码推演 · E 简答与 X 选做补练

统一约定:除题目另说,Solidity 为 0.8.30、默认检查算术溢出;账户按普通 EOA 发起交易的课堂模型,不讨论账户代码委托。代码是隔离的教学片段,不是生产合约;假设有足够 gas,且不存在题面未给出的外部操作。金额计算忽略题面之外的费用。页码回查一律使用 PDF 页序。

自查分值仅供练习,不代表教师评分标准;先作答,再展开每题答案。

来源代号:C01 = Lecture crypto foundation.pdf;L01 = Lecture1.pdf;L02 = Lecture2.pdf;L03 = Lecture3.pdf;L04a = Lecture 4.0.pdf;L04b = Lecture 4.1.pdf;L05 = Lecture 5.pdf。页码都是 PDF 页序。来源为对应逐讲注解;标“补充”的部分另列标准文档。所有题干均为自拟。

D · 代码推演

每题 6 分。先画调用帧,分开记录实际 ETH、账面余额与回滚边界。

D1 · Call context through a proxy · 6 marks

Alice is an ordinary EOA. In one transaction, the call chain is:

Alice --CALL, 3 wei--> Router
Router --CALL, 3 wei--> Proxy
Proxy --DELEGATECALL--> Logic

All calls succeed. Router forwards the received 3 wei. Proxy and Logic have compatible storage layouts. While executing Logic’s code through the delegate call:

  1. State msg.sender, tx.origin, address(this), and msg.value. (4)
  2. If the code writes a storage variable, which contract’s storage changes? Does entering Logic by delegatecall transfer the 3 wei to Logic? (2)
D1 · 查看答案与解析

D1 · 始终画清三个调用帧

推理过程:逐层追踪:① Alice CALL Router,Router 看到 sender = Alice。② Router CALL Proxy,Proxy 看到 sender = Router,value = 3 wei。③ Proxy DELEGATECALL Logic,只借用 Logic 的代码,保留第②步的 sender、value,并使用 Proxy 的地址和存储。tx.origin 则一直记录整笔交易最初的发起者 Alice。

在 Logic 代码中读取 结果 为什么
msg.sender Router 保留进入 Proxy 的调用帧 sender
tx.origin Alice 题定普通 EOA 发起整笔交易
address(this) Proxy 当前执行上下文是 Proxy
msg.value 3 wei 保留进入 Proxy 的调用帧 value
写入的 storage Proxy 的 storage Logic 仅提供代码
3 wei 是否转到 Logic 否 delegatecall 本身不向实现合约转这笔 value

English: Delegatecall uses Logic’s code in Proxy’s context. It preserves the calling frame’s sender and value, not necessarily the transaction origin.

前四项各 1 分;后两项各 1 分。反例提醒:若 Alice 直接 CALL Proxy,则这里 msg.sender 才是 Alice;本题中间有 Router。不要用 tx.origin 代替权限设计。回查 L04b p.23-24、p.68-73。

D2 · Reentrancy and the rollback boundary · 6 marks

The following teaching contract is deliberately vulnerable:

contract Bank {
    mapping(address => uint256) public credit;
    function deposit() external payable {
        credit[msg.sender] += msg.value;
    }
    function withdraw() external {
        uint256 n = credit[msg.sender];
        require(n > 0, "empty");
        (bool ok, ) = msg.sender.call{value: n}("");
        require(ok, "payment failed");
        credit[msg.sender] = 0;
    }
}

Bank initially holds 5 ETH deposited earlier by honest users. An attacker contract starts with zero balance and zero recorded credit. Its attack() receives 2 ETH, calls deposit{value: 2 ether}(), then calls withdraw(), all in one transaction. Its receive function calls Bank.withdraw() again whenever Bank’s actual ETH balance is at least 2 ETH. This callback does not catch failures. Assume sufficient gas and no other interactions.

  1. Give the successive Bank balances after transfers, the total received by the attacker contract, and its net gain excluding gas. (2)
  2. Explain why require(n > 0) does not stop this trace. (1)
  3. Move credit[msg.sender] = 0 to just before the external call. Starting again from the same initial conditions, does this attack() succeed? Give Bank’s final balance and the attacker’s recorded credit, including whether the deposit in this transaction survives. (3)
D2 · 查看答案与解析

D2 · 池中剩 1 ETH,不是所有重入都会清空

推理过程:先画执行的嵌套顺序:外层 withdraw 在付款处暂停 → 接收方回调 → 内层 withdraw → 最内层先结束 → 逐层返回。再分别记录实际 ETH 与 credit(账面可提款额)。付款确实减少 Bank 的 ETH;清零语句却还没执行,因此嵌套检查仍看到旧 credit。最终能否获利,还要看这些帧能否全部成功返回。

原版本:5 ETH 旧存款 + 2 ETH 本次存入,Bank 起点为 7 ETH。credit[attacker] 为 2 ETH。

转账次数 本次转出 转出后 Bank 回调动作
1 2 ETH 5 ETH 5 ≥ 2,再次 withdraw
2 2 ETH 3 ETH 3 ≥ 2,再次 withdraw
3 2 ETH 1 ETH 1 < 2,停止重入

随后三个 withdraw 帧依次清零账面余额。攻击合约累计收到 6 ETH,净获利 4 ETH(扣除自己的 2 ETH,不计 gas);Bank 剩 1 ETH。表与总额正确共 2 分。

require(n > 0) 每次读到的还是尚未清零的 2 ETH;外部控制权在更新前交出,所以检查不能防止这个重入过程。(1 分)

CEI 修改版:首次提款先清零;回调尝试第二次提款时读到 0,require 失败。题设回调不捕获失败,导致首次付款的 ok 为 false;Bank 的 require(ok) 继续把错误传回 attack()。整笔 attack 交易回滚,包含同一交易内刚做的 deposit。

最终 Bank = 5 ETH,credit[attacker] = 0,攻击合约余额恢复为 0。外层发送者的 2 ETH 转入也回滚,但仍支付已消耗 gas。更早的诚实存款属于已完成的交易,不受这次回滚影响。(失败传播、deposit 回滚、最终状态各 1 分)

English: In the vulnerable version, stale credit permits three withdrawals. With effects before interactions, the uncaught callback failure propagates and reverts the entire attack transaction, including its deposit.

条件变化:如果攻击合约捕获内层失败、不再让接收过程失败,合法的第一次提款可能成功;不能把“CEI”背成“任何提款都回滚”。回查 L04b p.66、p.74 后重入补充。

D3 · A caught low-level failure · 6 marks

These contracts are freshly deployed. Each experiment starts from that fresh state. t refers to the displayed Target contract; no ETH is attached.

contract Target {
    uint256 public y;
    function fail() external {
        y = 9;
        revert("no");
    }
}
contract Caller {
    uint256 public x;
    function run(address t) external returns (bool ok) {
        x = 1;
        (ok, ) = t.call(abi.encodeWithSignature("fail()"));
        x = 2;
    }
}
  1. In the shown version, what does run return and what are the final values of x and y? Does the outer transaction succeed? (3)
  2. Insert require(ok, "propagate"); immediately before x = 2. Repeat from fresh state. Give the outer transaction status and final x and y. (2)
  3. If the outer transaction fails after execution, does that imply its gas fee is zero? (1)
D3 · 查看答案与解析

D3 · 被调帧失败不自动等于顶层失败

推理过程:初始 x = y = 0。① Caller 把 x 写成 1。② Target 把 y 写成 9,随后 revert,所以 y 恢复 0。③ 低级 call 把失败交给 Caller,ok = false;它不会自动强迫 Caller 回滚。④ 原版继续写 x = 2;加 require(ok) 的版本则在此报错,x = 2 根本不会执行,之前的 x = 1 也撤销。

版本 ok / 返回 外层交易 最终 x 最终 y
原版,无 require(ok) 返回 false 成功 2 0
插入 require(ok) 回滚,无成功返回值 失败 0 0

Target 里的 y = 9 被其 REVERT 撤销;原版 Caller 收到 false 后继续执行。插入 require 后,Caller 的 x = 1 也被回滚,因为失败传播到外层。即使外层交易失败,gas 也不是免费。

English: A low-level call reports failure to its caller. The caller may handle it and continue, or propagate it by reverting.

自查分值:原版 false、x = 2、y = 0 且外层成功共 3;传播版状态与值共 2;消耗 gas 收费 1。回查 L04b p.55-59、p.67-73。

D4 · Receive, fallback and checked arithmetic · 6 marks

Experiments (1), (2), and (3) use separately deployed instances. A low-level caller supplies enough gas and checks the returned success flag.

contract Inbox {
    uint256 public flag;
    receive() external payable { flag = 1; }
    fallback() external payable { flag = 2; }
    function bump(uint8 x) external pure returns (uint8) {
        return x + 1;
    }
}
  1. Send 1 wei with empty calldata. Which function runs, and what is flag? (2)
  2. Send 1 wei with calldata 0xdeadbeef, stipulated not to match a selector. Which function runs, and what is flag? (2)
  3. Call bump(255). Does it return 0 or fail? What if only the addition is placed inside unchecked? (2)
D4 · 查看答案与解析

D4 · 分派依据是 calldata,不是有没有 ETH

推理过程:入口选择先检查 calldata(调用数据):为空则有 receive 就进入 receive;非空则先匹配函数选择器,找不到才进入 fallback。是否带 ETH 决定入口还需不需要 payable,不替代前面的分派规则。算术题另算:uint8 可表示 0 至 255,255 + 1 超出范围;checked arithmetic(带检查的算术)失败,unchecked 才按模 256 回绕。

  1. 空 calldata,有 receive:运行 receive,flag = 1。(2 分)
  2. 非空且 selector 不匹配:运行 fallback;本题它 payable,所以接受 1 wei,flag = 2。(2 分)
  3. 0.8.30 默认检查 uint8 溢出,bump(255) 失败/回滚,不正常返回 0;将加法放入 unchecked 后按模 256 回绕,返回 0。(2 分)

English: Empty calldata selects receive when it exists; an unmatched selector selects fallback. Checked uint8 overflow reverts, whereas unchecked addition wraps.

题目明确给足 gas,不能额外引入 transfer 的 2300 gas 限额。flag = 1 的存储写入在 gas 不足的另一个场景可能失败,但不是本题条件。回查 L04b p.7、p.29-31;补充 Solidity contracts 与 control structures。

作答后怎么复盘

先记录错题号,再分成 概念 / 英文限定词 / 算术与单位 / 调用帧与状态 / 版本与条件 五类。展开对应题目的解析看错因,遮住答案后换一组数字或条件再答一次。不要只背 T/F 和选项字母。

下一页 →
Q05 期中复习题|E 简答与 X 选做补练

个人整理的学习笔记,不是官方材料;数字与结论以课件和讲师为准。