Skip to content

Commit 2b339cb

Browse files
committed
core, eth: split the db blocks into headers and bodies
1 parent 4e075e4 commit 2b339cb

9 files changed

Lines changed: 430 additions & 226 deletions

File tree

‎core/chain_manager.go‎

Lines changed: 153 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ var (
4848
)
4949

5050
const (
51+
headerCacheLimit = 256
52+
bodyCacheLimit = 256
5153
blockCacheLimit = 256
5254
maxFutureBlocks = 256
5355
maxTimeFutureBlocks = 30
@@ -71,7 +73,10 @@ type ChainManager struct {
7173
lastBlockHash common.Hash
7274
currentGasLimit *big.Int
7375

74-
cache *lru.Cache // cache is the LRU caching
76+
headerCache *lru.Cache // Cache for the most recent block headers
77+
bodyCache *lru.Cache // Cache for the most recent block bodies
78+
bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
79+
blockCache *lru.Cache // Cache for the most recent entire blocks
7580
futureBlocks *lru.Cache // future blocks are blocks added for later processing
7681

7782
quit chan struct{}
@@ -84,13 +89,22 @@ type ChainManager struct {
8489
}
8590

8691
func NewChainManager(chainDb common.Database, pow pow.PoW, mux *event.TypeMux) (*ChainManager, error) {
87-
cache, _ := lru.New(blockCacheLimit)
92+
headerCache, _ := lru.New(headerCacheLimit)
93+
bodyCache, _ := lru.New(bodyCacheLimit)
94+
bodyRLPCache, _ := lru.New(bodyCacheLimit)
95+
blockCache, _ := lru.New(blockCacheLimit)
96+
futureBlocks, _ := lru.New(maxFutureBlocks)
97+
8898
bc := &ChainManager{
89-
chainDb: chainDb,
90-
eventMux: mux,
91-
quit: make(chan struct{}),
92-
cache: cache,
93-
pow: pow,
99+
chainDb: chainDb,
100+
eventMux: mux,
101+
quit: make(chan struct{}),
102+
headerCache: headerCache,
103+
bodyCache: bodyCache,
104+
bodyRLPCache: bodyRLPCache,
105+
blockCache: blockCache,
106+
futureBlocks: futureBlocks,
107+
pow: pow,
94108
}
95109

96110
bc.genesisBlock = bc.GetBlockByNumber(0)
@@ -105,11 +119,9 @@ func NewChainManager(chainDb common.Database, pow pow.PoW, mux *event.TypeMux) (
105119
}
106120
glog.V(logger.Info).Infoln("WARNING: Wrote default ethereum genesis block")
107121
}
108-
109122
if err := bc.setLastState(); err != nil {
110123
return nil, err
111124
}
112-
113125
// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
114126
for hash, _ := range BadHashes {
115127
if block := bc.GetBlock(hash); block != nil {
@@ -123,14 +135,8 @@ func NewChainManager(chainDb common.Database, pow pow.PoW, mux *event.TypeMux) (
123135
glog.V(logger.Error).Infoln("Chain reorg was successfull. Resuming normal operation")
124136
}
125137
}
126-
127138
// Take ownership of this particular state
128-
129-
bc.futureBlocks, _ = lru.New(maxFutureBlocks)
130-
bc.makeCache()
131-
132139
go bc.update()
133-
134140
return bc, nil
135141
}
136142

@@ -139,13 +145,15 @@ func (bc *ChainManager) SetHead(head *types.Block) {
139145
defer bc.mu.Unlock()
140146

141147
for block := bc.currentBlock; block != nil && block.Hash() != head.Hash(); block = bc.GetBlock(block.ParentHash()) {
142-
bc.removeBlock(block)
148+
DeleteBlock(bc.chainDb, block.Hash())
143149
}
150+
bc.headerCache.Purge()
151+
bc.bodyCache.Purge()
152+
bc.bodyRLPCache.Purge()
153+
bc.blockCache.Purge()
154+
bc.futureBlocks.Purge()
144155

145-
bc.cache, _ = lru.New(blockCacheLimit)
146156
bc.currentBlock = head
147-
bc.makeCache()
148-
149157
bc.setTotalDifficulty(head.Td)
150158
bc.insert(head)
151159
bc.setLastState()
@@ -199,11 +207,9 @@ func (bc *ChainManager) recover() bool {
199207
if len(data) != 0 {
200208
block := bc.GetBlock(common.BytesToHash(data))
201209
if block != nil {
202-
err := bc.chainDb.Put([]byte("LastBlock"), block.Hash().Bytes())
203-
if err != nil {
204-
glog.Fatalln("db write err:", err)
210+
if err := WriteHead(bc.chainDb, block); err != nil {
211+
glog.Fatalf("failed to write database head: %v", err)
205212
}
206-
207213
bc.currentBlock = block
208214
bc.lastBlockHash = block.Hash()
209215
return true
@@ -213,14 +219,14 @@ func (bc *ChainManager) recover() bool {
213219
}
214220

215221
func (bc *ChainManager) setLastState() error {
216-
data, _ := bc.chainDb.Get([]byte("LastBlock"))
217-
if len(data) != 0 {
218-
block := bc.GetBlock(common.BytesToHash(data))
222+
head := GetHeadHash(bc.chainDb)
223+
if head != (common.Hash{}) {
224+
block := bc.GetBlock(head)
219225
if block != nil {
220226
bc.currentBlock = block
221227
bc.lastBlockHash = block.Hash()
222228
} else {
223-
glog.Infof("LastBlock (%x) not found. Recovering...\n", data)
229+
glog.Infof("LastBlock (%x) not found. Recovering...\n", head)
224230
if bc.recover() {
225231
glog.Infof("Recover successful")
226232
} else {
@@ -240,63 +246,37 @@ func (bc *ChainManager) setLastState() error {
240246
return nil
241247
}
242248

243-
func (bc *ChainManager) makeCache() {
244-
bc.cache, _ = lru.New(blockCacheLimit)
245-
// load in last `blockCacheLimit` - 1 blocks. Last block is the current.
246-
bc.cache.Add(bc.genesisBlock.Hash(), bc.genesisBlock)
247-
for _, block := range bc.GetBlocksFromHash(bc.currentBlock.Hash(), blockCacheLimit) {
248-
bc.cache.Add(block.Hash(), block)
249-
}
250-
}
251-
249+
// Reset purges the entire blockchain, restoring it to its genesis state.
252250
func (bc *ChainManager) Reset() {
253-
bc.mu.Lock()
254-
defer bc.mu.Unlock()
255-
256-
for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.ParentHash()) {
257-
bc.removeBlock(block)
258-
}
259-
260-
bc.cache, _ = lru.New(blockCacheLimit)
261-
262-
// Prepare the genesis block
263-
err := WriteBlock(bc.chainDb, bc.genesisBlock)
264-
if err != nil {
265-
glog.Fatalln("db err:", err)
266-
}
267-
268-
bc.insert(bc.genesisBlock)
269-
bc.currentBlock = bc.genesisBlock
270-
bc.makeCache()
271-
272-
bc.setTotalDifficulty(common.Big("0"))
251+
bc.ResetWithGenesisBlock(bc.genesisBlock)
273252
}
274253

275-
func (bc *ChainManager) removeBlock(block *types.Block) {
276-
bc.chainDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
277-
}
278-
279-
func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
254+
// ResetWithGenesisBlock purges the entire blockchain, restoring it to the
255+
// specified genesis state.
256+
func (bc *ChainManager) ResetWithGenesisBlock(genesis *types.Block) {
280257
bc.mu.Lock()
281258
defer bc.mu.Unlock()
282259

260+
// Dump the entire block chain and purge the caches
283261
for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.ParentHash()) {
284-
bc.removeBlock(block)
262+
DeleteBlock(bc.chainDb, block.Hash())
285263
}
264+
bc.headerCache.Purge()
265+
bc.bodyCache.Purge()
266+
bc.bodyRLPCache.Purge()
267+
bc.blockCache.Purge()
268+
bc.futureBlocks.Purge()
286269

287-
// Prepare the genesis block
288-
gb.Td = gb.Difficulty()
289-
bc.genesisBlock = gb
270+
// Prepare the genesis block and reinitialize the chain
271+
bc.genesisBlock = genesis
272+
bc.genesisBlock.Td = genesis.Difficulty()
290273

291-
err := WriteBlock(bc.chainDb, bc.genesisBlock)
292-
if err != nil {
293-
glog.Fatalln("db err:", err)
274+
if err := WriteBlock(bc.chainDb, bc.genesisBlock); err != nil {
275+
glog.Fatalf("failed to write genesis block: %v", err)
294276
}
295-
296277
bc.insert(bc.genesisBlock)
297278
bc.currentBlock = bc.genesisBlock
298-
bc.makeCache()
299-
bc.td = gb.Difficulty()
279+
bc.setTotalDifficulty(genesis.Difficulty())
300280
}
301281

302282
// Export writes the active chain to the given writer.
@@ -359,61 +339,130 @@ func (bc *ChainManager) Genesis() *types.Block {
359339
return bc.genesisBlock
360340
}
361341

362-
// Block fetching methods
363-
func (bc *ChainManager) HasBlock(hash common.Hash) bool {
364-
if bc.cache.Contains(hash) {
365-
return true
342+
// HasHeader checks if a block header is present in the database or not, caching
343+
// it if present.
344+
func (bc *ChainManager) HasHeader(hash common.Hash) bool {
345+
return bc.GetHeader(hash) != nil
346+
}
347+
348+
// GetHeader retrieves a block header from the database by hash, caching it if
349+
// found.
350+
func (self *ChainManager) GetHeader(hash common.Hash) *types.Header {
351+
// Short circuit if the header's already in the cache, retrieve otherwise
352+
if header, ok := self.headerCache.Get(hash); ok {
353+
return header.(*types.Header)
354+
}
355+
header := GetHeaderByHash(self.chainDb, hash)
356+
if header == nil {
357+
return nil
366358
}
359+
// Cache the found header for next time and return
360+
self.headerCache.Add(header.Hash(), header)
361+
return header
362+
}
367363

368-
data, _ := bc.chainDb.Get(append(blockHashPre, hash[:]...))
369-
return len(data) != 0
364+
// GetHeaderByNumber retrieves a block header from the database by number,
365+
// caching it (associated with its hash) if found.
366+
func (self *ChainManager) GetHeaderByNumber(number uint64) *types.Header {
367+
hash := GetHashByNumber(self.chainDb, number)
368+
if hash == (common.Hash{}) {
369+
return nil
370+
}
371+
return self.GetHeader(hash)
370372
}
371373

372-
func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (chain []common.Hash) {
373-
block := self.GetBlock(hash)
374-
if block == nil {
375-
return
374+
// GetBody retrieves a block body (transactions, uncles and total difficulty)
375+
// from the database by hash, caching it if found. The resion for the peculiar
376+
// pointer-to-slice return type is to differentiate between empty and inexistent
377+
// bodies.
378+
func (self *ChainManager) GetBody(hash common.Hash) (*[]*types.Transaction, *[]*types.Header) {
379+
// Short circuit if the body's already in the cache, retrieve otherwise
380+
if cached, ok := self.bodyCache.Get(hash); ok {
381+
body := cached.(*storageBody)
382+
return &body.Transactions, &body.Uncles
376383
}
377-
// XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
378-
for i := uint64(0); i < max; i++ {
379-
block = self.GetBlock(block.ParentHash())
380-
if block == nil {
381-
break
382-
}
384+
transactions, uncles, td := GetBodyByHash(self.chainDb, hash)
385+
if td == nil {
386+
return nil, nil
387+
}
388+
// Cache the found body for next time and return
389+
self.bodyCache.Add(hash, &storageBody{
390+
Transactions: transactions,
391+
Uncles: uncles,
392+
})
393+
return &transactions, &uncles
394+
}
383395

384-
chain = append(chain, block.Hash())
385-
if block.Number().Cmp(common.Big0) <= 0 {
386-
break
387-
}
396+
// GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
397+
// caching it if found.
398+
func (self *ChainManager) GetBodyRLP(hash common.Hash) []byte {
399+
// Short circuit if the body's already in the cache, retrieve otherwise
400+
if cached, ok := self.bodyRLPCache.Get(hash); ok {
401+
return cached.([]byte)
388402
}
403+
body, td := GetBodyRLPByHash(self.chainDb, hash)
404+
if td == nil {
405+
return nil
406+
}
407+
// Cache the found body for next time and return
408+
self.bodyRLPCache.Add(hash, body)
409+
return body
410+
}
389411

390-
return
412+
// HasBlock checks if a block is fully present in the database or not, caching
413+
// it if present.
414+
func (bc *ChainManager) HasBlock(hash common.Hash) bool {
415+
return bc.GetBlock(hash) != nil
391416
}
392417

418+
// GetBlock retrieves a block from the database by hash, caching it if found.
393419
func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
394-
if block, ok := self.cache.Get(hash); ok {
420+
// Short circuit if the block's already in the cache, retrieve otherwise
421+
if block, ok := self.blockCache.Get(hash); ok {
395422
return block.(*types.Block)
396423
}
397-
398424
block := GetBlockByHash(self.chainDb, hash)
399425
if block == nil {
400426
return nil
401427
}
402-
403-
// Add the block to the cache
404-
self.cache.Add(hash, (*types.Block)(block))
405-
406-
return (*types.Block)(block)
428+
// Cache the found block for next time and return
429+
self.blockCache.Add(block.Hash(), block)
430+
return block
407431
}
408432

409-
func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
410-
self.mu.RLock()
411-
defer self.mu.RUnlock()
412-
413-
return self.getBlockByNumber(num)
433+
// GetBlockByNumber retrieves a block from the database by number, caching it
434+
// (associated with its hash) if found.
435+
func (self *ChainManager) GetBlockByNumber(number uint64) *types.Block {
436+
hash := GetHashByNumber(self.chainDb, number)
437+
if hash == (common.Hash{}) {
438+
return nil
439+
}
440+
return self.GetBlock(hash)
441+
}
414442

443+
// GetBlockHashesFromHash retrieves a number of block hashes starting at a given
444+
// hash, fetching towards the genesis block.
445+
func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
446+
// Get the origin header from which to fetch
447+
header := self.GetHeader(hash)
448+
if header == nil {
449+
return nil
450+
}
451+
// Iterate the headers until enough is collected or the genesis reached
452+
chain := make([]common.Hash, 0, max)
453+
for i := uint64(0); i < max; i++ {
454+
if header = self.GetHeader(header.ParentHash); header == nil {
455+
break
456+
}
457+
chain = append(chain, header.Hash())
458+
if header.Number.Cmp(common.Big0) <= 0 {
459+
break
460+
}
461+
}
462+
return chain
415463
}
416464

465+
// [deprecated by eth/62]
417466
// GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
418467
func (self *ChainManager) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
419468
for i := 0; i < n; i++ {
@@ -427,11 +476,6 @@ func (self *ChainManager) GetBlocksFromHash(hash common.Hash, n int) (blocks []*
427476
return
428477
}
429478

430-
// non blocking version
431-
func (self *ChainManager) getBlockByNumber(num uint64) *types.Block {
432-
return GetBlockByNumber(self.chainDb, num)
433-
}
434-
435479
func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
436480
for i := 0; block != nil && i < length; i++ {
437481
uncles = append(uncles, block.Uncles()...)

‎core/chain_manager_test.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,10 @@ func makeChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block
388388
func chm(genesis *types.Block, db common.Database) *ChainManager {
389389
var eventMux event.TypeMux
390390
bc := &ChainManager{chainDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}}
391-
bc.cache, _ = lru.New(100)
391+
bc.headerCache, _ = lru.New(100)
392+
bc.bodyCache, _ = lru.New(100)
393+
bc.bodyRLPCache, _ = lru.New(100)
394+
bc.blockCache, _ = lru.New(100)
392395
bc.futureBlocks, _ = lru.New(100)
393396
bc.processor = bproc{}
394397
bc.ResetWithGenesisBlock(genesis)

0 commit comments

Comments
 (0)