Skip to content

Commit

Permalink
Reorder the db WriteBlock codes to reduce the harm of partial-write (#52
Browse files Browse the repository at this point in the history
)
  • Loading branch information
DarianShawn authored May 23, 2022
1 parent 88dc515 commit 82b6abb
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,12 +688,6 @@ func (b *Blockchain) WriteBlock(block *types.Block) error {
return err
}

// Write the header to the chain
evnt := &Event{}
if err := b.writeHeaderImpl(evnt, header); err != nil {
return err
}

// write the receipts, do it only after the header has been written.
// Otherwise, a client might ask for a header once the receipt is valid
// but before it is written into the storage
Expand All @@ -706,6 +700,12 @@ func (b *Blockchain) WriteBlock(block *types.Block) error {
return err
}

// Write the header to the chain
evnt := &Event{}
if err := b.writeHeaderImpl(evnt, header); err != nil {
return err
}

b.dispatchEvent(evnt)

// Update the average gas price
Expand Down Expand Up @@ -915,16 +915,6 @@ func (b *Blockchain) dispatchEvent(evnt *Event) {
func (b *Blockchain) writeHeaderImpl(evnt *Event, header *types.Header) error {
currentHeader := b.Header()

// Write the data
if header.ParentHash == currentHeader.Hash {
// Fast path to save the new canonical header
return b.writeCanonicalHeader(evnt, header)
}

if err := b.db.WriteHeader(header); err != nil {
return err
}

currentTD, ok := b.readTotalDifficulty(currentHeader.Hash)
if !ok {
panic("failed to get header difficulty")
Expand All @@ -951,6 +941,17 @@ func (b *Blockchain) writeHeaderImpl(evnt *Event, header *types.Header) error {
return err
}

// Write header
if err := b.db.WriteHeader(header); err != nil {
return err
}

// Write canonical header
if header.ParentHash == currentHeader.Hash {
// Fast path to save the new canonical header
return b.writeCanonicalHeader(evnt, header)
}

// Update the headers cache
b.headersCache.Add(header.Hash, header)

Expand Down

0 comments on commit 82b6abb

Please sign in to comment.