// Find and establish sessions with a fixed number of peers to download the latest state from.
Find and establish sessions with a fixed number of peers to download the latest state from.
// Find and establish sessions with a fixed number of peers to download the latest state from .
func (s *SyncManager) findPeersToDownloadStateFrom(numPeers int) ([]syncPeer, error) {
	sessions := make([]syncPeer, 0, numPeers)
	sessionsLock := sync.Mutex{}
	peers, err := SelectPeers(s.client.ClosestPeers(), numPeers)
	if err != nil {
		s.logger.Warn().
			Msg("It looks like there are no peers for us to download state from. Retrying after 1 second...")
		s.wait(1 * time.Second)
		if s.closed() {
			return nil, nil
		}
		return nil, errors.New("no peers for us to sync with")
	}
	height := s.blocks.LatestHeight()
	req := &SyncRequest{Data: &SyncRequest_BlockId{BlockId: height}}
	var wg sync.WaitGroup
	wg.Add(len(peers))
	for _, p := range peers {
		go func(peer skademlia.ClosestPeer) {
			defer wg.Done()
			stream, err := NewWaveletClient(peer.Conn()).Sync(context.Background())
			if err != nil {
				return
			}
			block, checksums, err := s.askForLatestStateDetails(stream, height, req)
			if err != nil {
				return
			}
			sessionsLock.Lock()
			defer sessionsLock.Unlock()
			sessions = append(sessions, syncPeer{peer: peer, stream: stream, block: block, checksums: checksums})
		}(p)
	}
	wg.Wait()
	if len(sessions) < numPeers {
		return nil, errors.Errorf(
			"got %d sessions established but require a minimum of %d sessions to sync",
			len(sessions),
			numPeers,
		)
	}
	return sessions, nil
}
func ( s * SyncManager ) findPeersToDownloadStateFrom ( numPeers int ) ( [ ] syncPeer , error ) { sessions := make ( [ ] syncPeer , 0 , numPeers ) sessionsLock := sync . Mutex { } peers , err := SelectPeers ( s . client . ClosestPeers ( ) , numPeers ) if err != nil { s . logger . Warn ( ) . Msg ( " " ) s . wait ( 1 * time . Second ) if s . closed ( ) { return nil , nil } return nil , errors . New ( " " ) } height := s . blocks . LatestHeight ( ) req := & SyncRequest { Data : & SyncRequest_BlockId { BlockId : height } } var wg sync . WaitGroup wg . Add ( len ( peers ) ) for _ , p := range peers { go func ( peer skademlia . ClosestPeer ) { defer wg . Done ( ) stream , err := NewWaveletClient ( peer . Conn ( ) ) . Sync ( context . Background ( ) ) if err != nil { return } block , checksums , err := s . askForLatestStateDetails ( stream , height , req ) if err != nil { return } sessionsLock . Lock ( ) defer sessionsLock . Unlock ( ) sessions = append ( sessions , syncPeer { peer : peer , stream : stream , block : block , checksums : checksums } ) } ( p ) } wg . Wait ( ) if len ( sessions ) < numPeers { return nil , errors . Errorf ( " " , len ( sessions ) , numPeers , ) } return sessions , nil }
Find and establish sessions with a fixed number of peers to download the latest state from.
Find and establish sessions with a fixed number of peers to download the latest state from .