github.com/amazechain/amc@v0.1.3/internal/sync/decode_pubsub.go (about) 1 package sync 2 3 import ( 4 "github.com/amazechain/amc/internal/p2p" 5 "strings" 6 7 pubsub "github.com/libp2p/go-libp2p-pubsub" 8 "github.com/pkg/errors" 9 ssz "github.com/prysmaticlabs/fastssz" 10 "google.golang.org/protobuf/proto" 11 ) 12 13 var errNilPubsubMessage = errors.New("nil pubsub message") 14 var errInvalidTopic = errors.New("invalid topic format") 15 16 func (s *Service) decodePubsubMessage(msg *pubsub.Message) (ssz.Unmarshaler, error) { 17 if msg == nil || msg.Topic == nil || *msg.Topic == "" { 18 return nil, errNilPubsubMessage 19 } 20 topic := *msg.Topic 21 //todo 22 _, err := p2p.ExtractGossipDigest(topic) 23 if err != nil { 24 return nil, errors.Wrapf(err, "extraction failed for topic: %s", topic) 25 } 26 topic = strings.TrimSuffix(topic, s.cfg.p2p.Encoding().ProtocolSuffix()) 27 topic, err = s.replaceForkDigest(topic) 28 if err != nil { 29 return nil, err 30 } 31 32 base := p2p.GossipTopicMappings(topic) 33 if base == nil { 34 return nil, p2p.ErrMessageNotMapped 35 } 36 m, ok := proto.Clone(base).(ssz.Unmarshaler) 37 if !ok { 38 return nil, errors.Errorf("message of %T does not support marshaller interface", base) 39 } 40 41 if err := s.cfg.p2p.Encoding().DecodeGossip(msg.Data, m); err != nil { 42 return nil, err 43 } 44 return m, nil 45 } 46 47 // Replaces our fork digest with the formatter. 48 func (_ *Service) replaceForkDigest(topic string) (string, error) { 49 subStrings := strings.Split(topic, "/") 50 if len(subStrings) != 4 { 51 return "", errInvalidTopic 52 } 53 subStrings[2] = "%x" 54 return strings.Join(subStrings, "/"), nil 55 }