---
# System prepended metadata

title: 'Guide to Learning: Practical Smart Contract Security'

---

![F83eisQWEAAaIfN](https://hackmd.io/_uploads/HysEAUQ2kl.jpg)


# Guide to Learning: Practical Smart Contract Security

## Quiz (short answers)

1. Explain the difference between security from a user's perspective and security from a developer's perspective in the context of smart contracts. Provide an example for each perspective.

2. Describe the evolution of the ERC-721 standard, paying particular attention to the motivations for introducing the safeTransferFrom function.

3. Why are external calls to unknown contracts considered potentially dangerous? Explain this in relation to the concept of control flow takeover.

4. In the context of the ENS Name Wrapper example, how did the safe mint function contribute to the creation of a security vulnerability?

5. Using the Hashmasks NFT example, describe how the attacker exploited reentrancy through the safe minting function to violate the supply cap.

6. What two general strategies can be applied when analyzing the security of an existing, complex smart contract to effectively narrow the search space for potential vulnerabilities?

7. Explain the main vulnerability in the Ambisafe contract that allowed the generation of fake transfer events.

8. Describe how the attacker in the Atomic Loans project exploited the specifics of Bitcoin transactions (zero-confirmation transactions) to bypass the collateral locking requirement.

9. In the context of the Lean Finance attack, explain how the ability to register a bond group with an empty list of bond IDs led to the possibility of unlimited ether withdrawals from the contract.

10. What two key aspects, besides finding the vulnerability itself, are important when responding to a serious security vulnerability in a decentralized protocol, using the example of rescuing funds from Lean Finance?

## Quiz Answer Key

1. From a user's perspective, security can mean protection from their own mistakes, for example preventing tokens from being sent to a zero address. From a developer's perspective, security concerns protection against malicious actions, such as attempts to steal tokens by hackers.

2. Initially, ERC-721 had approve and takeOwnership functions. These were changed to transfer and approve, and later transfer was split into transfer and transferFrom. The safeTransferFrom functions were introduced to prevent the loss of NFTs by sending them to contracts that do not implement the NFT receiving interface.

3. During an external call to an unknown contract, the caller loses control over the execution flow. A malicious contract can modify the global state of Ethereum in an unexpected way during this time, for example by performing a reentrancy attack on the original contract.

4. In the ENS Name Wrapper, the wrap function minted a token representing the ENS domain before verifying whether the user actually owned that domain. The safe minting function (safeMint) called a callback on the recipient after minting, giving the attacker the opportunity to use the newly acquired token for unauthorized domain takeover.

5. In Hashmasks NFT, the safe minting function (safeMint) performed an external call to the token recipient after minting a single NFT. The attacker used this call to reenter and call the function to mint additional NFTs before the original minting call completed, thus bypassing the supply limitation.

6. Two strategies are: working forward from places where user input is processed to see how data can be manipulated to cause unexpected behavior, and working backward from places where "bad" events (e.g., ether transfers) can occur to find ways to trigger them using crafted input data.

7. The main vulnerability in Ambisafe was that the transfer function called the proxyTransferEvent function, which emitted a transfer event by making a call to the address stored in the proxiesAtSymbol variable. By exploiting an unchecked external call in the checkSign modifier, the attacker could temporarily replace the address in proxiesAtSymbol with the victim's address and emit a fake transfer event.

8. The attacker in Atomic Loans exploited the fact that the Bitcoin RPC getBalance function returned the balance of transactions with zero confirmations. They sent a small amount of BTC, waited for one confirmation, and then sent a large BTC transaction (with zero confirmations). The Atomic Loans system incorrectly recognized that the collateral was fully locked and approved the loan, after which the attacker could replace the unconfirmed transaction with another one, sending the funds to themselves.

9. In Lean Finance, the registerNewBondGroup function allowed registering a new bond group with an empty bondIds array. The exchangeBondGroup function then allowed "exchanging" this empty bond group for another, which effectively allowed calling the ether withdrawal function (transferEthToSender) without actually burning any bond tokens.

10. Two key aspects are: verifying the identity of the people you are communicating with (to avoid disclosing attack details to unauthorized persons) and considering potential legal and tax obligations associated with temporarily taking control of a significant amount of funds during a rescue attempt.

## Suggested Essay Questions

1. Thoroughly analyze the concept of "safe transfers" in token standards (such as ERC-721 and ERC-1155). Present both their intended benefits for user security and potential drawbacks and risks they may introduce from a developer's security perspective. Illustrate your arguments with specific examples from the lectures discussed.

2. The lecture presents several examples of security vulnerabilities that existed in contracts for an extended period before being discovered. Discuss the factors that contribute to this phenomenon in the smart contract ecosystem. What strategies and tools can help increase the likelihood of earlier detection of such hidden vulnerabilities?

3. Chaining multiple seemingly harmless vulnerabilities into one highly damaging exploit (exploit chaining) is an advanced attack technique. Using the example of the Pickle Finance attack, explain in detail how three separate low or medium severity vulnerabilities were combined to lead to a significant loss of funds. What conclusions about smart contract design and auditing can be drawn from this case?

4. Optimizing code for gas costs is an important aspect of creating smart contracts. However, the lecture warns against careless application of optimizations, especially through direct manipulation of EVM assembly. Using the examples of 0x Exchange and ENS Registry, discuss how optimization attempts led to serious security vulnerabilities. What general principles should be followed to optimize code in a responsible and secure manner?

5. Interactions between different blockchains introduce an additional layer of complexity and potential risks in designing decentralized applications. Using the example of Atomic Loans, analyze the security challenges in cross-chain systems. What unique vulnerabilities can emerge in such architectures and what strategies can be applied to minimize them?

## Glossary of Key Terms

- **ERC-20**: Interface standard for fungible tokens on the Ethereum blockchain.
- **ERC-721**: Interface standard for non-fungible tokens (NFTs) on the Ethereum blockchain. Each token is unique.
- **ERC-1155**: Token interface standard on the Ethereum blockchain that enables the creation of both fungible and non-fungible tokens in a single contract.
- **Smart Contract**: Self-executing contract with the terms of the agreement directly written into code. It operates on a blockchain.
- **Safe Transfer**: A function in token standards (e.g., safeTransferFrom in ERC-721 and ERC-1155) that additionally checks whether the token recipient is able to handle it, to prevent token loss.
- **External Call**: Calling a function of another smart contract or external account (EOA) from the current contract.
- **Reentrancy**: A type of security vulnerability in which a malicious contract calls back into a function of the calling contract before the original call completes, potentially violating its logic and state.
- **Control Flow**: The order in which instructions in a program are executed. During an external call, control flow temporarily passes to the called contract.
- **Supply Cap**: The maximum number of tokens that can be issued by a given token contract.
- **Tokenized Deposits**: Representing deposited assets (e.g., DAI deposited on Compound as cDAI) as standard ERC-20 tokens that can be transferred.
- **Delegatecall**: Low-level EVM opcode that allows executing code from another contract in the context (storage, balance, msg.sender) of the current contract.
- **P2SH (Pay to Script Hash)**: A type of Bitcoin address where the conditions for spending funds are defined by a script hash, not just a public key.
- **Zero-Confirmation Transaction**: A transaction that has been sent to the Bitcoin network but has not yet been included in a confirmed block.
- **Replace-by-fee (RBF)**: A feature in Bitcoin that allows the sender to replace an unpaid transaction with another transaction with a higher transaction fee (gas price), if it uses the same nonce.
- **Mempool**: The pool of pending, unconfirmed transactions in a blockchain network.
- **Front-running**: The practice of observing pending transactions in the mempool and sending your own transaction before it (with a higher gas fee) to take advantage of the upcoming transaction.
- **Private Relay**: A service that allows transactions to be sent directly to miners, bypassing the public mempool and reducing the risk of front-running.

## Source / Berkeley RDI Center on Decentralization & AI
[![DeFi Lecture 12: Practical Smart Contract Security](https://img.youtube.com/vi/pJKy5HWuFK8/0.jpg)](https://youtu.be/pJKy5HWuFK8?si=7isyvauWjq4B7Yoo)