Skip to content

Commit 074efe6

Browse files
holimankaralabe
authored andcommitted
core: fix two snapshot iterator flaws, decollide snap storage prefix
* core/state/snapshot/iterator: fix two disk iterator flaws * core/rawdb: change SnapshotStoragePrefix to avoid prefix collision with preimagePrefix
1 parent fab0ee3 commit 074efe6

5 files changed

Lines changed: 149 additions & 12 deletions

File tree

‎core/blockchain_test.go‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2758,3 +2758,126 @@ func TestDeleteRecreateSlotsAcrossManyBlocks(t *testing.T) {
27582758
}
27592759
}
27602760
}
2761+
2762+
// TestInitThenFailCreateContract tests a pretty notorious case that happened
2763+
// on mainnet over blocks 7338108, 7338110 and 7338115.
2764+
// - Block 7338108: address e771789f5cccac282f23bb7add5690e1f6ca467c is initiated
2765+
// with 0.001 ether (thus created but no code)
2766+
// - Block 7338110: a CREATE2 is attempted. The CREATE2 would deploy code on
2767+
// the same address e771789f5cccac282f23bb7add5690e1f6ca467c. However, the
2768+
// deployment fails due to OOG during initcode execution
2769+
// - Block 7338115: another tx checks the balance of
2770+
// e771789f5cccac282f23bb7add5690e1f6ca467c, and the snapshotter returned it as
2771+
// zero.
2772+
//
2773+
// The problem being that the snapshotter maintains a destructset, and adds items
2774+
// to the destructset in case something is created "onto" an existing item.
2775+
// We need to either roll back the snapDestructs, or not place it into snapDestructs
2776+
// in the first place.
2777+
//
2778+
func TestInitThenFailCreateContract(t *testing.T) {
2779+
var (
2780+
// Generate a canonical chain to act as the main dataset
2781+
engine = ethash.NewFaker()
2782+
db = rawdb.NewMemoryDatabase()
2783+
// A sender who makes transactions, has some funds
2784+
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
2785+
address = crypto.PubkeyToAddress(key.PublicKey)
2786+
funds = big.NewInt(1000000000)
2787+
bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
2788+
)
2789+
2790+
// The bb-code needs to CREATE2 the aa contract. It consists of
2791+
// both initcode and deployment code
2792+
// initcode:
2793+
// 1. If blocknum < 1, error out (e.g invalid opcode)
2794+
// 2. else, return a snippet of code
2795+
initCode := []byte{
2796+
byte(vm.PUSH1), 0x1, // y (2)
2797+
byte(vm.NUMBER), // x (number)
2798+
byte(vm.GT), // x > y?
2799+
byte(vm.PUSH1), byte(0x8),
2800+
byte(vm.JUMPI), // jump to label if number > 2
2801+
byte(0xFE), // illegal opcode
2802+
byte(vm.JUMPDEST),
2803+
byte(vm.PUSH1), 0x2, // size
2804+
byte(vm.PUSH1), 0x0, // offset
2805+
byte(vm.RETURN), // return 2 bytes of zero-code
2806+
}
2807+
if l := len(initCode); l > 32 {
2808+
t.Fatalf("init code is too long for a pushx, need a more elaborate deployer")
2809+
}
2810+
bbCode := []byte{
2811+
// Push initcode onto stack
2812+
byte(vm.PUSH1) + byte(len(initCode)-1)}
2813+
bbCode = append(bbCode, initCode...)
2814+
bbCode = append(bbCode, []byte{
2815+
byte(vm.PUSH1), 0x0, // memory start on stack
2816+
byte(vm.MSTORE),
2817+
byte(vm.PUSH1), 0x00, // salt
2818+
byte(vm.PUSH1), byte(len(initCode)), // size
2819+
byte(vm.PUSH1), byte(32 - len(initCode)), // offset
2820+
byte(vm.PUSH1), 0x00, // endowment
2821+
byte(vm.CREATE2),
2822+
}...)
2823+
2824+
initHash := crypto.Keccak256Hash(initCode)
2825+
aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:])
2826+
t.Logf("Destination address: %x\n", aa)
2827+
2828+
gspec := &Genesis{
2829+
Config: params.TestChainConfig,
2830+
Alloc: GenesisAlloc{
2831+
address: {Balance: funds},
2832+
// The address aa has some funds
2833+
aa: {Balance: big.NewInt(100000)},
2834+
// The contract BB tries to create code onto AA
2835+
bb: {
2836+
Code: bbCode,
2837+
Balance: big.NewInt(1),
2838+
},
2839+
},
2840+
}
2841+
genesis := gspec.MustCommit(db)
2842+
nonce := uint64(0)
2843+
blocks, _ := GenerateChain(params.TestChainConfig, genesis, engine, db, 4, func(i int, b *BlockGen) {
2844+
b.SetCoinbase(common.Address{1})
2845+
// One transaction to BB
2846+
tx, _ := types.SignTx(types.NewTransaction(nonce, bb,
2847+
big.NewInt(0), 100000, big.NewInt(1), nil), types.HomesteadSigner{}, key)
2848+
b.AddTx(tx)
2849+
nonce++
2850+
})
2851+
2852+
// Import the canonical chain
2853+
diskdb := rawdb.NewMemoryDatabase()
2854+
gspec.MustCommit(diskdb)
2855+
chain, err := NewBlockChain(diskdb, nil, params.TestChainConfig, engine, vm.Config{
2856+
//Debug: true,
2857+
//Tracer: vm.NewJSONLogger(nil, os.Stdout),
2858+
}, nil)
2859+
if err != nil {
2860+
t.Fatalf("failed to create tester chain: %v", err)
2861+
}
2862+
statedb, _ := chain.State()
2863+
if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
2864+
t.Fatalf("Genesis err, got %v exp %v", got, exp)
2865+
}
2866+
// First block tries to create, but fails
2867+
{
2868+
block := blocks[0]
2869+
if _, err := chain.InsertChain([]*types.Block{blocks[0]}); err != nil {
2870+
t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
2871+
}
2872+
statedb, _ = chain.State()
2873+
if got, exp := statedb.GetBalance(aa), big.NewInt(100000); got.Cmp(exp) != 0 {
2874+
t.Fatalf("block %d: got %v exp %v", block.NumberU64(), got, exp)
2875+
}
2876+
}
2877+
// Import the rest of the blocks
2878+
for _, block := range blocks[1:] {
2879+
if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
2880+
t.Fatalf("block %d: failed to insert into chain: %v", block.NumberU64(), err)
2881+
}
2882+
}
2883+
}

‎core/rawdb/schema.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ var (
5959
txLookupPrefix = []byte("l") // txLookupPrefix + hash -> transaction/receipt lookup metadata
6060
bloomBitsPrefix = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits
6161
SnapshotAccountPrefix = []byte("a") // SnapshotAccountPrefix + account hash -> account trie value
62-
SnapshotStoragePrefix = []byte("s") // SnapshotStoragePrefix + account hash + storage hash -> storage trie value
62+
SnapshotStoragePrefix = []byte("o") // SnapshotStoragePrefix + account hash + storage hash -> storage trie value
6363

6464
preimagePrefix = []byte("secure-key-") // preimagePrefix + hash -> preimage
6565
configPrefix = []byte("ethereum-config-") // config prefix for the db

‎core/state/journal.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ type (
9090
account *common.Address
9191
}
9292
resetObjectChange struct {
93-
prev *stateObject
93+
prev *stateObject
94+
prevdestruct bool
9495
}
9596
suicideChange struct {
9697
account *common.Address
@@ -142,6 +143,9 @@ func (ch createObjectChange) dirtied() *common.Address {
142143

143144
func (ch resetObjectChange) revert(s *StateDB) {
144145
s.setStateObject(ch.prev)
146+
if !ch.prevdestruct && s.snap != nil {
147+
delete(s.snapDestructs, ch.prev.addrHash)
148+
}
145149
}
146150

147151
func (ch resetObjectChange) dirtied() *common.Address {

‎core/state/snapshot/iterator.go‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,10 @@ type diskAccountIterator struct {
148148

149149
// AccountIterator creates an account iterator over a disk layer.
150150
func (dl *diskLayer) AccountIterator(seek common.Hash) AccountIterator {
151+
// TODO: Fix seek position, or remove seek parameter
151152
return &diskAccountIterator{
152153
layer: dl,
153-
it: dl.diskdb.NewIteratorWithPrefix(append(rawdb.SnapshotAccountPrefix, seek[:]...)),
154+
it: dl.diskdb.NewIteratorWithPrefix(rawdb.SnapshotAccountPrefix),
154155
}
155156
}
156157

@@ -160,11 +161,16 @@ func (it *diskAccountIterator) Next() bool {
160161
if it.it == nil {
161162
return false
162163
}
163-
// Try to advance the iterator and release it if we reahed the end
164-
if !it.it.Next() || !bytes.HasPrefix(it.it.Key(), rawdb.SnapshotAccountPrefix) {
165-
it.it.Release()
166-
it.it = nil
167-
return false
164+
// Try to advance the iterator and release it if we reached the end
165+
for {
166+
if !it.it.Next() || !bytes.HasPrefix(it.it.Key(), rawdb.SnapshotAccountPrefix) {
167+
it.it.Release()
168+
it.it = nil
169+
return false
170+
}
171+
if len(it.it.Key()) == len(rawdb.SnapshotAccountPrefix)+common.HashLength {
172+
break
173+
}
168174
}
169175
return true
170176
}

‎core/state/statedb.go‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -569,12 +569,19 @@ func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
569569
func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
570570
prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
571571

572+
var prevdestruct bool
573+
if s.snap != nil && prev != nil {
574+
_, prevdestruct = s.snapDestructs[prev.addrHash]
575+
if !prevdestruct {
576+
s.snapDestructs[prev.addrHash] = struct{}{}
577+
}
578+
}
572579
newobj = newObject(s, addr, Account{})
573580
newobj.setNonce(0) // sets the object to dirty
574581
if prev == nil {
575582
s.journal.append(createObjectChange{account: &addr})
576583
} else {
577-
s.journal.append(resetObjectChange{prev: prev})
584+
s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
578585
}
579586
s.setStateObject(newobj)
580587
return newobj, prev
@@ -595,9 +602,6 @@ func (s *StateDB) CreateAccount(addr common.Address) {
595602
if prev != nil {
596603
newObj.setBalance(prev.data.Balance)
597604
}
598-
if s.snap != nil && prev != nil {
599-
s.snapDestructs[prev.addrHash] = struct{}{}
600-
}
601605
}
602606

603607
func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {

0 commit comments

Comments
 (0)