github.com/ethersphere/bee/v2@v2.2.0/pkg/p2p/libp2p/headers.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package libp2p 6 7 import ( 8 "context" 9 "fmt" 10 11 "github.com/ethersphere/bee/v2/pkg/p2p" 12 "github.com/ethersphere/bee/v2/pkg/p2p/libp2p/internal/headers/pb" 13 "github.com/ethersphere/bee/v2/pkg/p2p/protobuf" 14 "github.com/ethersphere/bee/v2/pkg/swarm" 15 ) 16 17 func sendHeaders(ctx context.Context, headers p2p.Headers, stream *stream) error { 18 w, r := protobuf.NewWriterAndReader(stream) 19 20 if err := w.WriteMsgWithContext(ctx, headersP2PToPB(headers)); err != nil { 21 return fmt.Errorf("write message: %w", err) 22 } 23 24 h := new(pb.Headers) 25 if err := r.ReadMsgWithContext(ctx, h); err != nil { 26 return fmt.Errorf("read message: %w", err) 27 } 28 29 stream.headers = headersPBToP2P(h) 30 31 return nil 32 } 33 34 func handleHeaders(ctx context.Context, headler p2p.HeadlerFunc, stream *stream, peerAddress swarm.Address) error { 35 w, r := protobuf.NewWriterAndReader(stream) 36 37 headers := new(pb.Headers) 38 if err := r.ReadMsgWithContext(ctx, headers); err != nil { 39 return fmt.Errorf("read message: %w", err) 40 } 41 42 stream.headers = headersPBToP2P(headers) 43 44 var h p2p.Headers 45 if headler != nil { 46 h = headler(stream.headers, peerAddress) 47 } 48 49 stream.responseHeaders = h 50 51 if err := w.WriteMsgWithContext(ctx, headersP2PToPB(h)); err != nil { 52 return fmt.Errorf("write message: %w", err) 53 } 54 return nil 55 } 56 57 func headersPBToP2P(h *pb.Headers) p2p.Headers { 58 p2ph := make(p2p.Headers) 59 for _, rh := range h.Headers { 60 p2ph[rh.Key] = rh.Value 61 } 62 return p2ph 63 } 64 65 func headersP2PToPB(h p2p.Headers) *pb.Headers { 66 pbh := new(pb.Headers) 67 pbh.Headers = make([]*pb.Header, 0) 68 for key, value := range h { 69 pbh.Headers = append(pbh.Headers, &pb.Header{ 70 Key: key, 71 Value: value, 72 }) 73 } 74 return pbh 75 }