/
blockchain_cache.go
346 lines (302 loc) · 11.1 KB
/
blockchain_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package core
import (
"errors"
"fmt"
"sort"
"sync"
"time"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/metrics"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/consensus"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/state"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/types"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/log"
)
var (
errMakeStateDB = errors.New("make StateDB error")
blockExecutedGauage = metrics.NewRegisteredGauge("pbft/gauage/block/executed", nil)
)
type BlockChainCache struct {
*BlockChain
stateDBCache map[common.Hash]*stateDBCache // key is header SealHash
receiptsCache map[common.Hash]*receiptsCache // key is header SealHash
stateDBMu sync.RWMutex
receiptsMu sync.RWMutex
executing sync.Mutex
executed sync.Map
}
type stateDBCache struct {
stateDB *state.StateDB
blockNum uint64
}
type receiptsCache struct {
receipts []*types.Receipt
blockNum uint64
}
func (pbc *BlockChainCache) CurrentBlock() *types.Block {
block := pbc.Engine().CurrentBlock()
if block != nil {
return block
}
return pbc.currentBlock.Load().(*types.Block)
}
func (pbc *BlockChainCache) GetBlock(hash common.Hash, number uint64) *types.Block {
var block *types.Block
if pbft, ok := pbc.Engine().(consensus.Bft); ok {
log.Trace("Find block in pbft", "hash", hash, "number", number)
block = pbft.GetBlock(hash, number)
}
if block == nil {
log.Trace("Cannot find block in pbft, try to find it in chain", "hash", hash, "number", number)
block = pbc.getBlock(hash, number)
if block == nil {
log.Trace("Cannot find block in chain", "hash", hash, "number", number)
}
}
return block
}
func (pbc *BlockChainCache) GetBlockInMemory(hash common.Hash, number uint64) *types.Block {
var block *types.Block
if pbft, ok := pbc.Engine().(consensus.Bft); ok {
log.Trace("find block in pbft", "hash", hash, "number", number)
block = pbft.GetBlockWithoutLock(hash, number)
}
if block == nil {
log.Trace("cannot find block in pbft, try to find it in chain", "hash", hash, "number", number)
block = pbc.getBlock(hash, number)
if block == nil {
log.Trace("cannot find block in chain", "hash", hash, "number", number)
}
}
return block
}
func NewBlockChainCache(blockChain *BlockChain) *BlockChainCache {
pbc := &BlockChainCache{}
pbc.BlockChain = blockChain
pbc.stateDBCache = make(map[common.Hash]*stateDBCache)
pbc.receiptsCache = make(map[common.Hash]*receiptsCache)
return pbc
}
// Read the Receipt collection from the cache map.
func (bcc *BlockChainCache) ReadReceipts(sealHash common.Hash) []*types.Receipt {
bcc.receiptsMu.RLock()
defer bcc.receiptsMu.RUnlock()
if obj, exist := bcc.receiptsCache[sealHash]; exist {
return obj.receipts
}
return nil
}
// GetState returns a new mutable state based on a particular point in time.
func (bcc *BlockChainCache) GetState(header *types.Header) (*state.StateDB, error) {
state, err := bcc.MakeStateDBByHeader(header)
if err == nil {
return state, nil
} else {
return bcc.StateAt(header.Root)
}
}
// Read the StateDB instance from the cache map
func (pbc *BlockChainCache) ReadStateDB(sealHash common.Hash) *state.StateDB {
pbc.stateDBMu.RLock()
defer pbc.stateDBMu.RUnlock()
if obj, exist := pbc.stateDBCache[sealHash]; exist {
log.Debug("Read the StateDB instance from the cache map", "sealHash", sealHash)
return obj.stateDB.Copy()
}
return nil
}
func (pbc *BlockChainCache) ReadOnlyStateDB(sealHash common.Hash) *state.StateDB {
pbc.stateDBMu.RLock()
defer pbc.stateDBMu.RUnlock()
if obj, exist := pbc.stateDBCache[sealHash]; exist {
log.Debug("Read the StateDB instance from the cache map", "sealHash", sealHash)
return obj.stateDB
}
return nil
}
// Write Receipt to the cache
func (pbc *BlockChainCache) WriteReceipts(sealHash common.Hash, receipts []*types.Receipt, blockNum uint64) {
pbc.receiptsMu.Lock()
defer pbc.receiptsMu.Unlock()
_, exist := pbc.receiptsCache[sealHash]
if !exist {
pbc.receiptsCache[sealHash] = &receiptsCache{receipts: receipts, blockNum: blockNum}
}
}
// Write a StateDB instance to the cache
func (bcc *BlockChainCache) WriteStateDB(sealHash common.Hash, stateDB *state.StateDB, blockNum uint64) {
bcc.stateDBMu.Lock()
defer bcc.stateDBMu.Unlock()
log.Info("Write a StateDB instance to the cache", "sealHash", sealHash, "blockNum", blockNum)
if _, exist := bcc.stateDBCache[sealHash]; !exist {
bcc.stateDBCache[sealHash] = &stateDBCache{stateDB: stateDB, blockNum: blockNum}
}
}
// Read the Receipt collection from the cache map
func (bcc *BlockChainCache) clearReceipts(sealHash common.Hash) {
bcc.receiptsMu.Lock()
defer bcc.receiptsMu.Unlock()
//var blockNum uint64
if obj, exist := bcc.receiptsCache[sealHash]; exist {
//blockNum = obj.blockNum
log.Debug("Clear Receipts", "sealHash", sealHash, "number", obj.blockNum)
delete(bcc.receiptsCache, sealHash)
}
//for hash, obj := range bcc.receiptsCache {
// if obj.blockNum < blockNum {
// delete(bcc.receiptsCache, hash)
// }
//}
}
// Read the StateDB instance from the cache map
func (bcc *BlockChainCache) clearStateDB(sealHash common.Hash) {
bcc.stateDBMu.Lock()
defer bcc.stateDBMu.Unlock()
if obj, exist := bcc.stateDBCache[sealHash]; exist {
obj.stateDB.ClearReference()
log.Debug("Clear StateDB", "sealHash", sealHash, "number", obj.blockNum)
delete(bcc.stateDBCache, sealHash)
//delete(pbc.stateDBCache, sealHash)
}
//for hash, obj := range bcc.stateDBCache {
// if obj.blockNum < blockNum {
// obj.stateDB.ClearReference()
// log.Debug("Clear StateDB", "sealHash", hash, "number", obj.blockNum)
// delete(bcc.stateDBCache, hash)
// }
//}
}
// Get the StateDB instance of the corresponding block
func (bcc *BlockChainCache) MakeStateDB(block *types.Block) (*state.StateDB, error) {
log.Info("Make stateDB", "hash", block.Hash(), "number", block.NumberU64(), "root", block.Root())
return bcc.MakeStateDBByHeader(block.Header())
}
func (bcc *BlockChainCache) MakeStateDBByHeader(header *types.Header) (*state.StateDB, error) {
// Read and copy the stateDB instance in the cache
sealHash, number, root := header.SealHash(), header.Number.Uint64(), header.Root
if state := bcc.ReadOnlyStateDB(sealHash); state != nil {
statedb := state.NewStateDB()
if number > 1 && !statedb.HadParent() {
panic(fmt.Sprintf("parent is nil:%d", number))
}
return statedb, nil
} else if state, err := bcc.StateAt(root); err == nil && state != nil {
// Create a StateDB instance from the blockchain based on stateRoot
return state, nil
}
return nil, errMakeStateDB
}
// Get the StateDB instance of the corresponding block
func (bcc *BlockChainCache) ClearCache(block *types.Block) {
baseNumber := block.NumberU64()
if baseNumber < 1 {
return
}
log.Debug("Clear cache", "baseBlockHash", block.Hash(), "baseBlockNumber", baseNumber)
var sh sealHashSort
bcc.executed.Range(func(key, value interface{}) bool {
number := value.(uint64)
if number < baseNumber-1 {
sealHash := key.(common.Hash)
sh = append(sh, &sealHashNumber{number: number, hash: sealHash})
}
return true
})
sort.Sort(sh)
for _, s := range sh {
log.Debug("Clear Cache block", "sealHash", s.hash, "number", s.number)
bcc.clearReceipts(s.hash)
bcc.clearStateDB(s.hash)
bcc.executed.Delete(s.hash)
}
}
func (bcc *BlockChainCache) StateDBString() string {
status := fmt.Sprintf("[")
for hash, obj := range bcc.stateDBCache {
status += fmt.Sprintf("[%s, %d]", hash, obj.blockNum)
}
status += fmt.Sprintf("]")
return status
}
func (bcc *BlockChainCache) Execute(block *types.Block, parent *types.Block) error {
executed := func() bool {
if number, ok := bcc.executed.Load(block.Header().SealHash()); ok && number.(uint64) == block.Number().Uint64() {
log.Debug("Block has executed", "number", block.Number(), "hash", block.Hash(), "parentNumber", parent.Number(), "parentHash", parent.Hash())
return true
}
return false
}
if executed() {
return nil
}
bcc.executing.Lock()
defer bcc.executing.Unlock()
if executed() {
return nil
}
SenderCacher.RecoverFromBlock(types.NewEIP155Signer(bcc.chainConfig.ChainID), block)
log.Debug("Start execute block", "hash", block.Hash(), "number", block.Number(), "sealHash", block.Header().SealHash())
start := time.Now()
state, err := bcc.MakeStateDB(parent)
elapse := time.Since(start)
if err != nil {
return errors.New("execute block error")
}
t := time.Now()
//to execute
receipts, err := bcc.ProcessDirectly(block, state, parent)
log.Debug("Execute block", "number", block.Number(), "hash", block.Hash(),
"parentNumber", parent.Number(), "parentHash", parent.Hash(), "duration", time.Since(t), "makeState", elapse, "err", err)
if err == nil {
//save the receipts and state to consensusCache
sealHash := block.Header().SealHash()
bcc.WriteReceipts(sealHash, receipts, block.NumberU64())
bcc.WriteStateDB(sealHash, state, block.NumberU64())
bcc.executed.Store(block.Header().SealHash(), block.Number().Uint64())
} else {
return fmt.Errorf("execute block error, err:%s", err.Error())
}
blockExecutedGauage.Update(common.Millis(time.Now()) - common.Millis(start))
return nil
}
func (bcc *BlockChainCache) AddSealBlock(hash common.Hash, number uint64) {
bcc.executed.Store(hash, number)
}
func (bcc *BlockChainCache) WriteBlock(block *types.Block) error {
sealHash := block.Header().SealHash()
state := bcc.ReadStateDB(sealHash)
receipts := bcc.ReadReceipts(sealHash)
if state == nil {
log.Error("Write Block error, state is nil", "number", block.NumberU64(), "hash", block.Hash())
return fmt.Errorf("write Block error, state is nil, number:%d, hash:%s", block.NumberU64(), block.Hash().String())
} else if len(block.Transactions()) > 0 && len(receipts) == 0 {
log.Error("Write Block error, block has transactions but receipts is nil", "number", block.NumberU64(), "hash", block.Hash())
return fmt.Errorf("write Block error, block has transactions but receipts is nil, number:%d, hash:%s", block.NumberU64(), block.Hash().String())
}
// Different block could share same sealhash, deep copy here to prevent write-write conflict.
var _receipts = make([]*types.Receipt, len(receipts))
for i, receipt := range receipts {
_receipts[i] = new(types.Receipt)
*_receipts[i] = *receipt
}
// Commit block and state to database.
//block.SetExtraData(extraData)
log.Debug("Write extra data", "txs", len(block.Transactions()), "extra", len(block.ExtraData()))
_, err := bcc.WriteBlockWithState(block, _receipts, state)
if err != nil {
log.Error("Failed writing block to chain", "hash", block.Hash(), "number", block.NumberU64(), "err", err)
return fmt.Errorf("failed writing block to chain, number:%d, hash:%s, err:%s", block.NumberU64(), block.Hash().String(), err.Error())
}
log.Info("Successfully write new block", "hash", block.Hash(), "number", block.NumberU64())
return nil
}
type sealHashNumber struct {
number uint64
hash common.Hash
}
type sealHashSort []*sealHashNumber
func (self sealHashSort) Len() int { return len(self) }
func (self sealHashSort) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
func (self sealHashSort) Less(i, j int) bool { return self[i].number < self[j].number }