2019-08-16 17:13:04 +00:00
|
|
|
package p2p
|
|
|
|
|
2019-08-18 04:32:39 +00:00
|
|
|
import (
|
|
|
|
"bytes"
|
2019-08-19 21:20:56 +00:00
|
|
|
"context"
|
2019-08-18 04:32:39 +00:00
|
|
|
"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")
|
2019-08-16 17:13:04 +00:00
|
|
|
|
|
|
|
// Broadcast a message to the p2p network.
|
2019-08-19 21:20:56 +00:00
|
|
|
func (s *Service) Broadcast(ctx context.Context, msg proto.Message) error {
|
2019-08-18 04:32:39 +00:00
|
|
|
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
|
2019-08-16 17:13:04 +00:00
|
|
|
}
|