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
- Cài Foundry và chạy
forge --version. - Mở
starter/README.mdvà tự viết defensive contract. - So sánh
solution/src/SafeVault.sol. cd solution && forge test -vvv.- Thêm test cho caller không có quyền, giá trị biên, repeated transaction và invariant.
- 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
- Viết ít nhất 3 negative tests và một fuzz/property test.
- Viết bảng threat → exploit precondition → mitigation → regression test.
- Nêu giới hạn của solution và cách dùng OpenZeppelin, audit, multisig khi production.
8. Interview
- Tại sao bug này tồn tại?
- Trust boundary nằm ở đâu?
- Test nào phát hiện regression?
- Vì sao chỉ kiểm tra require là chưa đủ?
- Cơ chế phòng thủ có trade-off gì?