github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/sync/context.go (about)

     1  package sync
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/libp2p/go-libp2p-core/network"
     7  	"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
     8  	"github.com/prysmaticlabs/prysm/beacon-chain/p2p"
     9  )
    10  
    11  // writes peer's current context for the expected payload to the stream.
    12  func writeContextToStream(stream network.Stream, chain blockchain.ChainInfoFetcher) error {
    13  	rpcCtx, err := rpcContext(stream, chain)
    14  	if err != nil {
    15  		return err
    16  	}
    17  	// Exit early if there is an empty context.
    18  	if len(rpcCtx) == 0 {
    19  		return nil
    20  	}
    21  	_, err = stream.Write(rpcCtx)
    22  	return err
    23  }
    24  
    25  // reads any attached context-bytes to the payload.
    26  func readContextFromStream(stream network.Stream, chain blockchain.ChainInfoFetcher) ([]byte, error) {
    27  	rpcCtx, err := rpcContext(stream, chain)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	if len(rpcCtx) == 0 {
    32  		return []byte{}, nil
    33  	}
    34  	// Read context (fork-digest) from stream
    35  	b := make([]byte, 4)
    36  	if _, err := stream.Read(b); err != nil {
    37  		return nil, err
    38  	}
    39  	return b, nil
    40  }
    41  
    42  // retrieve expected context depending on rpc topic schema version.
    43  func rpcContext(stream network.Stream, chain blockchain.ChainInfoFetcher) ([]byte, error) {
    44  	_, _, version, err := p2p.TopicDeconstructor(string(stream.Protocol()))
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	switch version {
    49  	case p2p.SchemaVersionV1:
    50  		// Return empty context for a v1 method.
    51  		return []byte{}, nil
    52  	default:
    53  		return nil, errors.New("invalid version of %s registered for topic: %s")
    54  	}
    55  }