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"
|
2019-10-03 16:33:16 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/hashutil"
|
2019-09-29 18:48:55 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/traceutil"
|
|
|
|
"go.opencensus.io/trace"
|
2019-08-18 04:32:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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-09-29 18:48:55 +00:00
|
|
|
ctx, span := trace.StartSpan(ctx, "p2p.Broadcast")
|
|
|
|
defer span.End()
|
2019-08-18 04:32:39 +00:00
|
|
|
topic, ok := GossipTypeMapping[reflect.TypeOf(msg)]
|
|
|
|
if !ok {
|
2019-09-29 18:48:55 +00:00
|
|
|
traceutil.AnnotateError(span, ErrMessageNotMapped)
|
2019-08-18 04:32:39 +00:00
|
|
|
return ErrMessageNotMapped
|
|
|
|
}
|
2019-09-29 18:48:55 +00:00
|
|
|
span.AddAttributes(trace.StringAttribute("topic", topic))
|
2019-08-18 04:32:39 +00:00
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if _, err := s.Encoding().Encode(buf, msg); err != nil {
|
2019-09-29 18:48:55 +00:00
|
|
|
err := errors.Wrap(err, "could not encode message")
|
|
|
|
traceutil.AnnotateError(span, err)
|
|
|
|
return err
|
2019-08-18 04:32:39 +00:00
|
|
|
}
|
|
|
|
|
2019-10-03 16:33:16 +00:00
|
|
|
if span.IsRecordingEvents() {
|
|
|
|
id := hashutil.FastSum64(buf.Bytes())
|
|
|
|
messageLen := int64(buf.Len())
|
|
|
|
span.AddMessageSendEvent(int64(id), messageLen /*uncompressed*/, messageLen /*compressed*/)
|
|
|
|
}
|
|
|
|
|
2019-08-18 04:32:39 +00:00
|
|
|
if err := s.pubsub.Publish(topic+s.Encoding().ProtocolSuffix(), buf.Bytes()); err != nil {
|
2019-09-29 18:48:55 +00:00
|
|
|
err := errors.Wrap(err, "could not publish message")
|
|
|
|
traceutil.AnnotateError(span, err)
|
|
|
|
return err
|
2019-08-18 04:32:39 +00:00
|
|
|
}
|
|
|
|
return nil
|
2019-08-16 17:13:04 +00:00
|
|
|
}
|