@@ -29,6 +29,7 @@ import (
2929 "github.com/ethereum/go-ethereum/common"
3030 "github.com/ethereum/go-ethereum/core/state"
3131 "github.com/ethereum/go-ethereum/core/types"
32+ "github.com/ethereum/go-ethereum/crypto"
3233 "github.com/ethereum/go-ethereum/ethdb"
3334 "github.com/ethereum/go-ethereum/event"
3435 "github.com/ethereum/go-ethereum/logger"
@@ -67,9 +68,10 @@ type BlockChain struct {
6768 chainmu sync.RWMutex
6869 tsmu sync.RWMutex
6970
70- checkpoint int // checkpoint counts towards the new checkpoint
71- currentHeader * types.Header // Current head of the header chain (may be above the block chain!)
72- currentBlock * types.Block // Current head of the block chain
71+ checkpoint int // checkpoint counts towards the new checkpoint
72+ currentHeader * types.Header // Current head of the header chain (may be above the block chain!)
73+ currentBlock * types.Block // Current head of the block chain
74+ currentFastBlock * types.Block // Current head of the fast-sync chain (may be above the block chain!)
7375
7476 headerCache * lru.Cache // Cache for the most recent block headers
7577 bodyCache * lru.Cache // Cache for the most recent block bodies
@@ -160,12 +162,21 @@ func (self *BlockChain) loadLastState() error {
160162 self .currentHeader = header
161163 }
162164 }
165+ // Restore the last known head fast block
166+ self .currentFastBlock = self .currentBlock
167+ if head := GetHeadFastBlockHash (self .chainDb ); head != (common.Hash {}) {
168+ if block := self .GetBlock (head ); block != nil {
169+ self .currentFastBlock = block
170+ }
171+ }
163172 // Issue a status log and return
164173 headerTd := self .GetTd (self .currentHeader .Hash ())
165174 blockTd := self .GetTd (self .currentBlock .Hash ())
175+ fastTd := self .GetTd (self .currentFastBlock .Hash ())
166176
167- glog .V (logger .Info ).Infof ("Last header: #%d [%x…] TD=%v" , self .currentHeader .Number , self .currentHeader .Hash (), headerTd )
168- glog .V (logger .Info ).Infof ("Last block: #%d [%x…] TD=%v" , self .currentBlock .Number (), self .currentBlock .Hash (), blockTd )
177+ glog .V (logger .Info ).Infof ("Last header: #%d [%x…] TD=%v" , self .currentHeader .Number , self .currentHeader .Hash ().Bytes ()[:4 ], headerTd )
178+ glog .V (logger .Info ).Infof ("Fast block: #%d [%x…] TD=%v" , self .currentFastBlock .Number (), self .currentFastBlock .Hash ().Bytes ()[:4 ], fastTd )
179+ glog .V (logger .Info ).Infof ("Last block: #%d [%x…] TD=%v" , self .currentBlock .Number (), self .currentBlock .Hash ().Bytes ()[:4 ], blockTd )
169180
170181 return nil
171182}
@@ -178,23 +189,48 @@ func (bc *BlockChain) SetHead(head uint64) {
178189 bc .mu .Lock ()
179190 defer bc .mu .Unlock ()
180191
181- // Delete everything from the current header head (is above block head)
182- for i := bc .currentHeader .Number .Uint64 (); i > head ; i -- {
183- if hash := GetCanonicalHash (bc .chainDb , i ); hash != (common.Hash {}) {
184- DeleteCanonicalHash (bc .chainDb , i )
185- DeleteHeader (bc .chainDb , hash )
186- DeleteBody (bc .chainDb , hash )
187- DeleteTd (bc .chainDb , hash )
192+ // Figure out the highest known canonical assignment
193+ height := uint64 (0 )
194+ if bc .currentHeader != nil {
195+ if hh := bc .currentHeader .Number .Uint64 (); hh > height {
196+ height = hh
188197 }
189198 }
190- bc .currentHeader = GetHeader (bc .chainDb , GetCanonicalHash (bc .chainDb , head ))
191-
192- // Rewind the block chain until a whole block is found
193- for bc .GetBlockByNumber (head ) == nil {
194- head --
199+ if bc .currentBlock != nil {
200+ if bh := bc .currentBlock .NumberU64 (); bh > height {
201+ height = bh
202+ }
195203 }
196- bc .currentBlock = bc .GetBlockByNumber (head )
204+ if bc .currentFastBlock != nil {
205+ if fbh := bc .currentFastBlock .NumberU64 (); fbh > height {
206+ height = fbh
207+ }
208+ }
209+ // Gather all the hashes that need deletion
210+ drop := make (map [common.Hash ]struct {})
197211
212+ for bc .currentHeader != nil && bc .currentHeader .Number .Uint64 () > head {
213+ drop [bc .currentHeader .Hash ()] = struct {}{}
214+ bc .currentHeader = bc .GetHeader (bc .currentHeader .ParentHash )
215+ }
216+ for bc .currentBlock != nil && bc .currentBlock .NumberU64 () > head {
217+ drop [bc .currentBlock .Hash ()] = struct {}{}
218+ bc .currentBlock = bc .GetBlock (bc .currentBlock .ParentHash ())
219+ }
220+ for bc .currentFastBlock != nil && bc .currentFastBlock .NumberU64 () > head {
221+ drop [bc .currentFastBlock .Hash ()] = struct {}{}
222+ bc .currentFastBlock = bc .GetBlock (bc .currentFastBlock .ParentHash ())
223+ }
224+ // Roll back the canonical chain numbering
225+ for i := height ; i > head ; i -- {
226+ DeleteCanonicalHash (bc .chainDb , i )
227+ }
228+ // Delete everything found by the above rewind
229+ for hash , _ := range drop {
230+ DeleteHeader (bc .chainDb , hash )
231+ DeleteBody (bc .chainDb , hash )
232+ DeleteTd (bc .chainDb , hash )
233+ }
198234 // Clear out any stale content from the caches
199235 bc .headerCache .Purge ()
200236 bc .bodyCache .Purge ()
@@ -203,6 +239,9 @@ func (bc *BlockChain) SetHead(head uint64) {
203239 bc .futureBlocks .Purge ()
204240
205241 // Update all computed fields to the new head
242+ if bc .currentBlock == nil {
243+ bc .currentBlock = bc .genesisBlock
244+ }
206245 bc .insert (bc .currentBlock )
207246 bc .loadLastState ()
208247}
@@ -222,8 +261,7 @@ func (self *BlockChain) LastBlockHash() common.Hash {
222261}
223262
224263// CurrentHeader retrieves the current head header of the canonical chain. The
225- // header is retrieved from the chain manager's internal cache, involving no
226- // database operations.
264+ // header is retrieved from the chain manager's internal cache.
227265func (self * BlockChain ) CurrentHeader () * types.Header {
228266 self .mu .RLock ()
229267 defer self .mu .RUnlock ()
@@ -232,15 +270,23 @@ func (self *BlockChain) CurrentHeader() *types.Header {
232270}
233271
234272// CurrentBlock retrieves the current head block of the canonical chain. The
235- // block is retrieved from the chain manager's internal cache, involving no
236- // database operations.
273+ // block is retrieved from the chain manager's internal cache.
237274func (self * BlockChain ) CurrentBlock () * types.Block {
238275 self .mu .RLock ()
239276 defer self .mu .RUnlock ()
240277
241278 return self .currentBlock
242279}
243280
281+ // CurrentFastBlock retrieves the current fast-sync head block of the canonical
282+ // chain. The block is retrieved from the chain manager's internal cache.
283+ func (self * BlockChain ) CurrentFastBlock () * types.Block {
284+ self .mu .RLock ()
285+ defer self .mu .RUnlock ()
286+
287+ return self .currentFastBlock
288+ }
289+
244290func (self * BlockChain ) Status () (td * big.Int , currentBlock common.Hash , genesisBlock common.Hash ) {
245291 self .mu .RLock ()
246292 defer self .mu .RUnlock ()
@@ -264,22 +310,12 @@ func (bc *BlockChain) Reset() {
264310// ResetWithGenesisBlock purges the entire blockchain, restoring it to the
265311// specified genesis state.
266312func (bc * BlockChain ) ResetWithGenesisBlock (genesis * types.Block ) {
313+ // Dump the entire block chain and purge the caches
314+ bc .SetHead (0 )
315+
267316 bc .mu .Lock ()
268317 defer bc .mu .Unlock ()
269318
270- // Dump the entire block chain and purge the caches
271- for block := bc .currentBlock ; block != nil ; block = bc .GetBlock (block .ParentHash ()) {
272- DeleteBlock (bc .chainDb , block .Hash ())
273- }
274- for header := bc .currentHeader ; header != nil ; header = bc .GetHeader (header .ParentHash ) {
275- DeleteBlock (bc .chainDb , header .Hash ())
276- }
277- bc .headerCache .Purge ()
278- bc .bodyCache .Purge ()
279- bc .bodyRLPCache .Purge ()
280- bc .blockCache .Purge ()
281- bc .futureBlocks .Purge ()
282-
283319 // Prepare the genesis block and reinitialize the chain
284320 if err := WriteTd (bc .chainDb , genesis .Hash (), genesis .Difficulty ()); err != nil {
285321 glog .Fatalf ("failed to write genesis block TD: %v" , err )
@@ -291,6 +327,7 @@ func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
291327 bc .insert (bc .genesisBlock )
292328 bc .currentBlock = bc .genesisBlock
293329 bc .currentHeader = bc .genesisBlock .Header ()
330+ bc .currentFastBlock = bc .genesisBlock
294331}
295332
296333// Export writes the active chain to the given writer.
@@ -328,8 +365,8 @@ func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
328365
329366// insert injects a new head block into the current block chain. This method
330367// assumes that the block is indeed a true head. It will also reset the head
331- // header to this very same block to prevent the headers from diverging on a
332- // different header chain.
368+ // header and the head fast sync block to this very same block to prevent them
369+ // from diverging on a different header chain.
333370//
334371// Note, this function assumes that the `mu` mutex is held!
335372func (bc * BlockChain ) insert (block * types.Block ) {
@@ -343,9 +380,13 @@ func (bc *BlockChain) insert(block *types.Block) {
343380 if err := WriteHeadHeaderHash (bc .chainDb , block .Hash ()); err != nil {
344381 glog .Fatalf ("failed to insert head header hash: %v" , err )
345382 }
383+ if err := WriteHeadFastBlockHash (bc .chainDb , block .Hash ()); err != nil {
384+ glog .Fatalf ("failed to insert head fast block hash: %v" , err )
385+ }
346386 // Update the internal state with the head block
347387 bc .currentBlock = block
348388 bc .currentHeader = block .Header ()
389+ bc .currentFastBlock = block
349390}
350391
351392// Accessors
@@ -634,7 +675,7 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, verify bool) (i
634675 for i , header := range chain {
635676 // Short circuit insertion if shutting down
636677 if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
637- glog .V (logger .Debug ).Infoln ("Premature abort during header chain processing" )
678+ glog .V (logger .Debug ).Infoln ("premature abort during header chain processing" )
638679 break
639680 }
640681 hash := header .Hash ()
@@ -653,7 +694,7 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, verify bool) (i
653694 }
654695 }
655696 if BadHashes [hash ] {
656- glog .V (logger .Error ).Infof ("Bad header %d [%x…], known bad hash" , header .Number , hash )
697+ glog .V (logger .Error ).Infof ("bad header %d [%x…], known bad hash" , header .Number , hash )
657698 return i , BadHashError (hash )
658699 }
659700 // Write the header to the chain and get the status
@@ -674,6 +715,95 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, verify bool) (i
674715 return 0 , nil
675716}
676717
718+ // InsertReceiptChain attempts to complete an already existing header chain with
719+ // transaction and receipt data.
720+ func (self * BlockChain ) InsertReceiptChain (blockChain types.Blocks , receiptChain []types.Receipts ) (int , error ) {
721+ self .wg .Add (1 )
722+ defer self .wg .Done ()
723+
724+ // Make sure only one thread manipulates the chain at once
725+ self .chainmu .Lock ()
726+ defer self .chainmu .Unlock ()
727+
728+ // Collect some import statistics to report on
729+ stats := struct { processed , ignored int }{}
730+ start := time .Now ()
731+
732+ // Iterate over the blocks and receipts, inserting any new ones
733+ for i := 0 ; i < len (blockChain ) && i < len (receiptChain ); i ++ {
734+ block , receipts := blockChain [i ], receiptChain [i ]
735+
736+ // Short circuit insertion if shutting down
737+ if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
738+ glog .V (logger .Debug ).Infoln ("premature abort during receipt chain processing" )
739+ break
740+ }
741+ // Short circuit if the owner header is unknown
742+ if ! self .HasHeader (block .Hash ()) {
743+ glog .V (logger .Debug ).Infof ("containing header #%d [%x…] unknown" , block .Number (), block .Hash ().Bytes ()[:4 ])
744+ return i , fmt .Errorf ("containing header #%d [%x…] unknown" , block .Number (), block .Hash ().Bytes ()[:4 ])
745+ }
746+ // Skip if the entire data is already known
747+ if self .HasBlock (block .Hash ()) {
748+ stats .ignored ++
749+ continue
750+ }
751+ // Compute all the non-consensus fields of the receipts
752+ transactions , logIndex := block .Transactions (), uint (0 )
753+ for j := 0 ; j < len (receipts ); j ++ {
754+ // The transaction hash can be retrieved from the transaction itself
755+ receipts [j ].TxHash = transactions [j ].Hash ()
756+
757+ // The contract address can be derived from the transaction itself
758+ if MessageCreatesContract (transactions [j ]) {
759+ from , _ := transactions [j ].From ()
760+ receipts [j ].ContractAddress = crypto .CreateAddress (from , transactions [j ].Nonce ())
761+ }
762+ // The used gas can be calculated based on previous receipts
763+ if j == 0 {
764+ receipts [j ].GasUsed = new (big.Int ).Set (receipts [j ].CumulativeGasUsed )
765+ } else {
766+ receipts [j ].GasUsed = new (big.Int ).Sub (receipts [j ].CumulativeGasUsed , receipts [j - 1 ].CumulativeGasUsed )
767+ }
768+ // The derived log fields can simply be set from the block and transaction
769+ for k := 0 ; k < len (receipts [j ].Logs ); k ++ {
770+ receipts [j ].Logs [k ].BlockNumber = block .NumberU64 ()
771+ receipts [j ].Logs [k ].BlockHash = block .Hash ()
772+ receipts [j ].Logs [k ].TxHash = receipts [j ].TxHash
773+ receipts [j ].Logs [k ].TxIndex = uint (j )
774+ receipts [j ].Logs [k ].Index = logIndex
775+ logIndex ++
776+ }
777+ }
778+ // Write all the data out into the database
779+ if err := WriteBody (self .chainDb , block .Hash (), & types.Body {block .Transactions (), block .Uncles ()}); err != nil {
780+ glog .Fatalf ("failed to write block body: %v" , err )
781+ return i , err
782+ }
783+ if err := PutBlockReceipts (self .chainDb , block .Hash (), receipts ); err != nil {
784+ glog .Fatalf ("failed to write block receipts: %v" , err )
785+ return i , err
786+ }
787+ // Update the head fast sync block if better
788+ self .mu .Lock ()
789+ if self .GetTd (self .currentFastBlock .Hash ()).Cmp (self .GetTd (block .Hash ())) < 0 {
790+ if err := WriteHeadFastBlockHash (self .chainDb , block .Hash ()); err != nil {
791+ glog .Fatalf ("failed to update head fast block hash: %v" , err )
792+ }
793+ self .currentFastBlock = block
794+ }
795+ self .mu .Unlock ()
796+
797+ stats .processed ++
798+ }
799+ // Report some public statistics so the user has a clue what's going on
800+ first , last := blockChain [0 ], blockChain [len (blockChain )- 1 ]
801+ glog .V (logger .Info ).Infof ("imported %d receipt(s) (%d ignored) in %v. #%d [%x… / %x…]" , stats .processed , stats .ignored ,
802+ time .Since (start ), last .Number (), first .Hash ().Bytes ()[:4 ], last .Hash ().Bytes ()[:4 ])
803+
804+ return 0 , nil
805+ }
806+
677807// WriteBlock writes the block to the chain.
678808func (self * BlockChain ) WriteBlock (block * types.Block ) (status writeStatus , err error ) {
679809 self .wg .Add (1 )
@@ -799,7 +929,7 @@ func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
799929
800930 return i , err
801931 }
802- if err := PutBlockReceipts (self .chainDb , block , receipts ); err != nil {
932+ if err := PutBlockReceipts (self .chainDb , block . Hash () , receipts ); err != nil {
803933 glog .V (logger .Warn ).Infoln ("error writing block receipts:" , err )
804934 }
805935
0 commit comments