@@ -22,6 +22,8 @@ import (
2222 "fmt"
2323 "io"
2424 "math/big"
25+ "math/rand"
26+ "runtime"
2527 "sync"
2628 "sync/atomic"
2729 "time"
@@ -671,7 +673,7 @@ func (self *BlockChain) writeHeader(header *types.Header) error {
671673// should be done or not. The reason behind the optional check is because some
672674// of the header retrieval mechanisms already need to verfy nonces, as well as
673675// because nonces can be verified sparsely, not needing to check each.
674- func (self * BlockChain ) InsertHeaderChain (chain []* types.Header , verify bool ) (int , error ) {
676+ func (self * BlockChain ) InsertHeaderChain (chain []* types.Header , checkFreq int ) (int , error ) {
675677 self .wg .Add (1 )
676678 defer self .wg .Done ()
677679
@@ -683,16 +685,85 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, verify bool) (i
683685 stats := struct { processed , ignored int }{}
684686 start := time .Now ()
685687
686- // Start the parallel nonce verifier, with a fake nonce if not requested
687- verifier := self .pow
688- if ! verify {
689- verifier = FakePow {}
688+ // Generate the list of headers that should be POW verified
689+ verify := make ([]bool , len (chain ))
690+ for i := 0 ; i < len (verify )/ checkFreq ; i ++ {
691+ index := i * checkFreq + rand .Intn (checkFreq )
692+ if index >= len (verify ) {
693+ index = len (verify ) - 1
694+ }
695+ verify [index ] = true
690696 }
691- nonceAbort , nonceResults := verifyNoncesFromHeaders (verifier , chain )
692- defer close (nonceAbort )
697+ verify [len (verify )- 1 ] = true // Last should always be verified to avoid junk
698+
699+ // Create the header verification task queue and worker functions
700+ tasks := make (chan int , len (chain ))
701+ for i := 0 ; i < len (chain ); i ++ {
702+ tasks <- i
703+ }
704+ close (tasks )
693705
694- // Iterate over the headers, inserting any new ones
695- complete := make ([]bool , len (chain ))
706+ errs , failed := make ([]error , len (tasks )), int32 (0 )
707+ process := func (worker int ) {
708+ for index := range tasks {
709+ header , hash := chain [index ], chain [index ].Hash ()
710+
711+ // Short circuit insertion if shutting down or processing failed
712+ if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
713+ return
714+ }
715+ if atomic .LoadInt32 (& failed ) > 0 {
716+ return
717+ }
718+ // Short circuit if the header is bad or already known
719+ if BadHashes [hash ] {
720+ errs [index ] = BadHashError (hash )
721+ atomic .AddInt32 (& failed , 1 )
722+ return
723+ }
724+ if self .HasHeader (hash ) {
725+ continue
726+ }
727+ // Verify that the header honors the chain parameters
728+ checkPow := verify [index ]
729+
730+ var err error
731+ if index == 0 {
732+ err = self .processor .ValidateHeader (header , checkPow , false )
733+ } else {
734+ err = self .processor .ValidateHeaderWithParent (header , chain [index - 1 ], checkPow , false )
735+ }
736+ if err != nil {
737+ errs [index ] = err
738+ atomic .AddInt32 (& failed , 1 )
739+ return
740+ }
741+ }
742+ }
743+ // Start as many worker threads as goroutines allowed
744+ pending := new (sync.WaitGroup )
745+ for i := 0 ; i < runtime .GOMAXPROCS (0 ); i ++ {
746+ pending .Add (1 )
747+ go func (id int ) {
748+ defer pending .Done ()
749+ process (id )
750+ }(i )
751+ }
752+ pending .Wait ()
753+
754+ // If anything failed, report
755+ if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
756+ glog .V (logger .Debug ).Infoln ("premature abort during receipt chain processing" )
757+ return 0 , nil
758+ }
759+ if failed > 0 {
760+ for i , err := range errs {
761+ if err != nil {
762+ return i , err
763+ }
764+ }
765+ }
766+ // All headers passed verification, import them into the database
696767 for i , header := range chain {
697768 // Short circuit insertion if shutting down
698769 if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
@@ -701,24 +772,7 @@ func (self *BlockChain) InsertHeaderChain(chain []*types.Header, verify bool) (i
701772 }
702773 hash := header .Hash ()
703774
704- // Accumulate verification results until the next header is verified
705- for ! complete [i ] {
706- if res := <- nonceResults ; res .valid {
707- complete [res .index ] = true
708- } else {
709- header := chain [res .index ]
710- return res .index , & BlockNonceErr {
711- Hash : header .Hash (),
712- Number : new (big.Int ).Set (header .Number ),
713- Nonce : header .Nonce .Uint64 (),
714- }
715- }
716- }
717- if BadHashes [hash ] {
718- glog .V (logger .Error ).Infof ("bad header %d [%x…], known bad hash" , header .Number , hash )
719- return i , BadHashError (hash )
720- }
721- // Write the header to the chain and get the status
775+ // If the header's already known, skip it, otherwise store
722776 if self .HasHeader (hash ) {
723777 stats .ignored ++
724778 continue
@@ -743,76 +797,116 @@ func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain
743797 defer self .wg .Done ()
744798
745799 // Collect some import statistics to report on
746- stats := struct { processed , ignored int }{}
800+ stats := struct { processed , ignored int32 }{}
747801 start := time .Now ()
748802
749- // Iterate over the blocks and receipts, inserting any new ones
803+ // Create the block importing task queue and worker functions
804+ tasks := make (chan int , len (blockChain ))
750805 for i := 0 ; i < len (blockChain ) && i < len (receiptChain ); i ++ {
751- block , receipts := blockChain [i ], receiptChain [i ]
806+ tasks <- i
807+ }
808+ close (tasks )
752809
753- // Short circuit insertion if shutting down
754- if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
755- glog .V (logger .Debug ).Infoln ("premature abort during receipt chain processing" )
756- break
757- }
758- // Short circuit if the owner header is unknown
759- if ! self .HasHeader (block .Hash ()) {
760- glog .V (logger .Debug ).Infof ("containing header #%d [%x…] unknown" , block .Number (), block .Hash ().Bytes ()[:4 ])
761- return i , fmt .Errorf ("containing header #%d [%x…] unknown" , block .Number (), block .Hash ().Bytes ()[:4 ])
762- }
763- // Skip if the entire data is already known
764- if self .HasBlock (block .Hash ()) {
765- stats .ignored ++
766- continue
767- }
768- // Compute all the non-consensus fields of the receipts
769- transactions , logIndex := block .Transactions (), uint (0 )
770- for j := 0 ; j < len (receipts ); j ++ {
771- // The transaction hash can be retrieved from the transaction itself
772- receipts [j ].TxHash = transactions [j ].Hash ()
773-
774- // The contract address can be derived from the transaction itself
775- if MessageCreatesContract (transactions [j ]) {
776- from , _ := transactions [j ].From ()
777- receipts [j ].ContractAddress = crypto .CreateAddress (from , transactions [j ].Nonce ())
810+ errs , failed := make ([]error , len (tasks )), int32 (0 )
811+ process := func (worker int ) {
812+ for index := range tasks {
813+ block , receipts := blockChain [index ], receiptChain [index ]
814+
815+ // Short circuit insertion if shutting down or processing failed
816+ if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
817+ return
778818 }
779- // The used gas can be calculated based on previous receipts
780- if j == 0 {
781- receipts [j ].GasUsed = new (big.Int ).Set (receipts [j ].CumulativeGasUsed )
782- } else {
783- receipts [j ].GasUsed = new (big.Int ).Sub (receipts [j ].CumulativeGasUsed , receipts [j - 1 ].CumulativeGasUsed )
819+ if atomic .LoadInt32 (& failed ) > 0 {
820+ return
784821 }
785- // The derived log fields can simply be set from the block and transaction
786- for k := 0 ; k < len (receipts [j ].Logs ); k ++ {
787- receipts [j ].Logs [k ].BlockNumber = block .NumberU64 ()
788- receipts [j ].Logs [k ].BlockHash = block .Hash ()
789- receipts [j ].Logs [k ].TxHash = receipts [j ].TxHash
790- receipts [j ].Logs [k ].TxIndex = uint (j )
791- receipts [j ].Logs [k ].Index = logIndex
792- logIndex ++
822+ // Short circuit if the owner header is unknown
823+ if ! self .HasHeader (block .Hash ()) {
824+ errs [index ] = fmt .Errorf ("containing header #%d [%x…] unknown" , block .Number (), block .Hash ().Bytes ()[:4 ])
825+ atomic .AddInt32 (& failed , 1 )
826+ return
793827 }
828+ // Skip if the entire data is already known
829+ if self .HasBlock (block .Hash ()) {
830+ atomic .AddInt32 (& stats .ignored , 1 )
831+ continue
832+ }
833+ // Compute all the non-consensus fields of the receipts
834+ transactions , logIndex := block .Transactions (), uint (0 )
835+ for j := 0 ; j < len (receipts ); j ++ {
836+ // The transaction hash can be retrieved from the transaction itself
837+ receipts [j ].TxHash = transactions [j ].Hash ()
838+
839+ // The contract address can be derived from the transaction itself
840+ if MessageCreatesContract (transactions [j ]) {
841+ from , _ := transactions [j ].From ()
842+ receipts [j ].ContractAddress = crypto .CreateAddress (from , transactions [j ].Nonce ())
843+ }
844+ // The used gas can be calculated based on previous receipts
845+ if j == 0 {
846+ receipts [j ].GasUsed = new (big.Int ).Set (receipts [j ].CumulativeGasUsed )
847+ } else {
848+ receipts [j ].GasUsed = new (big.Int ).Sub (receipts [j ].CumulativeGasUsed , receipts [j - 1 ].CumulativeGasUsed )
849+ }
850+ // The derived log fields can simply be set from the block and transaction
851+ for k := 0 ; k < len (receipts [j ].Logs ); k ++ {
852+ receipts [j ].Logs [k ].BlockNumber = block .NumberU64 ()
853+ receipts [j ].Logs [k ].BlockHash = block .Hash ()
854+ receipts [j ].Logs [k ].TxHash = receipts [j ].TxHash
855+ receipts [j ].Logs [k ].TxIndex = uint (j )
856+ receipts [j ].Logs [k ].Index = logIndex
857+ logIndex ++
858+ }
859+ }
860+ // Write all the data out into the database
861+ if err := WriteBody (self .chainDb , block .Hash (), & types.Body {block .Transactions (), block .Uncles ()}); err != nil {
862+ errs [index ] = fmt .Errorf ("failed to write block body: %v" , err )
863+ atomic .AddInt32 (& failed , 1 )
864+ glog .Fatal (errs [index ])
865+ return
866+ }
867+ if err := PutBlockReceipts (self .chainDb , block .Hash (), receipts ); err != nil {
868+ errs [index ] = fmt .Errorf ("failed to write block receipts: %v" , err )
869+ atomic .AddInt32 (& failed , 1 )
870+ glog .Fatal (errs [index ])
871+ return
872+ }
873+ atomic .AddInt32 (& stats .processed , 1 )
794874 }
795- // Write all the data out into the database
796- if err := WriteBody (self .chainDb , block .Hash (), & types.Body {block .Transactions (), block .Uncles ()}); err != nil {
797- glog .Fatalf ("failed to write block body: %v" , err )
798- return i , err
799- }
800- if err := PutBlockReceipts (self .chainDb , block .Hash (), receipts ); err != nil {
801- glog .Fatalf ("failed to write block receipts: %v" , err )
802- return i , err
803- }
804- // Update the head fast sync block if better
805- self .mu .Lock ()
806- if self .GetTd (self .currentFastBlock .Hash ()).Cmp (self .GetTd (block .Hash ())) < 0 {
807- if err := WriteHeadFastBlockHash (self .chainDb , block .Hash ()); err != nil {
808- glog .Fatalf ("failed to update head fast block hash: %v" , err )
875+ }
876+ // Start as many worker threads as goroutines allowed
877+ pending := new (sync.WaitGroup )
878+ for i := 0 ; i < runtime .GOMAXPROCS (0 ); i ++ {
879+ pending .Add (1 )
880+ go func (id int ) {
881+ defer pending .Done ()
882+ process (id )
883+ }(i )
884+ }
885+ pending .Wait ()
886+
887+ // If anything failed, report
888+ if atomic .LoadInt32 (& self .procInterrupt ) == 1 {
889+ glog .V (logger .Debug ).Infoln ("premature abort during receipt chain processing" )
890+ return 0 , nil
891+ }
892+ if failed > 0 {
893+ for i , err := range errs {
894+ if err != nil {
895+ return i , err
809896 }
810- self .currentFastBlock = block
811897 }
812- self .mu .Unlock ()
813-
814- stats .processed ++
815898 }
899+ // Update the head fast sync block if better
900+ self .mu .Lock ()
901+ head := blockChain [len (errs )- 1 ]
902+ if self .GetTd (self .currentFastBlock .Hash ()).Cmp (self .GetTd (head .Hash ())) < 0 {
903+ if err := WriteHeadFastBlockHash (self .chainDb , head .Hash ()); err != nil {
904+ glog .Fatalf ("failed to update head fast block hash: %v" , err )
905+ }
906+ self .currentFastBlock = head
907+ }
908+ self .mu .Unlock ()
909+
816910 // Report some public statistics so the user has a clue what's going on
817911 first , last := blockChain [0 ], blockChain [len (blockChain )- 1 ]
818912 glog .V (logger .Info ).Infof ("imported %d receipt(s) (%d ignored) in %v. #%d [%x… / %x…]" , stats .processed , stats .ignored ,
0 commit comments