Skip to content

Commit cdc2662

Browse files
committed
core: split out TD from database and all internals
1 parent 2b339cb commit cdc2662

19 files changed

Lines changed: 590 additions & 294 deletions

‎cmd/geth/main.go‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -528,17 +528,16 @@ func blockRecovery(ctx *cli.Context) {
528528

529529
var block *types.Block
530530
if arg[0] == '#' {
531-
block = core.GetBlockByNumber(blockDb, common.String2Big(arg[1:]).Uint64())
531+
block = core.GetBlock(blockDb, core.GetCanonicalHash(blockDb, common.String2Big(arg[1:]).Uint64()))
532532
} else {
533-
block = core.GetBlockByHash(blockDb, common.HexToHash(arg))
533+
block = core.GetBlock(blockDb, common.HexToHash(arg))
534534
}
535535

536536
if block == nil {
537537
glog.Fatalln("block not found. Recovery failed")
538538
}
539539

540-
err = core.WriteHead(blockDb, block)
541-
if err != nil {
540+
if err = core.WriteHeadBlockHash(blockDb, block.Hash()); err != nil {
542541
glog.Fatalln("block write err", err)
543542
}
544543
glog.Infof("Recovery succesful. New HEAD %x\n", block.Hash())

‎core/chain_makers.go‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,6 @@ func GenerateChain(parent *types.Block, db common.Database, n int, gen func(int,
158158
for i := 0; i < n; i++ {
159159
header := makeHeader(parent, statedb)
160160
block := genblock(i, header)
161-
block.Td = CalcTD(block, parent)
162161
blocks[i] = block
163162
parent = block
164163
}

‎core/chain_manager.go‎

Lines changed: 85 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535
"github.com/ethereum/go-ethereum/logger/glog"
3636
"github.com/ethereum/go-ethereum/metrics"
3737
"github.com/ethereum/go-ethereum/pow"
38+
"github.com/ethereum/go-ethereum/rlp"
3839
"github.com/hashicorp/golang-lru"
3940
)
4041

@@ -48,8 +49,9 @@ var (
4849
)
4950

5051
const (
51-
headerCacheLimit = 256
52+
headerCacheLimit = 512
5253
bodyCacheLimit = 256
54+
tdCacheLimit = 1024
5355
blockCacheLimit = 256
5456
maxFutureBlocks = 256
5557
maxTimeFutureBlocks = 30
@@ -70,12 +72,12 @@ type ChainManager struct {
7072
checkpoint int // checkpoint counts towards the new checkpoint
7173
td *big.Int
7274
currentBlock *types.Block
73-
lastBlockHash common.Hash
7475
currentGasLimit *big.Int
7576

7677
headerCache *lru.Cache // Cache for the most recent block headers
7778
bodyCache *lru.Cache // Cache for the most recent block bodies
7879
bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
80+
tdCache *lru.Cache // Cache for the most recent block total difficulties
7981
blockCache *lru.Cache // Cache for the most recent entire blocks
8082
futureBlocks *lru.Cache // future blocks are blocks added for later processing
8183

@@ -92,6 +94,7 @@ func NewChainManager(chainDb common.Database, pow pow.PoW, mux *event.TypeMux) (
9294
headerCache, _ := lru.New(headerCacheLimit)
9395
bodyCache, _ := lru.New(bodyCacheLimit)
9496
bodyRLPCache, _ := lru.New(bodyCacheLimit)
97+
tdCache, _ := lru.New(tdCacheLimit)
9598
blockCache, _ := lru.New(blockCacheLimit)
9699
futureBlocks, _ := lru.New(maxFutureBlocks)
97100

@@ -102,6 +105,7 @@ func NewChainManager(chainDb common.Database, pow pow.PoW, mux *event.TypeMux) (
102105
headerCache: headerCache,
103106
bodyCache: bodyCache,
104107
bodyRLPCache: bodyRLPCache,
108+
tdCache: tdCache,
105109
blockCache: blockCache,
106110
futureBlocks: futureBlocks,
107111
pow: pow,
@@ -154,7 +158,7 @@ func (bc *ChainManager) SetHead(head *types.Block) {
154158
bc.futureBlocks.Purge()
155159

156160
bc.currentBlock = head
157-
bc.setTotalDifficulty(head.Td)
161+
bc.setTotalDifficulty(bc.GetTd(head.Hash()))
158162
bc.insert(head)
159163
bc.setLastState()
160164
}
@@ -177,7 +181,7 @@ func (self *ChainManager) LastBlockHash() common.Hash {
177181
self.mu.RLock()
178182
defer self.mu.RUnlock()
179183

180-
return self.lastBlockHash
184+
return self.currentBlock.Hash()
181185
}
182186

183187
func (self *ChainManager) CurrentBlock() *types.Block {
@@ -207,24 +211,25 @@ func (bc *ChainManager) recover() bool {
207211
if len(data) != 0 {
208212
block := bc.GetBlock(common.BytesToHash(data))
209213
if block != nil {
210-
if err := WriteHead(bc.chainDb, block); err != nil {
211-
glog.Fatalf("failed to write database head: %v", err)
214+
if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
215+
glog.Fatalf("failed to write database head number: %v", err)
216+
}
217+
if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
218+
glog.Fatalf("failed to write database head hash: %v", err)
212219
}
213220
bc.currentBlock = block
214-
bc.lastBlockHash = block.Hash()
215221
return true
216222
}
217223
}
218224
return false
219225
}
220226

221227
func (bc *ChainManager) setLastState() error {
222-
head := GetHeadHash(bc.chainDb)
228+
head := GetHeadBlockHash(bc.chainDb)
223229
if head != (common.Hash{}) {
224230
block := bc.GetBlock(head)
225231
if block != nil {
226232
bc.currentBlock = block
227-
bc.lastBlockHash = block.Hash()
228233
} else {
229234
glog.Infof("LastBlock (%x) not found. Recovering...\n", head)
230235
if bc.recover() {
@@ -236,7 +241,7 @@ func (bc *ChainManager) setLastState() error {
236241
} else {
237242
bc.Reset()
238243
}
239-
bc.td = bc.currentBlock.Td
244+
bc.td = bc.GetTd(bc.currentBlock.Hash())
240245
bc.currentGasLimit = CalcGasLimit(bc.currentBlock)
241246

242247
if glog.V(logger.Info) {
@@ -268,10 +273,10 @@ func (bc *ChainManager) ResetWithGenesisBlock(genesis *types.Block) {
268273
bc.futureBlocks.Purge()
269274

270275
// Prepare the genesis block and reinitialize the chain
271-
bc.genesisBlock = genesis
272-
bc.genesisBlock.Td = genesis.Difficulty()
273-
274-
if err := WriteBlock(bc.chainDb, bc.genesisBlock); err != nil {
276+
if err := WriteTd(bc.chainDb, genesis.Hash(), genesis.Difficulty()); err != nil {
277+
glog.Fatalf("failed to write genesis block TD: %v", err)
278+
}
279+
if err := WriteBlock(bc.chainDb, genesis); err != nil {
275280
glog.Fatalf("failed to write genesis block: %v", err)
276281
}
277282
bc.insert(bc.genesisBlock)
@@ -315,23 +320,23 @@ func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error
315320
// insert injects a block into the current chain block chain. Note, this function
316321
// assumes that the `mu` mutex is held!
317322
func (bc *ChainManager) insert(block *types.Block) {
318-
err := WriteHead(bc.chainDb, block)
319-
if err != nil {
320-
glog.Fatal("db write fail:", err)
323+
// Add the block to the canonical chain number scheme and mark as the head
324+
if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
325+
glog.Fatalf("failed to insert block number: %v", err)
321326
}
322-
327+
if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
328+
glog.Fatalf("failed to insert block number: %v", err)
329+
}
330+
// Add a new restore point if we reached some limit
323331
bc.checkpoint++
324332
if bc.checkpoint > checkpointLimit {
325-
err = bc.chainDb.Put([]byte("checkpoint"), block.Hash().Bytes())
326-
if err != nil {
327-
glog.Fatal("db write fail:", err)
333+
if err := bc.chainDb.Put([]byte("checkpoint"), block.Hash().Bytes()); err != nil {
334+
glog.Fatalf("failed to create checkpoint: %v", err)
328335
}
329-
330336
bc.checkpoint = 0
331337
}
332-
338+
// Update the internal internal state with the head block
333339
bc.currentBlock = block
334-
bc.lastBlockHash = block.Hash()
335340
}
336341

337342
// Accessors
@@ -352,7 +357,7 @@ func (self *ChainManager) GetHeader(hash common.Hash) *types.Header {
352357
if header, ok := self.headerCache.Get(hash); ok {
353358
return header.(*types.Header)
354359
}
355-
header := GetHeaderByHash(self.chainDb, hash)
360+
header := GetHeader(self.chainDb, hash)
356361
if header == nil {
357362
return nil
358363
}
@@ -364,51 +369,62 @@ func (self *ChainManager) GetHeader(hash common.Hash) *types.Header {
364369
// GetHeaderByNumber retrieves a block header from the database by number,
365370
// caching it (associated with its hash) if found.
366371
func (self *ChainManager) GetHeaderByNumber(number uint64) *types.Header {
367-
hash := GetHashByNumber(self.chainDb, number)
372+
hash := GetCanonicalHash(self.chainDb, number)
368373
if hash == (common.Hash{}) {
369374
return nil
370375
}
371376
return self.GetHeader(hash)
372377
}
373378

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+
// GetBody retrieves a block body (transactions and uncles) from the database by
380+
// hash, caching it if found.
381+
func (self *ChainManager) GetBody(hash common.Hash) *types.Body {
379382
// Short circuit if the body's already in the cache, retrieve otherwise
380383
if cached, ok := self.bodyCache.Get(hash); ok {
381-
body := cached.(*storageBody)
382-
return &body.Transactions, &body.Uncles
384+
body := cached.(*types.Body)
385+
return body
383386
}
384-
transactions, uncles, td := GetBodyByHash(self.chainDb, hash)
385-
if td == nil {
386-
return nil, nil
387+
body := GetBody(self.chainDb, hash)
388+
if body == nil {
389+
return nil
387390
}
388391
// 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
392+
self.bodyCache.Add(hash, body)
393+
return body
394394
}
395395

396396
// GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
397397
// caching it if found.
398-
func (self *ChainManager) GetBodyRLP(hash common.Hash) []byte {
398+
func (self *ChainManager) GetBodyRLP(hash common.Hash) rlp.RawValue {
399399
// Short circuit if the body's already in the cache, retrieve otherwise
400400
if cached, ok := self.bodyRLPCache.Get(hash); ok {
401-
return cached.([]byte)
401+
return cached.(rlp.RawValue)
402402
}
403-
body, td := GetBodyRLPByHash(self.chainDb, hash)
404-
if td == nil {
403+
body := GetBodyRLP(self.chainDb, hash)
404+
if len(body) == 0 {
405405
return nil
406406
}
407407
// Cache the found body for next time and return
408408
self.bodyRLPCache.Add(hash, body)
409409
return body
410410
}
411411

412+
// GetTd retrieves a block's total difficulty in the canonical chain from the
413+
// database by hash, caching it if found.
414+
func (self *ChainManager) GetTd(hash common.Hash) *big.Int {
415+
// Short circuit if the td's already in the cache, retrieve otherwise
416+
if cached, ok := self.tdCache.Get(hash); ok {
417+
return cached.(*big.Int)
418+
}
419+
td := GetTd(self.chainDb, hash)
420+
if td == nil {
421+
return nil
422+
}
423+
// Cache the found body for next time and return
424+
self.tdCache.Add(hash, td)
425+
return td
426+
}
427+
412428
// HasBlock checks if a block is fully present in the database or not, caching
413429
// it if present.
414430
func (bc *ChainManager) HasBlock(hash common.Hash) bool {
@@ -421,7 +437,7 @@ func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
421437
if block, ok := self.blockCache.Get(hash); ok {
422438
return block.(*types.Block)
423439
}
424-
block := GetBlockByHash(self.chainDb, hash)
440+
block := GetBlock(self.chainDb, hash)
425441
if block == nil {
426442
return nil
427443
}
@@ -433,7 +449,7 @@ func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
433449
// GetBlockByNumber retrieves a block from the database by number, caching it
434450
// (associated with its hash) if found.
435451
func (self *ChainManager) GetBlockByNumber(number uint64) *types.Block {
436-
hash := GetHashByNumber(self.chainDb, number)
452+
hash := GetCanonicalHash(self.chainDb, number)
437453
if hash == (common.Hash{}) {
438454
return nil
439455
}
@@ -455,7 +471,7 @@ func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) [
455471
break
456472
}
457473
chain = append(chain, header.Hash())
458-
if header.Number.Cmp(common.Big0) <= 0 {
474+
if header.Number.Cmp(common.Big0) == 0 {
459475
break
460476
}
461477
}
@@ -531,28 +547,36 @@ const (
531547
SideStatTy
532548
)
533549

534-
// WriteBlock writes the block to the chain (or pending queue)
535-
func (self *ChainManager) WriteBlock(block *types.Block, queued bool) (status writeStatus, err error) {
550+
// WriteBlock writes the block to the chain.
551+
func (self *ChainManager) WriteBlock(block *types.Block) (status writeStatus, err error) {
536552
self.wg.Add(1)
537553
defer self.wg.Done()
538554

555+
// Calculate the total difficulty of the block
556+
ptd := self.GetTd(block.ParentHash())
557+
if ptd == nil {
558+
return NonStatTy, ParentError(block.ParentHash())
559+
}
560+
td := new(big.Int).Add(block.Difficulty(), ptd)
561+
562+
self.mu.RLock()
539563
cblock := self.currentBlock
564+
self.mu.RUnlock()
565+
540566
// Compare the TD of the last known block in the canonical chain to make sure it's greater.
541567
// At this point it's possible that a different chain (fork) becomes the new canonical chain.
542-
if block.Td.Cmp(self.Td()) > 0 {
568+
if td.Cmp(self.Td()) > 0 {
543569
// chain fork
544570
if block.ParentHash() != cblock.Hash() {
545571
// during split we merge two different chains and create the new canonical chain
546572
err := self.merge(cblock, block)
547573
if err != nil {
548574
return NonStatTy, err
549575
}
550-
551576
status = SplitStatTy
552577
}
553-
554578
self.mu.Lock()
555-
self.setTotalDifficulty(block.Td)
579+
self.setTotalDifficulty(td)
556580
self.insert(block)
557581
self.mu.Unlock()
558582

@@ -561,9 +585,11 @@ func (self *ChainManager) WriteBlock(block *types.Block, queued bool) (status wr
561585
status = SideStatTy
562586
}
563587

564-
err = WriteBlock(self.chainDb, block)
565-
if err != nil {
566-
glog.Fatalln("db err:", err)
588+
if err := WriteTd(self.chainDb, block.Hash(), td); err != nil {
589+
glog.Fatalf("failed to write block total difficulty: %v", err)
590+
}
591+
if err := WriteBlock(self.chainDb, block); err != nil {
592+
glog.Fatalf("filed to write block contents: %v", err)
567593
}
568594
// Delete from future blocks
569595
self.futureBlocks.Remove(block.Hash())
@@ -622,11 +648,6 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
622648
blockErr(block, err)
623649
return i, err
624650
}
625-
626-
// Setting block.Td regardless of error (known for example) prevents errors down the line
627-
// in the protocol handler
628-
block.Td = new(big.Int).Set(CalcTD(block, self.GetBlock(block.ParentHash())))
629-
630651
// Call in to the block processor and check for errors. It's likely that if one block fails
631652
// all others will fail too (unless a known block is returned).
632653
logs, receipts, err := self.processor.Process(block)
@@ -666,7 +687,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
666687
txcount += len(block.Transactions())
667688

668689
// write the block to the chain and get the status
669-
status, err := self.WriteBlock(block, true)
690+
status, err := self.WriteBlock(block)
670691
if err != nil {
671692
return i, err
672693
}
@@ -799,12 +820,11 @@ out:
799820
case ChainEvent:
800821
// We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
801822
// and in most cases isn't even necessary.
802-
if self.lastBlockHash == event.Hash {
823+
if self.currentBlock.Hash() == event.Hash {
803824
self.currentGasLimit = CalcGasLimit(event.Block)
804825
self.eventMux.Post(ChainHeadEvent{event.Block})
805826
}
806827
}
807-
808828
self.eventMux.Post(event)
809829
}
810830
}

0 commit comments

Comments
 (0)