From ba4cd3793230a12fcffc2b484b9fa7736c3ff323 Mon Sep 17 00:00:00 2001 From: DarianShawn Date: Fri, 20 May 2022 11:37:57 +0800 Subject: [PATCH] Reorder the db WriteBlock codes to reduce the harm of partial-write --- blockchain/blockchain.go | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 35461eacbb..d2a005cf94 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -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 @@ -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 @@ -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") @@ -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)