Skip to content

Commit ab27bee

Browse files
committed
core, eth, trie: direct state trie synchronization
1 parent 832b37c commit ab27bee

13 files changed

Lines changed: 1626 additions & 463 deletions

File tree

‎core/blockchain.go‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import (
3737
"github.com/ethereum/go-ethereum/metrics"
3838
"github.com/ethereum/go-ethereum/pow"
3939
"github.com/ethereum/go-ethereum/rlp"
40+
"github.com/ethereum/go-ethereum/trie"
4041
"github.com/hashicorp/golang-lru"
4142
)
4243

@@ -246,6 +247,26 @@ func (bc *BlockChain) SetHead(head uint64) {
246247
bc.loadLastState()
247248
}
248249

250+
// FastSyncCommitHead sets the current head block to the one defined by the hash
251+
// irrelevant what the chain contents were prior.
252+
func (self *BlockChain) FastSyncCommitHead(hash common.Hash) error {
253+
// Make sure that both the block as well at it's state trie exists
254+
block := self.GetBlock(hash)
255+
if block == nil {
256+
return fmt.Errorf("non existent block [%x…]", hash[:4])
257+
}
258+
if _, err := trie.NewSecure(block.Root(), self.chainDb); err != nil {
259+
return err
260+
}
261+
// If all checks out, manually set the head block
262+
self.mu.Lock()
263+
self.currentBlock = block
264+
self.mu.Unlock()
265+
266+
glog.V(logger.Info).Infof("committed block #%d [%x…] as new head", block.Number(), hash[:4])
267+
return nil
268+
}
269+
249270
func (self *BlockChain) GasLimit() *big.Int {
250271
self.mu.RLock()
251272
defer self.mu.RUnlock()
@@ -721,10 +742,6 @@ func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain
721742
self.wg.Add(1)
722743
defer self.wg.Done()
723744

724-
// Make sure only one thread manipulates the chain at once
725-
self.chainmu.Lock()
726-
defer self.chainmu.Unlock()
727-
728745
// Collect some import statistics to report on
729746
stats := struct{ processed, ignored int }{}
730747
start := time.Now()

‎core/state/sync.go‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
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+
"bytes"
21+
"math/big"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/crypto/sha3"
25+
"github.com/ethereum/go-ethereum/ethdb"
26+
"github.com/ethereum/go-ethereum/rlp"
27+
"github.com/ethereum/go-ethereum/trie"
28+
)
29+
30+
type StateSync struct {
31+
db ethdb.Database
32+
sync *trie.TrieSync
33+
codeReqs map[common.Hash]struct{} // requested but not yet written to database
34+
codeReqList []common.Hash // requested since last Missing
35+
}
36+
37+
var sha3_nil = common.BytesToHash(sha3.NewKeccak256().Sum(nil))
38+
39+
func NewStateSync(root common.Hash, db ethdb.Database) *StateSync {
40+
ss := &StateSync{
41+
db: db,
42+
codeReqs: make(map[common.Hash]struct{}),
43+
}
44+
ss.codeReqs[sha3_nil] = struct{}{} // never request the nil hash
45+
ss.sync = trie.NewTrieSync(root, db, ss.leafFound)
46+
return ss
47+
}
48+
49+
func (self *StateSync) leafFound(leaf []byte, parent common.Hash) error {
50+
var obj struct {
51+
Nonce uint64
52+
Balance *big.Int
53+
Root common.Hash
54+
CodeHash []byte
55+
}
56+
if err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil {
57+
return err
58+
}
59+
self.sync.AddSubTrie(obj.Root, 64, parent, nil)
60+
61+
codehash := common.BytesToHash(obj.CodeHash)
62+
if _, ok := self.codeReqs[codehash]; !ok {
63+
code, _ := self.db.Get(obj.CodeHash)
64+
if code == nil {
65+
self.codeReqs[codehash] = struct{}{}
66+
self.codeReqList = append(self.codeReqList, codehash)
67+
}
68+
}
69+
return nil
70+
}
71+
72+
func (self *StateSync) Missing(max int) []common.Hash {
73+
cr := len(self.codeReqList)
74+
gh := 0
75+
if max != 0 {
76+
if cr > max {
77+
cr = max
78+
}
79+
gh = max - cr
80+
}
81+
list := append(self.sync.Missing(gh), self.codeReqList[:cr]...)
82+
self.codeReqList = self.codeReqList[cr:]
83+
return list
84+
}
85+
86+
func (self *StateSync) Process(list []trie.SyncResult) error {
87+
for i := 0; i < len(list); i++ {
88+
if _, ok := self.codeReqs[list[i].Hash]; ok { // code data, not a node
89+
self.db.Put(list[i].Hash[:], list[i].Data)
90+
delete(self.codeReqs, list[i].Hash)
91+
list[i] = list[len(list)-1]
92+
list = list[:len(list)-1]
93+
i--
94+
}
95+
}
96+
_, err := self.sync.Process(list)
97+
return err
98+
}

‎core/state/sync_test.go‎

Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
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+
"bytes"
21+
"math/big"
22+
"testing"
23+
24+
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/ethdb"
26+
"github.com/ethereum/go-ethereum/trie"
27+
)
28+
29+
// testAccount is the data associated with an account used by the state tests.
30+
type testAccount struct {
31+
address common.Address
32+
balance *big.Int
33+
nonce uint64
34+
code []byte
35+
}
36+
37+
// makeTestState create a sample test state to test node-wise reconstruction.
38+
func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
39+
// Create an empty state
40+
db, _ := ethdb.NewMemDatabase()
41+
state := New(common.Hash{}, db)
42+
43+
// Fill it with some arbitrary data
44+
accounts := []*testAccount{}
45+
for i := byte(0); i < 255; i++ {
46+
obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
47+
acc := &testAccount{address: common.BytesToAddress([]byte{i})}
48+
49+
obj.AddBalance(big.NewInt(int64(11 * i)))
50+
acc.balance = big.NewInt(int64(11 * i))
51+
52+
obj.SetNonce(uint64(42 * i))
53+
acc.nonce = uint64(42 * i)
54+
55+
if i%3 == 0 {
56+
obj.SetCode([]byte{i, i, i, i, i})
57+
acc.code = []byte{i, i, i, i, i}
58+
}
59+
state.UpdateStateObject(obj)
60+
accounts = append(accounts, acc)
61+
}
62+
root, _ := state.Commit()
63+
64+
// Return the generated state
65+
return db, root, accounts
66+
}
67+
68+
// checkStateAccounts cross references a reconstructed state with an expected
69+
// account array.
70+
func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
71+
state := New(root, db)
72+
for i, acc := range accounts {
73+
74+
if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
75+
t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
76+
}
77+
if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
78+
t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
79+
}
80+
if code := state.GetCode(acc.address); bytes.Compare(code, acc.code) != 0 {
81+
t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
82+
}
83+
}
84+
}
85+
86+
// Tests that an empty state is not scheduled for syncing.
87+
func TestEmptyStateSync(t *testing.T) {
88+
empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
89+
db, _ := ethdb.NewMemDatabase()
90+
if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
91+
t.Errorf("content requested for empty state: %v", req)
92+
}
93+
}
94+
95+
// Tests that given a root hash, a state can sync iteratively on a single thread,
96+
// requesting retrieval tasks and returning all of them in one go.
97+
func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
98+
func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }
99+
100+
func testIterativeStateSync(t *testing.T, batch int) {
101+
// Create a random state to copy
102+
srcDb, srcRoot, srcAccounts := makeTestState()
103+
104+
// Create a destination state and sync with the scheduler
105+
dstDb, _ := ethdb.NewMemDatabase()
106+
sched := NewStateSync(srcRoot, dstDb)
107+
108+
queue := append([]common.Hash{}, sched.Missing(batch)...)
109+
for len(queue) > 0 {
110+
results := make([]trie.SyncResult, len(queue))
111+
for i, hash := range queue {
112+
data, err := srcDb.Get(hash.Bytes())
113+
if err != nil {
114+
t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
115+
}
116+
results[i] = trie.SyncResult{hash, data}
117+
}
118+
if err := sched.Process(results); err != nil {
119+
t.Fatalf("failed to process results: %v", err)
120+
}
121+
queue = append(queue[:0], sched.Missing(batch)...)
122+
}
123+
// Cross check that the two states are in sync
124+
checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
125+
}
126+
127+
// Tests that the trie scheduler can correctly reconstruct the state even if only
128+
// partial results are returned, and the others sent only later.
129+
func TestIterativeDelayedStateSync(t *testing.T) {
130+
// Create a random state to copy
131+
srcDb, srcRoot, srcAccounts := makeTestState()
132+
133+
// Create a destination state and sync with the scheduler
134+
dstDb, _ := ethdb.NewMemDatabase()
135+
sched := NewStateSync(srcRoot, dstDb)
136+
137+
queue := append([]common.Hash{}, sched.Missing(0)...)
138+
for len(queue) > 0 {
139+
// Sync only half of the scheduled nodes
140+
results := make([]trie.SyncResult, len(queue)/2+1)
141+
for i, hash := range queue[:len(results)] {
142+
data, err := srcDb.Get(hash.Bytes())
143+
if err != nil {
144+
t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
145+
}
146+
results[i] = trie.SyncResult{hash, data}
147+
}
148+
if err := sched.Process(results); err != nil {
149+
t.Fatalf("failed to process results: %v", err)
150+
}
151+
queue = append(queue[len(results):], sched.Missing(0)...)
152+
}
153+
// Cross check that the two states are in sync
154+
checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
155+
}
156+
157+
// Tests that given a root hash, a trie can sync iteratively on a single thread,
158+
// requesting retrieval tasks and returning all of them in one go, however in a
159+
// random order.
160+
func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
161+
func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
162+
163+
func testIterativeRandomStateSync(t *testing.T, batch int) {
164+
// Create a random state to copy
165+
srcDb, srcRoot, srcAccounts := makeTestState()
166+
167+
// Create a destination state and sync with the scheduler
168+
dstDb, _ := ethdb.NewMemDatabase()
169+
sched := NewStateSync(srcRoot, dstDb)
170+
171+
queue := make(map[common.Hash]struct{})
172+
for _, hash := range sched.Missing(batch) {
173+
queue[hash] = struct{}{}
174+
}
175+
for len(queue) > 0 {
176+
// Fetch all the queued nodes in a random order
177+
results := make([]trie.SyncResult, 0, len(queue))
178+
for hash, _ := range queue {
179+
data, err := srcDb.Get(hash.Bytes())
180+
if err != nil {
181+
t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
182+
}
183+
results = append(results, trie.SyncResult{hash, data})
184+
}
185+
// Feed the retrieved results back and queue new tasks
186+
if err := sched.Process(results); err != nil {
187+
t.Fatalf("failed to process results: %v", err)
188+
}
189+
queue = make(map[common.Hash]struct{})
190+
for _, hash := range sched.Missing(batch) {
191+
queue[hash] = struct{}{}
192+
}
193+
}
194+
// Cross check that the two states are in sync
195+
checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
196+
}
197+
198+
// Tests that the trie scheduler can correctly reconstruct the state even if only
199+
// partial results are returned (Even those randomly), others sent only later.
200+
func TestIterativeRandomDelayedStateSync(t *testing.T) {
201+
// Create a random state to copy
202+
srcDb, srcRoot, srcAccounts := makeTestState()
203+
204+
// Create a destination state and sync with the scheduler
205+
dstDb, _ := ethdb.NewMemDatabase()
206+
sched := NewStateSync(srcRoot, dstDb)
207+
208+
queue := make(map[common.Hash]struct{})
209+
for _, hash := range sched.Missing(0) {
210+
queue[hash] = struct{}{}
211+
}
212+
for len(queue) > 0 {
213+
// Sync only half of the scheduled nodes, even those in random order
214+
results := make([]trie.SyncResult, 0, len(queue)/2+1)
215+
for hash, _ := range queue {
216+
delete(queue, hash)
217+
218+
data, err := srcDb.Get(hash.Bytes())
219+
if err != nil {
220+
t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
221+
}
222+
results = append(results, trie.SyncResult{hash, data})
223+
224+
if len(results) >= cap(results) {
225+
break
226+
}
227+
}
228+
// Feed the retrieved results back and queue new tasks
229+
if err := sched.Process(results); err != nil {
230+
t.Fatalf("failed to process results: %v", err)
231+
}
232+
for _, hash := range sched.Missing(0) {
233+
queue[hash] = struct{}{}
234+
}
235+
}
236+
// Cross check that the two states are in sync
237+
checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
238+
}

0 commit comments

Comments
 (0)