Skip to content

Commit a50bccc

Browse files
committed
Merge pull request bnb-chain#2134 from karalabe/save-state-writes
core/state, trie: don't leak database writes before commit
2 parents fbbedb4 + f3d4ce0 commit a50bccc

4 files changed

Lines changed: 175 additions & 10 deletions

File tree

‎core/state/statedb.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -206,9 +206,6 @@ func (self *StateDB) Delete(addr common.Address) bool {
206206

207207
// Update the given state object and apply it to state trie
208208
func (self *StateDB) UpdateStateObject(stateObject *StateObject) {
209-
if len(stateObject.code) > 0 {
210-
self.db.Put(stateObject.codeHash, stateObject.code)
211-
}
212209
addr := stateObject.Address()
213210
data, err := rlp.EncodeToBytes(stateObject)
214211
if err != nil {
@@ -375,8 +372,15 @@ func (s *StateDB) commit(db trie.DatabaseWriter) (common.Hash, error) {
375372
// and just mark it for deletion in the trie.
376373
s.DeleteStateObject(stateObject)
377374
} else {
375+
// Write any contract code associated with the state object
376+
if len(stateObject.code) > 0 {
377+
if err := db.Put(stateObject.codeHash, stateObject.code); err != nil {
378+
return common.Hash{}, err
379+
}
380+
}
378381
// Write any storage changes in the state object to its trie.
379382
stateObject.Update()
383+
380384
// Commit the trie of the object to the batch.
381385
// This updates the trie root internally, so
382386
// getting the root hash of the storage trie

‎core/state/statedb_test.go‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright 2015 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package state
18+
19+
import (
20+
"math/big"
21+
"testing"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/ethdb"
25+
)
26+
27+
// Tests that updating a state trie does not leak any database writes prior to
28+
// actually committing the state.
29+
func TestUpdateLeaks(t *testing.T) {
30+
// Create an empty state database
31+
db, _ := ethdb.NewMemDatabase()
32+
state, _ := New(common.Hash{}, db)
33+
34+
// Update it with some accounts
35+
for i := byte(0); i < 255; i++ {
36+
obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
37+
obj.AddBalance(big.NewInt(int64(11 * i)))
38+
obj.SetNonce(uint64(42 * i))
39+
if i%2 == 0 {
40+
obj.SetState(common.BytesToHash([]byte{i, i, i}), common.BytesToHash([]byte{i, i, i, i}))
41+
}
42+
if i%3 == 0 {
43+
obj.SetCode([]byte{i, i, i, i, i})
44+
}
45+
state.UpdateStateObject(obj)
46+
}
47+
// Ensure that no data was leaked into the database
48+
for _, key := range db.Keys() {
49+
value, _ := db.Get(key)
50+
t.Errorf("State leaked into database: %x -> %x", key, value)
51+
}
52+
}
53+
54+
// Tests that no intermediate state of an object is stored into the database,
55+
// only the one right before the commit.
56+
func TestIntermediateLeaks(t *testing.T) {
57+
// Create two state databases, one transitioning to the final state, the other final from the beginning
58+
transDb, _ := ethdb.NewMemDatabase()
59+
finalDb, _ := ethdb.NewMemDatabase()
60+
transState, _ := New(common.Hash{}, transDb)
61+
finalState, _ := New(common.Hash{}, finalDb)
62+
63+
// Update the states with some objects
64+
for i := byte(0); i < 255; i++ {
65+
// Create a new state object with some data into the transition database
66+
obj := transState.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
67+
obj.SetBalance(big.NewInt(int64(11 * i)))
68+
obj.SetNonce(uint64(42 * i))
69+
if i%2 == 0 {
70+
obj.SetState(common.BytesToHash([]byte{i, i, i, 0}), common.BytesToHash([]byte{i, i, i, i, 0}))
71+
}
72+
if i%3 == 0 {
73+
obj.SetCode([]byte{i, i, i, i, i, 0})
74+
}
75+
transState.UpdateStateObject(obj)
76+
77+
// Overwrite all the data with new values in the transition database
78+
obj.SetBalance(big.NewInt(int64(11*i + 1)))
79+
obj.SetNonce(uint64(42*i + 1))
80+
if i%2 == 0 {
81+
obj.SetState(common.BytesToHash([]byte{i, i, i, 0}), common.Hash{})
82+
obj.SetState(common.BytesToHash([]byte{i, i, i, 1}), common.BytesToHash([]byte{i, i, i, i, 1}))
83+
}
84+
if i%3 == 0 {
85+
obj.SetCode([]byte{i, i, i, i, i, 1})
86+
}
87+
transState.UpdateStateObject(obj)
88+
89+
// Create the final state object directly in the final database
90+
obj = finalState.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
91+
obj.SetBalance(big.NewInt(int64(11*i + 1)))
92+
obj.SetNonce(uint64(42*i + 1))
93+
if i%2 == 0 {
94+
obj.SetState(common.BytesToHash([]byte{i, i, i, 1}), common.BytesToHash([]byte{i, i, i, i, 1}))
95+
}
96+
if i%3 == 0 {
97+
obj.SetCode([]byte{i, i, i, i, i, 1})
98+
}
99+
finalState.UpdateStateObject(obj)
100+
}
101+
if _, err := transState.Commit(); err != nil {
102+
t.Fatalf("failed to commit transition state: %v", err)
103+
}
104+
if _, err := finalState.Commit(); err != nil {
105+
t.Fatalf("failed to commit final state: %v", err)
106+
}
107+
// Cross check the databases to ensure they are the same
108+
for _, key := range finalDb.Keys() {
109+
if _, err := transDb.Get(key); err != nil {
110+
val, _ := finalDb.Get(key)
111+
t.Errorf("entry missing from the transition database: %x -> %x", key, val)
112+
}
113+
}
114+
for _, key := range transDb.Keys() {
115+
if _, err := finalDb.Get(key); err != nil {
116+
val, _ := transDb.Get(key)
117+
t.Errorf("extra entry in the transition database: %x -> %x", key, val)
118+
}
119+
}
120+
}

‎ethdb/memory_database.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func (b *memBatch) Put(key, value []byte) error {
107107
b.lock.Lock()
108108
defer b.lock.Unlock()
109109

110-
b.writes = append(b.writes, kv{key, common.CopyBytes(value)})
110+
b.writes = append(b.writes, kv{common.CopyBytes(key), common.CopyBytes(value)})
111111
return nil
112112
}
113113

‎trie/secure_trie.go‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,10 @@ var secureKeyPrefix = []byte("secure-key-")
4040
type SecureTrie struct {
4141
*Trie
4242

43-
hash hash.Hash
44-
secKeyBuf []byte
45-
hashKeyBuf []byte
43+
hash hash.Hash
44+
hashKeyBuf []byte
45+
secKeyBuf []byte
46+
secKeyCache map[string][]byte
4647
}
4748

4849
// NewSecure creates a trie with an existing root node from db.
@@ -59,7 +60,10 @@ func NewSecure(root common.Hash, db Database) (*SecureTrie, error) {
5960
if err != nil {
6061
return nil, err
6162
}
62-
return &SecureTrie{Trie: trie}, nil
63+
return &SecureTrie{
64+
Trie: trie,
65+
secKeyCache: make(map[string][]byte),
66+
}, nil
6367
}
6468

6569
// Get returns the value for key stored in the trie.
@@ -105,7 +109,7 @@ func (t *SecureTrie) TryUpdate(key, value []byte) error {
105109
if err != nil {
106110
return err
107111
}
108-
t.Trie.db.Put(t.secKey(hk), key)
112+
t.secKeyCache[string(hk)] = common.CopyBytes(key)
109113
return nil
110114
}
111115

@@ -119,16 +123,53 @@ func (t *SecureTrie) Delete(key []byte) {
119123
// TryDelete removes any existing value for key from the trie.
120124
// If a node was not found in the database, a MissingNodeError is returned.
121125
func (t *SecureTrie) TryDelete(key []byte) error {
122-
return t.Trie.TryDelete(t.hashKey(key))
126+
hk := t.hashKey(key)
127+
delete(t.secKeyCache, string(hk))
128+
return t.Trie.TryDelete(hk)
123129
}
124130

125131
// GetKey returns the sha3 preimage of a hashed key that was
126132
// previously used to store a value.
127133
func (t *SecureTrie) GetKey(shaKey []byte) []byte {
134+
if key, ok := t.secKeyCache[string(shaKey)]; ok {
135+
return key
136+
}
128137
key, _ := t.Trie.db.Get(t.secKey(shaKey))
129138
return key
130139
}
131140

141+
// Commit writes all nodes and the secure hash pre-images to the trie's database.
142+
// Nodes are stored with their sha3 hash as the key.
143+
//
144+
// Committing flushes nodes from memory. Subsequent Get calls will load nodes
145+
// from the database.
146+
func (t *SecureTrie) Commit() (root common.Hash, err error) {
147+
return t.CommitTo(t.db)
148+
}
149+
150+
// CommitTo writes all nodes and the secure hash pre-images to the given database.
151+
// Nodes are stored with their sha3 hash as the key.
152+
//
153+
// Committing flushes nodes from memory. Subsequent Get calls will load nodes from
154+
// the trie's database. Calling code must ensure that the changes made to db are
155+
// written back to the trie's attached database before using the trie.
156+
func (t *SecureTrie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
157+
if len(t.secKeyCache) > 0 {
158+
for hk, key := range t.secKeyCache {
159+
if err := db.Put(t.secKey([]byte(hk)), key); err != nil {
160+
return common.Hash{}, err
161+
}
162+
}
163+
t.secKeyCache = make(map[string][]byte)
164+
}
165+
n, err := t.hashRoot(db)
166+
if err != nil {
167+
return (common.Hash{}), err
168+
}
169+
t.root = n
170+
return common.BytesToHash(n.(hashNode)), nil
171+
}
172+
132173
func (t *SecureTrie) secKey(key []byte) []byte {
133174
t.secKeyBuf = append(t.secKeyBuf[:0], secureKeyPrefix...)
134175
t.secKeyBuf = append(t.secKeyBuf, key...)

0 commit comments

Comments
 (0)