diff --git a/beacon-chain/sync/initial-sync/service.go b/beacon-chain/sync/initial-sync/service.go index d25ef8400..d659639f5 100644 --- a/beacon-chain/sync/initial-sync/service.go +++ b/beacon-chain/sync/initial-sync/service.go @@ -80,7 +80,17 @@ func (s *Service) Start() { // Wait for state to be initialized. stateChannel := make(chan *feed.Event, 1) stateSub := s.stateNotifier.StateFeed().Subscribe(stateChannel) - for genesisSet := false; !genesisSet; { + // We have two instances in which we call unsubscribe. The first + // instance below is to account for the fact that we exit + // the for-select loop through a return when we receive a closed + // context or error from our subscription. The only way to correctly + // close the subscription would be through a defer. The second instance we + // call unsubscribe when we have already received the state + // initialized event and are proceeding with the main synchronization + // routine. + defer stateSub.Unsubscribe() + genesisSet := false + for !genesisSet { select { case event := <-stateChannel: if event.Type == statefeed.Initialized { @@ -95,10 +105,10 @@ func (s *Service) Start() { } case <-s.ctx.Done(): log.Debug("Context closed, exiting goroutine") - break + return case err := <-stateSub.Err(): log.WithError(err).Error("Subscription to state notifier failed") - break + return } } stateSub.Unsubscribe()