github.com/amazechain/amc@v0.1.3/internal/sync/context.go (about) 1 package sync 2 3 import ( 4 "github.com/amazechain/amc/common" 5 "github.com/amazechain/amc/internal/p2p" 6 "github.com/libp2p/go-libp2p/core/network" 7 "github.com/libp2p/go-libp2p/core/protocol" 8 "github.com/pkg/errors" 9 ) 10 11 // Specifies the fixed size context length. 12 const forkDigestLength = 4 13 14 // writes peer's current context for the expected payload to the stream. 15 func writeContextToStream(objCtx []byte, stream network.Stream, chain common.IBlockChain) error { 16 _, err := stream.Write(objCtx) 17 return err 18 } 19 20 // reads any attached context-bytes to the payload. 21 func readContextFromStream(stream network.Stream) ([]byte, error) { 22 // Read context (fork-digest) from stream 23 b := make([]byte, forkDigestLength) 24 if _, err := stream.Read(b); err != nil { 25 return nil, err 26 } 27 return b, nil 28 } 29 30 // retrieve expected context depending on rpc topic schema version. 31 func rpcContext(stream network.Stream, chain common.IBlockChain) ([]byte, error) { 32 _, _, version, err := p2p.TopicDeconstructor(string(stream.Protocol())) 33 if err != nil { 34 return nil, err 35 } 36 switch version { 37 case p2p.SchemaVersionV1: 38 // Return empty context for a v1 method. 39 return []byte{}, nil 40 default: 41 return nil, errors.New("invalid version of %s registered for topic: %s") 42 } 43 } 44 45 // Minimal interface for a stream with a protocol. 46 type withProtocol interface { 47 Protocol() protocol.ID 48 } 49 50 // Validates that the rpc topic matches the provided version. 51 func validateVersion(version string, stream withProtocol) error { 52 _, _, streamVersion, err := p2p.TopicDeconstructor(string(stream.Protocol())) 53 if err != nil { 54 return err 55 } 56 if streamVersion != version { 57 return errors.Errorf("stream version of %s doesn't match provided version %s", streamVersion, version) 58 } 59 return nil 60 }