webrtcinterconnect

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package webrtcinterconnect implements the Go side of the external-signaling WebRTC interconnect defined by bitcoin-libp2p V1.4.

The package is protocol-neutral: callers provide a signaling adapter that transports opaque envelopes over their own message service. The transport turns a WebRTC DataChannel into a standard libp2p connection through the host upgrader (Noise + Yamux).

Index

Constants

View Source
const (
	DefaultConnectionTimeout           = 30 * time.Second
	DefaultSignalLifetime              = 120 * time.Second
	DefaultMaxEarlySignals             = 1024
	DefaultMaxEarlySignalsPerConn      = 32
	DefaultMaxSignalBytes              = 256 * 1024
	DefaultDataChannelMaxMessageBytes  = 16 * 1024
	DefaultDataChannelMaxBufferedBytes = 2 * 1024 * 1024
)

Defaults mirror the TypeScript SDK.

View Source
const DataChannelLabel = "bitcoin-libp2p-webrtc"

DataChannelLabel is the single DataChannel label used by the interconnect.

View Source
const MaxSafeInteger = int64(1)<<53 - 1

MaxSafeInteger mirrors JavaScript Number.MAX_SAFE_INTEGER. Sequence values must stay inside the same range so both languages validate identically.

Variables

This section is empty.

Functions

func BuildAddress

func BuildAddress(peerID peer.ID) ma.Multiaddr

BuildAddress returns the interconnect address `/webrtc/p2p/<peer-id>`.

func Factory

func Factory(options Options) func(tpt.Upgrader, network.ResourceManager, peer.ID) (tpt.Transport, error)

Factory returns a constructor suitable for libp2p.Transport(...).

func MarshalEnvelope

func MarshalEnvelope(envelope Envelope, maxSignalBytes int) ([]byte, error)

MarshalEnvelope validates and serializes an envelope.

func ParseAddress

func ParseAddress(address ma.Multiaddr) (peer.ID, error)

ParseAddress extracts the target peer ID from `/webrtc/p2p/<peer-id>`.

func ValidateEnvelope

func ValidateEnvelope(envelope Envelope, maxSignalBytes int) error

ValidateEnvelope applies the shared envelope rules. maxSignalBytes limits the JSON-encoded signal payload; the TypeScript SDK uses the same limit.

func WithSessionIDs

func WithSessionIDs(ctx context.Context, connectionID, attemptID string) (context.Context, error)

WithSessionIDs attaches caller-chosen session identifiers to a dial context. Browser interop uses the ChannelProtocol WebRTC session id as the connection id so both sides route signals under the same name. The identifiers apply to the next dial performed with this context.

Types

type Envelope

type Envelope struct {
	ConnectionID string `json:"connectionId"`
	AttemptID    string `json:"attemptId"`
	From         string `json:"from"`
	To           string `json:"to"`
	Sequence     int64  `json:"sequence"`
	ExpiresAtMs  int64  `json:"expiresAtMs"`
	Signal       Signal `json:"signal"`
}

Envelope is the routing metadata plus signal payload exchanged through the caller-provided signaling adapter. Field names match the TypeScript SDK.

func ParseEnvelope

func ParseEnvelope(data []byte, maxSignalBytes int) (Envelope, error)

ParseEnvelope parses and validates an envelope.

type Error

type Error struct {
	Code    ErrorCode
	Stage   ErrorStage
	Message string
	Cause   error
}

Error is a classified interconnect error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap exposes the cause for errors.Is/errors.As.

type ErrorCode

type ErrorCode string

ErrorCode is a stable interconnect error identifier.

const (
	CodeAddress       ErrorCode = "ERR_WEBRTC_INTERCONNECT_ADDRESS"
	CodeSignal        ErrorCode = "ERR_WEBRTC_INTERCONNECT_SIGNAL"
	CodeTimeout       ErrorCode = "ERR_WEBRTC_INTERCONNECT_TIMEOUT"
	CodeDial          ErrorCode = "ERR_WEBRTC_INTERCONNECT_DIAL"
	CodeAuth          ErrorCode = "ERR_WEBRTC_INTERCONNECT_AUTH"
	CodeNotConfigured ErrorCode = "ERR_WEBRTC_INTERCONNECT_NOT_CONFIGURED"
	CodeShutdown      ErrorCode = "ERR_WEBRTC_INTERCONNECT_SHUTDOWN"
)

Stable error codes; values match the TypeScript SDK.

func ErrorCodeOf

func ErrorCodeOf(err error) ErrorCode

ErrorCodeOf returns the stable code of an interconnect error, or "ERR_WEBRTC_INTERCONNECT_UNKNOWN" for any other error.

type ErrorStage

type ErrorStage string

ErrorStage identifies where an interconnect error happened.

const (
	StageValidate     ErrorStage = "validate"
	StageSignal       ErrorStage = "signal"
	StageDial         ErrorStage = "dial"
	StageConnect      ErrorStage = "connect"
	StageAuthenticate ErrorStage = "authenticate"
	StageShutdown     ErrorStage = "shutdown"
)

Error stages; values match the TypeScript SDK.

func ErrorStageOf

func ErrorStageOf(err error) ErrorStage

ErrorStageOf returns the stage of an interconnect error, or an empty string.

type ICECandidate

type ICECandidate struct {
	Candidate        string  `json:"candidate"`
	SDPMid           *string `json:"sdpMid,omitempty"`
	SDPMLineIndex    *uint16 `json:"sdpMLineIndex,omitempty"`
	UsernameFragment *string `json:"usernameFragment,omitempty"`
}

ICECandidate mirrors the browser RTCIceCandidateInit JSON shape.

type ICEServer

type ICEServer struct {
	URLs       []string
	Username   string
	Credential string
}

ICEServer mirrors the browser RTCIceServer shape without exposing pion types.

type Options

type Options struct {
	// Signaling is required; it moves envelopes through the caller's message service.
	Signaling SignalAdapter

	// ICEServers are passed to pion; the SDK never hardcodes STUN or TURN.
	ICEServers []ICEServer

	// ConnectionTimeout bounds offer/answer/ICE setup. Default 30s.
	ConnectionTimeout time.Duration

	// SignalLifetime sets Envelope.ExpiresAtMs for local signals. Default 120s.
	SignalLifetime time.Duration

	// MaxEarlySignals bounds globally buffered pre-offer ICE signals. Default 1024.
	MaxEarlySignals int

	// MaxSignalBytes bounds the JSON-encoded signal payload. Default 256 KiB.
	MaxSignalBytes int

	// DataChannelMaxMessageBytes chunks writes to the DataChannel. Default 16 KiB.
	DataChannelMaxMessageBytes int

	// DataChannelMaxBufferedBytes pauses writes above this local buffer. Default 2 MiB.
	DataChannelMaxBufferedBytes int

	// IncludeLoopbackCandidates enables loopback ICE candidates (tests only).
	IncludeLoopbackCandidates bool
}

Options configures an interconnect transport.

func (Options) String

func (o Options) String() string

type Role

type Role string

Role identifies the WebRTC signaling role of a session.

const (
	RoleInitiator Role = "initiator"
	RoleResponder Role = "responder"
)

Roles.

type Signal

type Signal struct {
	Type      SignalType    `json:"type"`
	SDP       string        `json:"sdp,omitempty"`
	Candidate *ICECandidate `json:"candidate,omitempty"`
	Reason    string        `json:"reason,omitempty"`
}

Signal is one WebRTC signaling payload.

type SignalAdapter

type SignalAdapter interface {
	// Send delivers one envelope to its target. Implementations should return
	// an error when delivery is unknown or failed.
	Send(ctx context.Context, envelope Envelope) error

	// Subscribe registers a listener for inbound envelopes. The returned
	// function unsubscribes. The listener may be called from any goroutine.
	Subscribe(listener func(Envelope)) (unsubscribe func(), err error)
}

SignalAdapter moves interconnect envelopes through the caller's message service. It must not be tied to any specific transport; the SDK never imports SatSubscription, ChannelProtocol or business code.

type SignalType

type SignalType string

SignalType enumerates the WebRTC interconnect signal payloads. Values are the exact JSON strings used by the TypeScript SDK.

const (
	SignalOffer           SignalType = "offer"
	SignalAnswer          SignalType = "answer"
	SignalICECandidate    SignalType = "ice-candidate"
	SignalEndOfCandidates SignalType = "end-of-candidates"
	SignalClose           SignalType = "close"
)

Signal types.

type Transport

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

Transport implements the go-libp2p transport half of the interconnect.

func New

func New(options Options, upgrader tpt.Upgrader, rcmgr network.ResourceManager, self peer.ID) (*Transport, error)

New creates an interconnect transport with an already available upgrader, resource manager and local peer id. Tests use this directly; hosts use Factory through libp2p.Transport.

func (*Transport) CanDial

func (t *Transport) CanDial(addr ma.Multiaddr) bool

CanDial reports whether addr is an interconnect address. The swarm strips the /p2p component before dialing, so `/webrtc` is dialable too.

func (*Transport) Close

func (t *Transport) Close() error

Close stops the transport, its sessions and the signaling subscription.

func (*Transport) Dial

func (t *Transport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (tpt.CapableConn, error)

Dial performs the initiator flow and returns an upgraded libp2p connection. The swarm strips the /p2p component before dialing, so the target peer ID is taken from the address when present and from p otherwise.

func (*Transport) DialSession

func (t *Transport) DialSession(ctx context.Context, raddr ma.Multiaddr, p peer.ID, connectionID, attemptID string) (tpt.CapableConn, error)

DialSession is Dial with caller-provided session identifiers. Browser interop uses the ChannelProtocol WebRTC session id as the connection id, so both sides route signals to the same session under its own name.

func (*Transport) Listen

func (t *Transport) Listen(addr ma.Multiaddr) (tpt.Listener, error)

Listen registers the virtual inbound listener. There is no network socket: inbound sessions arrive through the signaling adapter. Listen accepts `/webrtc` (the canonical listen address) and `/webrtc/p2p/<peer-id>`.

func (*Transport) Protocols

func (t *Transport) Protocols() []int

Protocols returns the multiaddr protocols this transport serves.

func (*Transport) Proxy

func (t *Transport) Proxy() bool

Proxy always returns false; the interconnect is not a proxy transport.

func (*Transport) QueueSessionIDs

func (t *Transport) QueueSessionIDs(connectionID, attemptID string) error

QueueSessionIDs makes the next outbound dial use the given session identifiers. It exists for swarm-driven dials (host.Connect/NewStream), whose context does not reach the transport; browser interop queues the ChannelProtocol session id right before connecting to the buyer.

Jump to

Keyboard shortcuts

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