prysm-pulse/beacon-chain/p2p/broadcaster.go
Preston Van Loon b8e550b1e9
Add p2p broadcast implementation (#3226)
* add broadcaster impl

* change API so broadcast returns an error

* change API so broadcast returns an error

* add test for message not mapped

* lint msg

* lint msg
2019-08-18 00:32:39 -04:00

32 lines
809 B
Go

package p2p
import (
"bytes"
"reflect"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
)
// ErrMessageNotMapped occurs on a Broadcast attempt when a message has not been defined in the
// GossipTypeMapping.
var ErrMessageNotMapped = errors.New("message type is not mapped to a PubSub topic")
// Broadcast a message to the p2p network.
func (s *Service) Broadcast(msg proto.Message) error {
topic, ok := GossipTypeMapping[reflect.TypeOf(msg)]
if !ok {
return ErrMessageNotMapped
}
buf := new(bytes.Buffer)
if _, err := s.Encoding().Encode(buf, msg); err != nil {
return errors.Wrap(err, "could not encode message")
}
if err := s.pubsub.Publish(topic+s.Encoding().ProtocolSuffix(), buf.Bytes()); err != nil {
return errors.Wrap(err, "could not publish message")
}
return nil
}