Skip to content

Commit 49ae538

Browse files
committed
Merge pull request bnb-chain#1405 from fjl/lean-trie
core, trie: new trie
2 parents 581c090 + c1a352c commit 49ae538

30 files changed

Lines changed: 1515 additions & 1059 deletions

‎build/update-license.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,10 @@ var (
4646
skipPrefixes = []string{
4747
// boring stuff
4848
"Godeps/", "tests/files/", "build/",
49-
// don't relicense vendored packages
49+
// don't relicense vendored sources
5050
"crypto/sha3/", "crypto/ecies/", "logger/glog/",
5151
"crypto/curve.go",
52+
"trie/arc.go",
5253
}
5354

5455
// paths with this prefix are licensed as GPL. all other files are LGPL.

‎core/block_processor.go‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,8 @@ func (self *BlockProcessor) ApplyTransaction(gp GasPool, statedb *state.StateDB,
100100
}
101101

102102
// Update the state with pending changes
103-
statedb.SyncIntermediate()
104-
105103
usedGas.Add(usedGas, gas)
106-
receipt := types.NewReceipt(statedb.Root().Bytes(), usedGas)
104+
receipt := types.NewReceipt(statedb.IntermediateRoot().Bytes(), usedGas)
107105
receipt.TxHash = tx.Hash()
108106
receipt.GasUsed = new(big.Int).Set(gas)
109107
if MessageCreatesContract(tx) {
@@ -265,16 +263,16 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs st
265263
// Accumulate static rewards; block reward, uncle's and uncle inclusion.
266264
AccumulateRewards(state, header, uncles)
267265

268-
// Commit state objects/accounts to a temporary trie (does not save)
269-
// used to calculate the state root.
270-
state.SyncObjects()
271-
if header.Root != state.Root() {
272-
err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
273-
return
266+
// Commit state objects/accounts to a database batch and calculate
267+
// the state root. The database is not modified if the root
268+
// doesn't match.
269+
root, batch := state.CommitBatch()
270+
if header.Root != root {
271+
return nil, nil, fmt.Errorf("invalid merkle root: header=%x computed=%x", header.Root, root)
274272
}
275273

276-
// Sync the current block's state to the database
277-
state.Sync()
274+
// Execute the database writes.
275+
batch.Write()
278276

279277
return state.Logs(), receipts, nil
280278
}

‎core/chain_makers.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package core
1818

1919
import (
20+
"fmt"
2021
"math/big"
2122

2223
"github.com/ethereum/go-ethereum/common"
@@ -94,9 +95,9 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
9495
if err != nil {
9596
panic(err)
9697
}
97-
b.statedb.SyncIntermediate()
98+
root := b.statedb.IntermediateRoot()
9899
b.header.GasUsed.Add(b.header.GasUsed, gas)
99-
receipt := types.NewReceipt(b.statedb.Root().Bytes(), b.header.GasUsed)
100+
receipt := types.NewReceipt(root.Bytes(), b.header.GasUsed)
100101
logs := b.statedb.GetLogs(tx.Hash())
101102
receipt.SetLogs(logs)
102103
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
@@ -163,8 +164,11 @@ func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int,
163164
gen(i, b)
164165
}
165166
AccumulateRewards(statedb, h, b.uncles)
166-
statedb.SyncIntermediate()
167-
h.Root = statedb.Root()
167+
root, err := statedb.Commit()
168+
if err != nil {
169+
panic(fmt.Sprintf("state write error: %v", err))
170+
}
171+
h.Root = root
168172
return types.NewBlock(h, b.txs, b.uncles, b.receipts)
169173
}
170174
for i := 0; i < n; i++ {
@@ -184,7 +188,7 @@ func makeHeader(parent *types.Block, state *state.StateDB) *types.Header {
184188
time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
185189
}
186190
return &types.Header{
187-
Root: state.Root(),
191+
Root: state.IntermediateRoot(),
188192
ParentHash: parent.Hash(),
189193
Coinbase: parent.Coinbase(),
190194
Difficulty: CalcDifficulty(time.Uint64(), new(big.Int).Sub(time, big.NewInt(10)).Uint64(), parent.Number(), parent.Difficulty()),

‎core/chain_manager.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -840,8 +840,8 @@ out:
840840
}
841841

842842
func blockErr(block *types.Block, err error) {
843-
h := block.Header()
844-
glog.V(logger.Error).Infof("Bad block #%v (%x)\n", h.Number, h.Hash().Bytes())
845-
glog.V(logger.Error).Infoln(err)
846-
glog.V(logger.Debug).Infoln(verifyNonces)
843+
if glog.V(logger.Error) {
844+
glog.Errorf("Bad block #%v (%s)\n", block.Number(), block.Hash().Hex())
845+
glog.Errorf(" %v", err)
846+
}
847847
}

‎core/genesis.go‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
6969
statedb.SetState(address, common.HexToHash(key), common.HexToHash(value))
7070
}
7171
}
72-
statedb.SyncObjects()
72+
root, stateBatch := statedb.CommitBatch()
7373

7474
difficulty := common.String2Big(genesis.Difficulty)
7575
block := types.NewBlock(&types.Header{
@@ -81,7 +81,7 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
8181
Difficulty: difficulty,
8282
MixDigest: common.HexToHash(genesis.Mixhash),
8383
Coinbase: common.HexToAddress(genesis.Coinbase),
84-
Root: statedb.Root(),
84+
Root: root,
8585
}, nil, nil, nil)
8686

8787
if block := GetBlock(chainDb, block.Hash()); block != nil {
@@ -92,8 +92,10 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
9292
}
9393
return block, nil
9494
}
95-
statedb.Sync()
9695

96+
if err := stateBatch.Write(); err != nil {
97+
return nil, fmt.Errorf("cannot write state: %v", err)
98+
}
9799
if err := WriteTd(chainDb, block.Hash(), difficulty); err != nil {
98100
return nil, err
99101
}
@@ -115,12 +117,14 @@ func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big
115117
statedb := state.New(common.Hash{}, db)
116118
obj := statedb.GetOrNewStateObject(addr)
117119
obj.SetBalance(balance)
118-
statedb.SyncObjects()
119-
statedb.Sync()
120+
root, err := statedb.Commit()
121+
if err != nil {
122+
panic(fmt.Sprintf("cannot write state: %v", err))
123+
}
120124
block := types.NewBlock(&types.Header{
121125
Difficulty: params.GenesisDifficulty,
122126
GasLimit: params.GenesisGasLimit,
123-
Root: statedb.Root(),
127+
Root: root,
124128
}, nil, nil, nil)
125129
return block
126130
}

‎core/state/state_object.go‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,13 @@ type StateObject struct {
9090

9191
func NewStateObject(address common.Address, db ethdb.Database) *StateObject {
9292
object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true}
93-
object.trie = trie.NewSecure((common.Hash{}).Bytes(), db)
93+
object.trie, _ = trie.NewSecure(common.Hash{}, db)
9494
object.storage = make(Storage)
9595
object.gasPool = new(big.Int)
96-
9796
return object
9897
}
9998

10099
func NewStateObjectFromBytes(address common.Address, data []byte, db ethdb.Database) *StateObject {
101-
// TODO clean me up
102100
var extobject struct {
103101
Nonce uint64
104102
Balance *big.Int
@@ -107,19 +105,24 @@ func NewStateObjectFromBytes(address common.Address, data []byte, db ethdb.Datab
107105
}
108106
err := rlp.Decode(bytes.NewReader(data), &extobject)
109107
if err != nil {
110-
fmt.Println(err)
108+
glog.Errorf("can't decode state object %x: %v", address, err)
109+
return nil
110+
}
111+
trie, err := trie.NewSecure(extobject.Root, db)
112+
if err != nil {
113+
// TODO: bubble this up or panic
114+
glog.Errorf("can't create account trie with root %x: %v", extobject.Root[:], err)
111115
return nil
112116
}
113117

114118
object := &StateObject{address: address, db: db}
115119
object.nonce = extobject.Nonce
116120
object.balance = extobject.Balance
117121
object.codeHash = extobject.CodeHash
118-
object.trie = trie.NewSecure(extobject.Root[:], db)
122+
object.trie = trie
119123
object.storage = make(map[string]common.Hash)
120124
object.gasPool = new(big.Int)
121125
object.code, _ = db.Get(extobject.CodeHash)
122-
123126
return object
124127
}
125128

@@ -215,6 +218,7 @@ func (c *StateObject) ReturnGas(gas, price *big.Int) {}
215218

216219
func (self *StateObject) SetGasLimit(gasLimit *big.Int) {
217220
self.gasPool = new(big.Int).Set(gasLimit)
221+
self.dirty = true
218222

219223
if glog.V(logger.Core) {
220224
glog.Infof("%x: gas (+ %v)", self.Address(), self.gasPool)
@@ -225,19 +229,14 @@ func (self *StateObject) SubGas(gas, price *big.Int) error {
225229
if self.gasPool.Cmp(gas) < 0 {
226230
return GasLimitError(self.gasPool, gas)
227231
}
228-
229232
self.gasPool.Sub(self.gasPool, gas)
230-
231-
rGas := new(big.Int).Set(gas)
232-
rGas.Mul(rGas, price)
233-
234233
self.dirty = true
235-
236234
return nil
237235
}
238236

239237
func (self *StateObject) AddGas(gas, price *big.Int) {
240238
self.gasPool.Add(self.gasPool, gas)
239+
self.dirty = true
241240
}
242241

243242
func (self *StateObject) Copy() *StateObject {

‎core/state/state_test.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,7 @@ func TestNull(t *testing.T) {
8989
//value := common.FromHex("0x823140710bf13990e4500136726d8b55")
9090
var value common.Hash
9191
state.SetState(address, common.Hash{}, value)
92-
state.SyncIntermediate()
93-
state.Sync()
92+
state.Commit()
9493
value = state.GetState(address, common.Hash{})
9594
if !common.EmptyHash(value) {
9695
t.Errorf("expected empty hash. got %x", value)

‎core/state/statedb.go‎

Lines changed: 56 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ import (
3535
type StateDB struct {
3636
db ethdb.Database
3737
trie *trie.SecureTrie
38-
root common.Hash
3938

4039
stateObjects map[string]*StateObject
4140

@@ -49,12 +48,19 @@ type StateDB struct {
4948

5049
// Create a new state from a given trie
5150
func New(root common.Hash, db ethdb.Database) *StateDB {
52-
trie := trie.NewSecure(root[:], db)
53-
return &StateDB{root: root, db: db, trie: trie, stateObjects: make(map[string]*StateObject), refund: new(big.Int), logs: make(map[common.Hash]Logs)}
54-
}
55-
56-
func (self *StateDB) PrintRoot() {
57-
self.trie.Trie.PrintRoot()
51+
tr, err := trie.NewSecure(root, db)
52+
if err != nil {
53+
// TODO: bubble this up
54+
tr, _ = trie.NewSecure(common.Hash{}, db)
55+
glog.Errorf("can't create state trie with root %x: %v", root[:], err)
56+
}
57+
return &StateDB{
58+
db: db,
59+
trie: tr,
60+
stateObjects: make(map[string]*StateObject),
61+
refund: new(big.Int),
62+
logs: make(map[common.Hash]Logs),
63+
}
5864
}
5965

6066
func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) {
@@ -196,7 +202,6 @@ func (self *StateDB) UpdateStateObject(stateObject *StateObject) {
196202
if len(stateObject.CodeHash()) > 0 {
197203
self.db.Put(stateObject.CodeHash(), stateObject.code)
198204
}
199-
200205
addr := stateObject.Address()
201206
self.trie.Update(addr[:], stateObject.RlpEncode())
202207
}
@@ -207,6 +212,7 @@ func (self *StateDB) DeleteStateObject(stateObject *StateObject) {
207212

208213
addr := stateObject.Address()
209214
self.trie.Delete(addr[:])
215+
//delete(self.stateObjects, addr.Str())
210216
}
211217

212218
// Retrieve a state object given my the address. Nil if not found
@@ -303,65 +309,67 @@ func (self *StateDB) Set(state *StateDB) {
303309
self.logSize = state.logSize
304310
}
305311

306-
func (s *StateDB) Root() common.Hash {
307-
return common.BytesToHash(s.trie.Root())
308-
}
309-
310-
// Syncs the trie and all siblings
311-
func (s *StateDB) Sync() {
312-
// Sync all nested states
312+
// IntermediateRoot computes the current root hash of the state trie.
313+
// It is called in between transactions to get the root hash that
314+
// goes into transaction receipts.
315+
func (s *StateDB) IntermediateRoot() common.Hash {
316+
s.refund = new(big.Int)
313317
for _, stateObject := range s.stateObjects {
314-
stateObject.trie.Commit()
315-
}
316-
317-
s.trie.Commit()
318-
319-
s.Empty()
320-
}
321-
322-
func (self *StateDB) Empty() {
323-
self.stateObjects = make(map[string]*StateObject)
324-
self.refund = new(big.Int)
325-
}
326-
327-
func (self *StateDB) Refunds() *big.Int {
328-
return self.refund
329-
}
330-
331-
// SyncIntermediate updates the intermediate state and all mid steps
332-
func (self *StateDB) SyncIntermediate() {
333-
self.refund = new(big.Int)
334-
335-
for _, stateObject := range self.stateObjects {
336318
if stateObject.dirty {
337319
if stateObject.remove {
338-
self.DeleteStateObject(stateObject)
320+
s.DeleteStateObject(stateObject)
339321
} else {
340322
stateObject.Update()
341-
342-
self.UpdateStateObject(stateObject)
323+
s.UpdateStateObject(stateObject)
343324
}
344325
stateObject.dirty = false
345326
}
346327
}
328+
return s.trie.Hash()
347329
}
348330

349-
// SyncObjects syncs the changed objects to the trie
350-
func (self *StateDB) SyncObjects() {
351-
self.trie = trie.NewSecure(self.root[:], self.db)
331+
// Commit commits all state changes to the database.
332+
func (s *StateDB) Commit() (root common.Hash, err error) {
333+
return s.commit(s.db)
334+
}
352335

353-
self.refund = new(big.Int)
336+
// CommitBatch commits all state changes to a write batch but does not
337+
// execute the batch. It is used to validate state changes against
338+
// the root hash stored in a block.
339+
func (s *StateDB) CommitBatch() (root common.Hash, batch ethdb.Batch) {
340+
batch = s.db.NewBatch()
341+
root, _ = s.commit(batch)
342+
return root, batch
343+
}
354344

355-
for _, stateObject := range self.stateObjects {
345+
func (s *StateDB) commit(db trie.DatabaseWriter) (common.Hash, error) {
346+
s.refund = new(big.Int)
347+
348+
for _, stateObject := range s.stateObjects {
356349
if stateObject.remove {
357-
self.DeleteStateObject(stateObject)
350+
// If the object has been removed, don't bother syncing it
351+
// and just mark it for deletion in the trie.
352+
s.DeleteStateObject(stateObject)
358353
} else {
354+
// Write any storage changes in the state object to its trie.
359355
stateObject.Update()
360-
361-
self.UpdateStateObject(stateObject)
356+
// Commit the trie of the object to the batch.
357+
// This updates the trie root internally, so
358+
// getting the root hash of the storage trie
359+
// through UpdateStateObject is fast.
360+
if _, err := stateObject.trie.CommitTo(db); err != nil {
361+
return common.Hash{}, err
362+
}
363+
// Update the object in the account trie.
364+
s.UpdateStateObject(stateObject)
362365
}
363366
stateObject.dirty = false
364367
}
368+
return s.trie.CommitTo(db)
369+
}
370+
371+
func (self *StateDB) Refunds() *big.Int {
372+
return self.refund
365373
}
366374

367375
// Debug stuff

0 commit comments

Comments
 (0)