github.com/celestiaorg/celestia-node@v0.15.0-beta.1/share/p2p/shrexsub/subscription.go (about)

     1  package shrexsub
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	pubsub "github.com/libp2p/go-libp2p-pubsub"
     8  
     9  	pb "github.com/celestiaorg/celestia-node/share/p2p/shrexsub/pb"
    10  )
    11  
    12  // Subscription is a wrapper over pubsub.Subscription that handles
    13  // receiving an EDS DataHash from other peers.
    14  type Subscription struct {
    15  	subscription *pubsub.Subscription
    16  }
    17  
    18  func newSubscription(t *pubsub.Topic) (*Subscription, error) {
    19  	subs, err := t.Subscribe()
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	return &Subscription{subscription: subs}, nil
    25  }
    26  
    27  // Next blocks the caller until any new EDS DataHash notification arrives.
    28  // Returns only notifications which successfully pass validation.
    29  func (subs *Subscription) Next(ctx context.Context) (Notification, error) {
    30  	msg, err := subs.subscription.Next(ctx)
    31  	if err != nil {
    32  		log.Errorw("listening for the next eds hash", "err", err)
    33  		return Notification{}, err
    34  	}
    35  
    36  	log.Debugw("received message", "topic", msg.Message.GetTopic(), "sender", msg.ReceivedFrom)
    37  	var pbmsg pb.RecentEDSNotification
    38  	if err := pbmsg.Unmarshal(msg.Data); err != nil {
    39  		log.Debugw("unmarshal error", "err", err)
    40  		return Notification{}, fmt.Errorf("shrex-sub: unmarshal notification, %w", err)
    41  	}
    42  	return Notification{
    43  		DataHash: pbmsg.DataHash,
    44  		Height:   pbmsg.Height,
    45  	}, nil
    46  }
    47  
    48  // Cancel stops the subscription.
    49  func (subs *Subscription) Cancel() {
    50  	subs.subscription.Cancel()
    51  }