bps

package
v2.8.4-rc1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: BSD-3-Clause Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package bps implements BPS-lite (SWIP-74) with the multi-publisher mode (SWIP-87). It is a live stream over feeds, relayed by a single broker.

Peers that join with the same topic and principal form a cohort. A peer may declare an owner, the address that signs its chunks. Without one, the stream only listens. The broker answers each join with a random challenge. The principal (the admin) must authenticate with an AUTH chunk before it can publish. Any other owner listens until a roster naming it arrives, then sends its AUTH to become a publisher. Publishers send signed chunks. The admin also sends ROSTER (the set of publishers) and EOS (end of the channel). The broker forwards each accepted chunk to every other receiving stream.

Index

Constants

View Source
const ChallengeSize = 32

ChallengeSize is the length of the challenge the broker sends in its Ack.

View Source
const ForgingBrokerBlocklistDuration = 10 * 24 * time.Hour

ForgingBrokerBlocklistDuration is how long a subscriber blocklists a broker that forwarded an invalid chunk. An honest broker never does that.

View Source
const MaxRosterSize = swarm.ChunkSize / (1 + 1 + crypto.AddressSize)

MaxRosterSize is the most addresses a ROSTER chunk can hold. Each address takes 22 bytes on the wire: a tag, a length and 20 bytes.

Variables

View Source
var (

	// ErrEndOfStream is returned by Session.Err after the admin ended the channel.
	ErrEndOfStream = errors.New("bps: end of stream")
	// ErrNotPublisher is returned by Publish when the session may not publish
	// the chunk. Either it was not granted, it was revoked, or it is not the
	// admin and the chunk is a ROSTER or EOS.
	ErrNotPublisher = errors.New("bps: session is not a publisher")
	// ErrInvalidDelivery is returned by Session.Err after the broker forwarded
	// a chunk that does not verify. The broker is at fault, not the client.
	ErrInvalidDelivery = errors.New("bps: invalid delivery")
)
View Source
var (
	// ErrInvalidMessage means the frame fields are malformed.
	ErrInvalidMessage = errors.New("bps: invalid message")
	// ErrInvalidSOC means the chunk's id does not match the frame, or the
	// chunk is not a valid single-owner chunk of the expected owner.
	ErrInvalidSOC = errors.New("bps: invalid soc")
	// ErrInvalidRoster means the roster payload does not decode, names the
	// admin, or names an address twice.
	ErrInvalidRoster = errors.New("bps: invalid roster")
)
View Source
var DefaultOptions = Options{
	MaxSubsPerCohort:             1024,
	MaxBrokerCohorts:             512,
	MaxCohortsPerConnection:      16,
	MaxPeerStreamsPerCohort:      2,
	MaxPublisherStreams:          2,
	InactiveTimeout:              10 * time.Minute,
	AuthWaitTimeout:              30 * time.Second,
	FlushTimeout:                 5 * time.Second,
	HandshakeTimeout:             10 * time.Second,
	WriteTimeout:                 10 * time.Second,
	QueueCap:                     64,
	ProtoBreachBlocklistDuration: 10 * time.Minute,
	InvalidAuthBlocklistDuration: time.Minute,
}

DefaultOptions are the default resource limits.

Functions

func ID

func ID(kind Kind, topic, challenge []byte, index uint64) ([]byte, error)

ID returns the single-owner chunk id for the given index: keccak256(SessionTopic(kind, topic, challenge) | index), index big-endian.

func SessionTopic

func SessionTopic(kind Kind, topic, challenge []byte) ([]byte, error)

SessionTopic returns keccak256(prefix | topic | challenge), the feed topic for chunks of the given kind. The prefix is empty for DATA, and "bps-service:v1" followed by the kind byte otherwise.

Types

type CohortSpec

type CohortSpec struct {
	Topic     []byte // 32-byte feed topic
	Principal []byte // 20-byte admin address
}

CohortSpec identifies a cohort. The topic binding is always FEED_TOPIC.

type Counters

type Counters struct {
	WrongStream    uint64 // kind not allowed for the stream's role
	UnknownKind    uint64 // unknown kind
	WrongChallenge uint64 // challenge does not match the stream
	InvalidSOC     uint64 // chunk failed verification
	AuthTimeout    uint64 // pending stream timed out before AUTH
	Retransmit     uint64 // index below the cursor
	QueueReset     uint64 // stream reset for a full queue
	InvalidRoster  uint64 // roster payload does not decode
	Revoked        uint64 // frame from a revoked stream
	Ended          uint64 // frame from a stream of an ended cohort
}

Counters count, per cohort, the frames the broker dropped and the streams it ended.

type Interface

type Interface interface {
	// Join joins a cohort at a broker and returns the session.
	Join(ctx context.Context, req JoinRequest) (Session, error)
}

Interface is the part of the service used by the API.

type JoinRequest

type JoinRequest struct {
	Broker   swarm.Address
	Spec     CohortSpec
	Owner    []byte   // 20-byte signer address, nil to only listen
	Position Position // from an earlier session
}

JoinRequest describes a cohort join.

type Kind

type Kind int

Kind is the type of a chunk on the wire.

const (
	KindUnspecified Kind = iota
	KindData             // a publisher's content
	// KindAuth is an empty chunk at index 0. It makes a stream a publisher.
	// On a publisher stream it is a heartbeat. It is never delivered.
	KindAuth
	// KindEOS is an empty chunk at index 0 from the admin. It ends the channel.
	KindEOS
	// KindRoster is the admin's list of publishers. Its payload is a Roster.
	KindRoster
)

type Message

type Message struct {
	Kind      Kind
	Owner     []byte // signer, the principal for ROSTER and EOS
	SOC       []byte
	Challenge []byte
	Index     uint64
	Roster    [][]byte // ROSTER only: publishers other than the principal
}

Message is a verified delivery: a DATA chunk from an allowed publisher, or a ROSTER or EOS from the admin.

type Options

type Options struct {
	MaxSubsPerCohort        int // subscriber streams per cohort
	MaxBrokerCohorts        int // live cohorts per broker
	MaxCohortsPerConnection int // cohorts per peer connection
	MaxPeerStreamsPerCohort int // streams per peer connection per cohort
	MaxPublisherStreams     int // publisher streams per address per cohort
	QueueCap                int // outbound frames per receiving stream
	//
	InactiveTimeout  time.Duration // idle time before a cohort is dropped
	AuthWaitTimeout  time.Duration // time a pending stream has to send its AUTH
	FlushTimeout     time.Duration // time to write out the queue of a closing stream
	HandshakeTimeout time.Duration // time a client's Join waits for the Ack
	WriteTimeout     time.Duration // time a client's Publish has to write its frame
	//
	ProtoBreachBlocklistDuration time.Duration // blocklist duration for a protocol violation
	InvalidAuthBlocklistDuration time.Duration // blocklist duration for an auth timeout
}

Options are the broker's resource limits. Zero values take the defaults.

type Position

type Position struct {
	Cursors      map[string]uint64 // next expected DATA index, keyed by publisher address
	Roster       [][]byte          // latest accepted roster
	RosterCursor uint64            // next expected ROSTER index
	Ended        bool              // an EOS was received
}

Position is how far a subscriber has read a channel. It is passed from one session to the next.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the bps protocol service. If broker is set, it also accepts inbound joins. Otherwise it only joins remote brokers.

func New

func New(streamer p2p.Streamer, blocklister p2p.Blocklister, broker bool, logger log.Logger, o Options) *Service

New returns a new bps Service. The blocklister may be nil.

func (*Service) Close

func (s *Service) Close() error

Close refuses new joins, drops all cohorts and resets their streams. Calling it again does nothing.

func (*Service) Counters

func (s *Service) Counters(spec CohortSpec) (Counters, bool)

Counters returns the counters of the cohort, if it exists.

func (*Service) Join

func (s *Service) Join(ctx context.Context, req JoinRequest) (Session, error)

Join joins a cohort at the broker. After a refused join or a reset stream, the caller must back off before joining again.

func (*Service) Metrics

func (s *Service) Metrics() []prometheus.Collector

Metrics returns the prometheus collectors of the service.

func (*Service) Protocol

func (s *Service) Protocol() p2p.ProtocolSpec

Protocol returns the p2p protocol specification for bps.

type Session

type Session interface {
	// Challenge returns the challenge the broker issued for this stream. Every
	// chunk published on the session must use it (see ID).
	Challenge() []byte
	// Messages returns the verified deliveries. The channel is never closed.
	// Use Done to learn when the stream has ended. All deliveries, including a
	// final EOS, are handed over before Done is closed.
	Messages() <-chan Message
	// Position returns how far the session has read, to pass to a later Join.
	Position() Position
	// Granted is closed when the session may send its AUTH. For the principal
	// that is at once. For any other owner it is when a roster naming it
	// arrives on this stream. A stream without an owner is never granted.
	Granted() <-chan struct{}
	// Publish sends a chunk of the given kind and index to the broker. The
	// broker does not reply, so Publish runs the broker's checks first and
	// returns ErrNotPublisher, ErrInvalidMessage, ErrInvalidSOC or
	// ErrInvalidRoster for a chunk the broker would reject.
	Publish(ctx context.Context, kind Kind, index uint64, chunk []byte) error
	// Done is closed when the p2p stream has ended.
	Done() <-chan struct{}
	// Err returns why the stream ended, ErrEndOfStream after an EOS. It is
	// valid once Done is closed.
	Err() error
	// Close closes the stream.
	Close() error
}

Session is a joined p2p stream to a broker.

Directories

Path Synopsis
Package pb holds only Protocol Buffer definitions and generated code.
Package pb holds only Protocol Buffer definitions and generated code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL