+func (c *Chain) syncProtocolStatus(subProtocol Protocoler) error {
+ if c.bestBlockHeader.Height < subProtocol.StartHeight() {
+ return nil
+ }
+
+ protocolHeight, protocolHash, err := subProtocol.ChainStatus()
+ if err != nil {
+ return errors.Wrap(err, "failed on get sub protocol status")
+ }
+
+ if *protocolHash == c.bestBlockHeader.Hash() {
+ return nil
+ }
+
+ for !c.InMainChain(*protocolHash) {
+ block, err := c.GetBlockByHash(protocolHash)
+ if err != nil {
+ return errors.Wrap(err, subProtocol.Name(), "can't get block by hash in chain")
+ }
+
+ if err := subProtocol.DetachBlock(block); err != nil {
+ return errors.Wrap(err, subProtocol.Name(), "sub protocol detach block err")
+ }
+
+ protocolHeight, protocolHash = block.Height-1, &block.PreviousBlockHash
+ }
+
+ for height := protocolHeight + 1; height <= c.bestBlockHeader.Height; height++ {
+ block, err := c.GetBlockByHeight(height)
+ if err != nil {
+ return errors.Wrap(err, subProtocol.Name(), "can't get block by height in chain")
+ }
+
+ if err := subProtocol.ApplyBlock(block); err != nil {
+ return errors.Wrap(err, subProtocol.Name(), "sub protocol apply block err")
+ }
+
+ blockHash := block.Hash()
+ protocolHeight, protocolHash = block.Height, &blockHash
+ }
+
+ return nil
+}
+