To begin with, there is an attack event about this article: Tornado.Cash DAO attack. Its attack logic is that:
Using CREATE2 to deploy an contract and returning a address, the rumtimecode will be deployed to EVM. If this contract has a selfdestruct(), it can remove the runtimecode, balance, nonce and so on in this address. As we know, the theory of using CREATE to create a contract is:
1
keccak256(rlp(senderAddress, nonce))[12:31]
Because the senderAddress isn’t change and nonce is reset to zero again, we can deploy different bytecode in the same address.
function getHash()public view returns(bytes32){ return keccak256(_bytecode); } }
contract B{ uint256 public x = 10;
function die() public{ selfdestruct(payable(0)); }
function createC_1() public returns(address){ C_1 c_1 = new C_1(); return address(c_1); }
function createC_2() public returns(address){ C_2 c_2 = new C_2(); return address(c_2); } }
contract C_1{ uint256 public y = 11;
function die() public{ selfdestruct(payable(0)); } }
contract C_2{ uint256 public z = 12;
function die() public{ selfdestruct(payable(0)); } }
Deploy contract A
calculate bytecodehash and deploy the contract B
contract B: call createC_1() to deploy C_1, now we can get y in contract C_1. Attention, contract use CREATE to create a contract: keccak256(rlp(contract B, 0))[12:31], nonce=0. After that, the nonce turns to 1.
contract C_1: call die(), and then we can’t get y. Now there is no code in the contract C_1’s address.
contract B: call die(), now the nonce of contract B is reset to 0 and no code in the contract B’s address.
use the contract A and the same salt to call deploy(), because the salt and senderAddress are the same, deploy() returns the same address of B in step 5.
contract B: call createC_2() to deploy C_2. Because keccak256(rlp(contract B, 0))[12:31] is the same as step 3, so CREATE returns the same address of step 3. Now we make it: deploy the same address with different bytecodes by CREATE, CREATE2 and selfdestruct().
summary
By these seven steps, we understand the advanced technique of CREATE, CREATE2 and selfdestruct(). All in all, the main idea is that:
the same address can be deployed with different bytecode, the code in other words.
an address can arbitrarily add and remove bytecode.