Resources

People often ask me "How did you learn how to hack?" The answer: by reading. This page is a collection of the blog posts and other articles that I have accumulated over the years of my journey. Enjoy!

When the Yul optimizer forgets to forget - 2230

d4r3d3v1lPosted 18 Days Ago
  • Solidity is a smart contract language used primarily on Ethereum-based blockchains. Like any compiler, it has multiple passes in order to optimize the code size, and speed as much as possible. Sometimes, there are issues in these optimization paths that lead to bugs.
  • --via-ir makes the compiler turn Solidity into an intermediate language below the bytecode called Yul. The optimizer rewrites the Solidity to Yul to make it cheaper, before running the normal bytecode optimizing. This flag makes the code much faster in terms of gas.
  • One of these optimizations is reusing local memory reads instead of storage reads. Since storage reads are more expensive, this makes execution cheaper. If a write happens to this storage slot, then a future load needs to read from the storage slot, and NOT the in-memory variable.
  • This book-keeping is kept track of in the KnowledgeBase of the compiler with various other constraints. For instance, k = i + 2. If k is always 2 more than i, they can never be the same slot. If i changes, then the note has to be erased.
  • The bug is a comparison issue in the compiler. At the beginning of a loop, a local in-memory variables value is set to unknown. If a future loop ALSO seats the local in-memory value to unknown, then this becomes a problem: unknown == unknown! So, a note is created (since the value didn't change), even though it's incorrect. I suppose this is why JavaScript has undefined != anything.
  • This bug only happens when two storage, or memory slots computed from the same changing variable turn out to be equal at runtime. So, the normal tests usually pass. The Solidity team ran a scan of verified contracts, and found no vulnerabilities in live contracts. To fix this bug, each change is now versioned.
  • Overall, a good article on an optimization bug. I appreciated how simple the explanation was.