M09-L01 · Smart Contract Security

M09 — Reentrancy and Checks-Effects-Interactions

M09 — Reentrancy and Checks-Effects-Interactions

1. Bài toán

Xây smart contract xử lý tài sản trước rủi ro reentrancy and checks-effects-interactions.

2. Vấn đề

Các giao dịch công khai, external calls, quyền admin và state không nhất quán có thể dẫn tới mất tài sản.

3. Giải pháp

Thiết kế defense-in-depth: điều kiện trước, cập nhật state, hạn chế quyền, kiểm thử negative paths và invariants.

4. Lý thuyết

Đọc solution/src/SafeVault.sol, nhận diện trust boundary, state variables, call graph, revert semantics. Phân biệt mô hình giáo dục và triển khai production.

5. Lab chi tiết

  1. Cài Foundry và chạy forge --version.
  2. Mở starter/README.md và tự viết defensive contract.
  3. So sánh solution/src/SafeVault.sol.
  4. cd solution && forge test -vvv.
  5. Thêm test cho caller không có quyền, giá trị biên, repeated transaction và invariant.
  6. Ghi lại trace, lý do revert và threat model.

6. Expected output

[PASS] testScenario() và exit code 0 khi Foundry tests thành công. Đây là output mong đợi, chưa xác minh bằng forge tại môi trường tạo ZIP.

7. Exercises

8. Interview

  1. Tại sao bug này tồn tại?
  2. Trust boundary nằm ở đâu?
  3. Test nào phát hiện regression?
  4. Vì sao chỉ kiểm tra require là chưa đủ?
  5. Cơ chế phòng thủ có trade-off gì?