cotilla

package
v0.0.0-dev4 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: BSD-2-Clause Imports: 26 Imported by: ? 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

Index

Constants

View Source
const (
	DefaultAppDistRoomID = "cotilla-app-dist-v1"
	DefaultAppID         = "cotilla-web"
	DefaultAppChannel    = "stable"
	FormatSingleHTMLV1   = "single-html-v1"
	FormatBundleV1       = "bundle-v1"
)

Public distribution constants

View Source
const BroadcastAddr = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"

BroadcastAddr is the universal destination address for mesh broadcasts (32-byte 0xFF hex).

View Source
const DefaultChunkSize = 64 * 1024

DefaultChunkSize is 64 KB as specified.

View Source
const MaxAttachmentChunks = 16384 // 16384 * 64KB = 1 GB

MaxAttachmentChunks caps allocated chunk slots to guard against OOM / DoS on untrusted metadata.

View Source
const MaxAttachmentSize int64 = 1 << 30 // 1 GB

MaxAttachmentSize caps declared file size.

View Source
const MaxTreeLeaves = 8192

MaxTreeLeaves caps decoded RatchetTree leaf count to prevent DoS allocations on malformed commits.

View Source
const RoomKeySize = 32

RoomKeySize is 32 bytes (256 bits).

View Source
const (
	SFrameCipherAES128GCM uint16 = 0x0001
)

RFC 9605 SFrame constants for AES_128_GCM_SHA256_128.

Variables

View Source
var (
	ErrSFrameMissingKey    = errors.New("sframe: missing key for KID")
	ErrSFrameInvalidHeader = errors.New("sframe: malformed RFC 9605 header")
	ErrSFrameReplay        = errors.New("sframe: replayed or stale counter")
	ErrSFrameAuthFailed    = errors.New("sframe: AEAD authentication failed")
	ErrSFrameUnadmitted    = errors.New("sframe: unadmitted member cannot derive SFrame keys")
)
View Source
var (
	// ErrTreeKEMEvictedMember indicates an evicted member attempted an unauthorized operation.
	ErrTreeKEMEvictedMember = errors.New("treekem: member is evicted from ratchet tree")
	// ErrTreeKEMInvalidCommit indicates a commit failed cryptographic verification.
	ErrTreeKEMInvalidCommit = errors.New("treekem: invalid commit signature, transcript hash, or confirmation tag")
	// ErrTreeKEMEpochMismatch indicates an unexpected epoch in commit or proposal.
	ErrTreeKEMEpochMismatch = errors.New("treekem: epoch mismatch")
	// ErrTreeKEMDecryptionFailed indicates unable to decrypt any path secret along copath resolution.
	ErrTreeKEMDecryptionFailed = errors.New("treekem: unable to decrypt path secret in direct path")
	// ErrTreeKEMLeafNotFound indicates the specified leaf does not exist.
	ErrTreeKEMLeafNotFound = errors.New("treekem: leaf index not found")
)

Functions

func CanonicalAppManifest

func CanonicalAppManifest(m *AppManifest) []byte

CanonicalAppManifest serializes the manifest metadata for Ed25519 signature computation and verification.

func CanonicalAttachMeta

func CanonicalAttachMeta(roomID, fileID, hash, name, mime, author string, size int64, totalChunks int, epochID, timestamp int64) []byte

CanonicalAttachMeta returns canonical bytes for authenticating attachment metadata offers.

func CanonicalCallControl

func CanonicalCallControl(scopeID, authorPub, nonceHex, ciphertextHex string, epochID, timestamp int64, isDM bool) []byte

CanonicalCallControl returns canonical bytes for signing an encrypted call presence control frame.

func CanonicalCallControlAAD

func CanonicalCallControlAAD(scopeID, authorPub string, epochID, timestamp int64, isDM bool) []byte

CanonicalCallControlAAD binds the outer metadata of a CallControlFrame into AEAD AAD.

func CanonicalCallSignal

func CanonicalCallSignal(fromSignPub, fromEncPub, toSignPub, ePubHex, nonceHex, ciphertextHex string, timestamp int64) []byte

CanonicalCallSignal returns canonical bytes for signing a pairwise Noise_IK-encrypted call signal frame.

func CanonicalCallSignalAAD

func CanonicalCallSignalAAD(fromSignPub, toSignPub string, timestamp int64) []byte

CanonicalCallSignalAAD binds pairwise Noise_IK call signal endpoints and timestamp.

func CanonicalChannelAnswer

func CanonicalChannelAnswer(channelID, sessionToken, targetPub, responderPub, sdpAnswer string, timestamp int64) []byte

CanonicalChannelAnswer returns canonical bytes for authenticating ChannelAnswer frames.

func CanonicalChannelInvite

func CanonicalChannelInvite(roomID, inviterPub, roomKey string, epochID, expiresAt int64) []byte

CanonicalChannelInvite returns length-prefixed canonical bytes for signing a room/channel invitation. It converts raw roomKey secrets into a salted SHA-256 commitment so redacted wire invites verify without leaking RoomKey.

func CanonicalChannelInviteWithInvitee

func CanonicalChannelInviteWithInvitee(roomID, inviterPub, inviteePub, roomKey string, epochID, expiresAt int64) []byte

CanonicalChannelInviteWithInvitee returns canonical bytes binding an explicit invitee public address when set.

func CanonicalChannelOffer

func CanonicalChannelOffer(queryID, channelID, sessionToken, responderPub, sdpOffer string, timestamp int64) []byte

CanonicalChannelOffer returns canonical bytes for authenticating ChannelOffer frames.

func CanonicalChannelQuery

func CanonicalChannelQuery(queryID, channelID, sessionToken, senderPub string, timestamp int64) []byte

CanonicalChannelQuery returns canonical bytes for authenticating epidemic ChannelQuery frames.

func CanonicalDirectInvite

func CanonicalDirectInvite(inviteID, fromSignPub, fromEncPub, ephemeralPub, toSignPub, nonce, ciphertext string, timestamp int64) []byte

CanonicalDirectInvite returns length-prefixed canonical bytes for signing an invite with forward secrecy.

func CanonicalEnvelopePayload

func CanonicalEnvelopePayload(roomID, authorPubKey, nonce, ciphertext string, epochID, timestamp int64) []byte

CanonicalEnvelopePayload constructs the length-prefixed canonical payload for envelope signature verification.

func CanonicalEpochCommit

func CanonicalEpochCommit(epochID int64, roomID, evictor, evictorEncPub, evictedPeer, addedPeer, reason, commitDigest string, timestamp int64) []byte

CanonicalEpochCommit returns length-prefixed canonical bytes for signing an epoch key rotation / member eviction / member welcome.

func CanonicalEpochCommitFromCommit

func CanonicalEpochCommitFromCommit(c *EpochCommit) []byte

CanonicalEpochCommitFromCommit generates the canonical byte representation for an EpochCommit struct.

func CanonicalInviteResponse

func CanonicalInviteResponse(inviteID, fromSignPub, toSignPub string, accepted bool, timestamp int64) []byte

CanonicalInviteResponse returns length-prefixed canonical bytes for signing an invite response.

func CanonicalLeave

func CanonicalLeave(peer string, timestamp int64) []byte

CanonicalLeave returns length-prefixed canonical bytes for signing a voluntary departure frame.

func CanonicalPacket

func CanonicalPacket(p *Packet) []byte

CanonicalPacket computes immutable canonical bytes for Ed25519 signing (excludes HopLimit).

func CanonicalPeerInfo

func CanonicalPeerInfo(signPub, encPub string, timestamp int64) []byte

CanonicalPeerInfo returns length-prefixed canonical bytes for signing peer discovery frames.

func CanonicalPeerSignal

func CanonicalPeerSignal(signalID, kind, from, target, sdp string, timestamp int64) []byte

CanonicalPeerSignal returns canonical bytes for authenticating PeerSignal frames.

func CanonicalRelayFrame

func CanonicalRelayFrame(from, target, relayType string, payload []byte, timestamp int64) []byte

CanonicalRelayFrame returns canonical bytes for authenticating a peer-to-peer relay envelope.

func CanonicalSignalingMsg

func CanonicalSignalingMsg(msgType, peer, target, sdp string, timestamp int64) []byte

CanonicalSignalingMsg returns canonical bytes for authenticating WebRTC signaling /ws control messages.

func ComputeChannelHash

func ComputeChannelHash(name string, psk RoomKey) uint32

ComputeChannelHash derives a Meshtastic-style non-zero 32-bit hash from channel name and PSK.

func ComputeMLSCommitDigest

func ComputeMLSCommitDigest(c *EpochCommit) string

ComputeMLSCommitDigest creates a length-prefixed collision-free SHA-256 digest of the MLSCommit and/or MLSWelcome payload.

func DecodeSFrameHeader

func DecodeSFrameHeader(frame []byte) (kid, ctr uint64, headerLen int, err error)

DecodeSFrameHeader parses an RFC 9605 header, returning KID, CTR, and header byte length.

func DecryptDirectInvite

func DecryptDirectInvite(recipient *Identity, senderEncPub [32]byte, ePub [32]byte, nonce, ciphertext, aad []byte) ([]byte, error)

DecryptDirectInvite decrypts ciphertext using recipient's private key, sender's static encryption key, and ephemeral public key.

func DecryptRoomPayload

func DecryptRoomPayload(key RoomKey, nonce []byte, ciphertext []byte, aad []byte) ([]byte, error)

DecryptRoomPayload decrypts ciphertext with the room key and verifies integrity against AAD using XChaCha20-Poly1305.

func DeriveNoiseIKInviteKey

func DeriveNoiseIKInviteKey(ePriv [32]byte, staticPriv [32]byte, peerEncPub [32]byte) ([]byte, error)

DeriveNoiseIKInviteKey computes the forward-secret symmetric invite key using Noise_IK pattern. ss1 = X25519(ePriv, peerEncPub) ss2 = X25519(staticPriv, peerEncPub) key = HKDF(ss1 || ss2, "cotilla-invite-v2")

func DeriveNoiseIKInviteKeyRecipient

func DeriveNoiseIKInviteKeyRecipient(recipientPriv [32]byte, ePub [32]byte, senderEncPub [32]byte) ([]byte, error)

DeriveNoiseIKInviteKeyRecipient computes the forward-secret symmetric invite key on the recipient side. ss1 = X25519(recipientPriv, ePub) ss2 = X25519(recipientPriv, senderEncPub) key = HKDF(ss1 || ss2, "cotilla-invite-v2")

func EncodeCanonical

func EncodeCanonical(tag string, fields ...string) []byte

EncodeCanonical serializes a domain tag and variable-length string fields using unambiguous length-prefixing. Format: tag + "|" + len(f0) + ":" + f0 + "|" + len(f1) + ":" + f1 ...

func EncodeSFrameHeader

func EncodeSFrameHeader(kid, ctr uint64) []byte

EncodeSFrameHeader encodes KID and CTR into the variable-length RFC 9605 §4.3 header.

func EncryptDirectInvite

func EncryptDirectInvite(sender *Identity, recipientEncPub [32]byte, payloadBytes []byte, aad []byte) (ePub [32]byte, nonce []byte, ciphertext []byte, err error)

EncryptDirectInvite encrypts plaintext payload using Noise_IK forward secrecy with recipient's X25519 key. Returns ephemeral public key, nonce, and ciphertext.

func EncryptRoomPayload

func EncryptRoomPayload(key RoomKey, plaintext []byte, aad []byte) (nonce []byte, ciphertext []byte, err error)

EncryptRoomPayload encrypts plaintext with the room key and additional authenticated data (AAD) using XChaCha20-Poly1305.

func GeneratePublisherKeypair

func GeneratePublisherKeypair() (pubHex, privHex string, err error)

GeneratePublisherKeypair generates a new random Ed25519 keypair for signing app bundles.

func InviteKeyCommitment

func InviteKeyCommitment(roomKey string) string

InviteKeyCommitment derives a non-reversible SHA-256 key commitment for channel invitations.

func MakeOpenSFrameKID

func MakeOpenSFrameKID(addr string) uint64

MakeOpenSFrameKID derives an immutable, collision-free 64-bit KID (with bit 63 set) for epoch-0 open rooms and 2-peer DM calls.

func MakeSFrameKID

func MakeSFrameKID(epoch uint64, leafIndex int) (uint64, error)

MakeSFrameKID packs an MLS epoch (bits 16..62) and tree leaf index (bits 0..15) into a KID, leaving bit 63 clear to distinguish MLS keys from epoch-0 open/DM peer KIDs.

func MarshalPacket

func MarshalPacket(p *Packet) ([]byte, error)

MarshalPacket serializes a Packet to JSON (see TODO.md §4 for future Protobuf migration).

func OpenGroupPayload

func OpenGroupPayload(key RoomKey, sealed, aad []byte) ([]byte, error)

OpenGroupPayload decrypts a [24B nonce || ciphertext] group payload.

func OpenUnicast

func OpenUnicast(recipient *Identity, senderEncHex string, sealed, aad []byte) ([]byte, error)

OpenUnicast decrypts a payload produced by SealUnicast from senderEncHex.

func PacketAAD

func PacketAAD(p *Packet) []byte

PacketAAD binds immutable routing headers into the AEAD additional authenticated data.

func ParseEncPub

func ParseEncPub(hexStr string) ([32]byte, error)

ParseEncPub decodes a hex-encoded 32-byte X25519 public key.

func RandomID

func RandomID() string

RandomID returns a random 128-bit hex identifier.

func SFrameEncryptFrame

func SFrameEncryptFrame(entry SFrameKeyEntry, ctr uint64, plaintext []byte) ([]byte, error)

SFrameEncryptFrame encrypts an encoded media frame using RFC 9605 AES-128-GCM.

func SealGroupPayload

func SealGroupPayload(key RoomKey, plaintext, aad []byte) ([]byte, error)

SealGroupPayload encrypts plaintext with key and AAD into [24B nonce || ciphertext].

func SealUnicast

func SealUnicast(sender *Identity, recipientEncHex string, plaintext, aad []byte) ([]byte, error)

SealUnicast encrypts plaintext for recipientEncHex using Noise_IK (ephemeral + static X25519). Output layout: [32B ePub || 24B nonce || ciphertext].

func SignAppManifest

func SignAppManifest(privHex string, m *AppManifest) error

SignAppManifest signs an AppManifest with an Ed25519 private key.

func SignPacket

func SignPacket(id *Identity, p *Packet)

SignPacket signs p with id and populates p.Signature.

func SplitSFrameKID

func SplitSFrameKID(kid uint64) (epoch uint64, leafIndex int)

SplitSFrameKID extracts the epoch and leaf index (or epoch=0, leafIndex=-1 for open KIDs).

func Verify

func Verify(pubHex string, msg []byte, sigHex string) bool

Verify checks an Ed25519 signature by pubHex against msg.

func VerifyAppBundle

func VerifyAppBundle(m *AppManifest, bundleBytes []byte, pinnedPubHex, expectedAppID, expectedChannel string, minSeq uint64, nowMs int64) error

VerifyAppBundle verifies both the AppManifest and the downloaded bundle bytes against a single pinned key.

func VerifyAppBundleWithKeys

func VerifyAppBundleWithKeys(m *AppManifest, bundleBytes []byte, validPubKeys []string, expectedAppID, expectedVersion, expectedChannel string, minSeq uint64, nowMs int64) error

VerifyAppBundleWithKeys verifies both the AppManifest (against validPubKeys, app name, and optional version) and the SHA-256 digest and chunk dimensions of the downloaded bundle bytes.

func VerifyAppManifest

func VerifyAppManifest(m *AppManifest, pinnedPubHex, expectedAppID, expectedChannel string, minSeq uint64, nowMs int64) error

VerifyAppManifest verifies the Ed25519 signature and basic constraints of an AppManifest.

func VerifyAppManifestWithKeys

func VerifyAppManifestWithKeys(m *AppManifest, validPubKeys []string, expectedAppID, expectedVersion, expectedChannel string, minSeq uint64, nowMs int64) error

VerifyAppManifestWithKeys validates an AppManifest against a list of allowed publisher public keys, app name (expectedAppID), optional version, channel, and sequence floor.

func VerifyPacket

func VerifyPacket(p *Packet, maxHop int, replayWindow time.Duration) error

VerifyPacket checks structural validity, hop bounds, replay window, and Ed25519 signature.

Types

type ActivePeer

type ActivePeer struct {
	SignPub       string
	EncPub        string
	JoinedAt      time.Time
	LastSeen      time.Time
	IsAnchor      bool
	IsGateway     bool
	ChannelHashes map[uint32]bool
}

ActivePeer tracks an open WebRTC overlay neighbor in the HyParView Active View.

type AnchorSolicitFrame

type AnchorSolicitFrame struct {
	QueryID string   `json:"query_id"`
	Sender  string   `json:"sender"`
	Needed  int      `json:"needed"`
	Exclude []string `json:"exclude,omitempty"`
}

AnchorSolicitFrame asks healthy non-anchor peers to register with their signaling server.

type AppBootstrapConfig

type AppBootstrapConfig struct {
	AppName         string            `json:"appName"`                   // Manifest AppID / app name
	Version         string            `json:"version,omitempty"`         // Optional expected version
	MinSeq          uint64            `json:"minSeq,omitempty"`          // Anti-rollback sequence floor
	ValidSignatures []string          `json:"validSignatures,omitempty"` // Allowed publisher Ed25519 public keys (hex)
	SeederGroup     SeederGroupConfig `json:"seederGroup"`
}

AppBootstrapConfig configures the application bundle to discover, verify, and load.

type AppManifest

type AppManifest struct {
	AppID       string `json:"app_id"`
	Channel     string `json:"channel"`
	Version     string `json:"version"`
	Seq         uint64 `json:"seq"`
	PublishedAt int64  `json:"published_at"`
	ExpiresAt   int64  `json:"expires_at,omitempty"`
	FileID      string `json:"file_id"`
	SHA256      string `json:"sha256"`
	Size        int64  `json:"size"`
	TotalChunks int    `json:"total_chunks"`
	EntryMIME   string `json:"entry_mime"`
	Format      string `json:"format"`
	PubKey      string `json:"pub_key"`
	Signature   string `json:"signature"`
}

AppManifest describes a signed application bundle distributed over Cotilla WebRTC.

func SignAppBundle

func SignAppBundle(privHex, appID, channel, version string, seq uint64, bundleData []byte, mime, format string, ttl time.Duration) (*AppManifest, error)

SignAppBundle creates, hashes, and signs an AppManifest for a raw application bundle.

type AppManifestRequest

type AppManifestRequest struct {
	RoomID    string `json:"room_id,omitempty"`
	AppID     string `json:"app_id"`
	Version   string `json:"version,omitempty"`
	Channel   string `json:"channel,omitempty"`
	MinSeq    uint64 `json:"min_seq,omitempty"`
	FileHash  string `json:"file_hash,omitempty"`
	RequestID string `json:"request_id,omitempty"`
}

AppManifestRequest asks app seeders in the public seeder group for a signed AppManifest.

type AppManifestResponse

type AppManifestResponse struct {
	RoomID    string          `json:"room_id,omitempty"`
	RequestID string          `json:"request_id,omitempty"`
	Manifest  *AppManifest    `json:"manifest"`
	Offer     *AttachmentMeta `json:"offer"`
}

AppManifestResponse returns the signed AppManifest and fresh AttachmentMeta offer.

type AttachmentAssembler

type AttachmentAssembler struct {
	Meta    AttachmentMeta
	RoomKey RoomKey
	// contains filtered or unexported fields
}

AttachmentAssembler handles chunk reception, decryption, and hash validation for incoming attachments.

func NewAttachmentAssembler

func NewAttachmentAssembler(meta AttachmentMeta, roomKey RoomKey) *AttachmentAssembler

NewAttachmentAssembler initializes an assembler for an announced attachment.

func (*AttachmentAssembler) AddChunk

func (a *AttachmentAssembler) AddChunk(index int, packedData []byte) (bool, error)

AddChunk decrypts an incoming chunk and records it if valid. Returns whether the file was completed by this chunk.

func (*AttachmentAssembler) Assemble

func (a *AttachmentAssembler) Assemble() ([]byte, error)

Assemble concatenates all chunks and validates the SHA-256 hash.

func (*AttachmentAssembler) Data

func (a *AttachmentAssembler) Data() []byte

Data returns the assembled file payload if available.

func (*AttachmentAssembler) ExportRawChunks

func (a *AttachmentAssembler) ExportRawChunks() [][]byte

ExportRawChunks returns a copy of all cached encrypted chunks for swarm seeding.

func (*AttachmentAssembler) IsComplete

func (a *AttachmentAssembler) IsComplete() bool

IsComplete returns whether all chunks have been received.

func (*AttachmentAssembler) MissingChunks

func (a *AttachmentAssembler) MissingChunks() []int

MissingChunks returns indices of all chunks not yet received.

func (*AttachmentAssembler) NextMissingChunks

func (a *AttachmentAssembler) NextMissingChunks(maxInFlight int) []int

NextMissingChunks returns up to available in-flight slots chunk indices and marks them requested.

func (*AttachmentAssembler) Progress

func (a *AttachmentAssembler) Progress() (int, int)

Progress returns received and total chunk counts.

func (*AttachmentAssembler) RawChunk

func (a *AttachmentAssembler) RawChunk(index int) []byte

RawChunk returns the cached encrypted chunk bytes at index for swarm seeding.

func (*AttachmentAssembler) ReceivedCount

func (a *AttachmentAssembler) ReceivedCount() int

ReceivedCount returns the number of chunks received so far.

func (*AttachmentAssembler) ResetUnreceivedRequests

func (a *AttachmentAssembler) ResetUnreceivedRequests()

ResetUnreceivedRequests unmarks requested status for any unreceived chunks (for manual re-requests).

func (*AttachmentAssembler) RetryStaleRequests

func (a *AttachmentAssembler) RetryStaleRequests(timeout time.Duration) int

RetryStaleRequests unmarks requested status for any unreceived chunks exceeding timeout.

type AttachmentMeta

type AttachmentMeta struct {
	RoomID       string `json:"room_id,omitempty"`
	FileID       string `json:"file_id"`
	Hash         string `json:"hash"`
	Name         string `json:"name"`
	Size         int64  `json:"size"`
	MIME         string `json:"mime"`
	TotalChunks  int    `json:"total_chunks"`
	EpochID      int64  `json:"epoch_id,omitempty"`
	AuthorPubKey string `json:"author_pub_key,omitempty"`
	Timestamp    int64  `json:"timestamp,omitempty"`
	Signature    string `json:"signature,omitempty"`
}

AttachmentMeta announces an encrypted file attachment.

func PrepareAttachment

func PrepareAttachment(roomKey RoomKey, name, mime string, data []byte) (*AttachmentMeta, [][]byte, error)

PrepareAttachment hashes, chunks, and encrypts a file payload with the room key.

func PrepareAttachmentWithEpoch

func PrepareAttachmentWithEpoch(roomKey RoomKey, epochID int64, author, name, mime string, data []byte) (*AttachmentMeta, [][]byte, error)

PrepareAttachmentWithEpoch hashes, chunks, and encrypts a file payload bound to a specific epoch and author.

type BroadcastEmitFunc

type BroadcastEmitFunc func(ttl int, fanout int)

BroadcastEmitFunc builds and transmits one attempt of a broadcast with the given TTL and peer fanout.

type CallControlFrame

type CallControlFrame struct {
	ScopeID    string `json:"scope_id"`
	AuthorPub  string `json:"author_pub"`
	EpochID    int64  `json:"epoch_id"`
	IsDM       bool   `json:"is_dm,omitempty"`
	Timestamp  int64  `json:"timestamp"`
	Nonce      string `json:"nonce"`
	Ciphertext string `json:"ciphertext"`
	Signature  string `json:"signature"`
}

CallControlFrame transports encrypted, signed ephemeral call presence across verified scope members.

type CallOptions

type CallOptions struct {
	ListenOnly bool `json:"listen_only"`
	Audio      bool `json:"audio"`
	Video      bool `json:"video"`
	Screen     bool `json:"screen"`
}

CallOptions configures which media capabilities a participant enables when joining a call.

type CallPeerState

type CallPeerState struct {
	Address      string    `json:"address"`
	CallID       string    `json:"call_id"`
	LeafIndex    int       `json:"leaf_index"`
	Epoch        int64     `json:"epoch"`
	SenderEncPub string    `json:"sender_enc_pub,omitempty"`
	Audio        bool      `json:"audio"`
	Video        bool      `json:"video"`
	Screen       bool      `json:"screen"`
	LastSeen     time.Time `json:"last_seen"`
}

CallPeerState tracks the active call presence of an authorized remote participant in a scope.

type CallPresencePayload

type CallPresencePayload struct {
	Action       string `json:"action"` // "join" | "leave" | "update"
	ScopeID      string `json:"scope_id"`
	IsDM         bool   `json:"is_dm,omitempty"`
	CallID       string `json:"call_id"`
	Epoch        int64  `json:"epoch"`
	LeafIndex    int    `json:"leaf_index"`
	SenderEncPub string `json:"sender_enc_pub,omitempty"`
	Audio        bool   `json:"audio"`
	Video        bool   `json:"video"`
	Screen       bool   `json:"screen"`
}

CallPresencePayload is the decrypted body of CallControlFrame announcing scoped call state.

type CallSignalFrame

type CallSignalFrame struct {
	From         string `json:"from"`
	FromEncPub   string `json:"from_enc_pub"`
	Target       string `json:"target"`
	EphemeralPub string `json:"ephemeral_pub"`
	Nonce        string `json:"nonce"`
	Ciphertext   string `json:"ciphertext"`
	Timestamp    int64  `json:"timestamp"`
	Signature    string `json:"signature"`
}

CallSignalFrame wraps a pairwise Noise_IK-encrypted secondary WebRTC signal.

type CallSignalPayload

type CallSignalPayload struct {
	ScopeID string `json:"scope_id"`
	IsDM    bool   `json:"is_dm,omitempty"`
	CallID  string `json:"call_id"`
	Epoch   int64  `json:"epoch"`
	Kind    string `json:"kind"`    // "offer" | "answer" | "candidate" | "bye"
	Payload string `json:"payload"` // Raw SDP or serialized ICE candidate JSON
	From    string `json:"from,omitempty"`
}

CallSignalPayload is the Noise_IK-decrypted pairwise secondary WebRTC signaling message.

type ChannelInvite

type ChannelInvite struct {
	RoomID       string         `json:"room_id"`
	InviterPub   string         `json:"inviter_pub"`
	InviteePub   string         `json:"invitee_pub,omitempty"`
	RoomKey      string         `json:"room_key,omitempty"`
	RoomKeyHash  string         `json:"room_key_hash,omitempty"`
	EpochID      int64          `json:"epoch_id"`
	ExpiresAt    int64          `json:"expires_at"`
	Signature    string         `json:"signature"`
	ParentInvite *ChannelInvite `json:"parent_invite,omitempty"`
}

ChannelInvite represents a cryptographically signed invitation to join a channel.

func (*ChannelInvite) KeyCommitment

func (inv *ChannelInvite) KeyCommitment() string

KeyCommitment returns the canonical SHA-256 key commitment for this invite.

func (*ChannelInvite) Redacted

func (inv *ChannelInvite) Redacted() *ChannelInvite

Redacted returns a deep copy of the ChannelInvite chain with raw RoomKey stripped.

type ChannelKind

type ChannelKind int

ChannelKind distinguishes public PSK groups (e.g. app seeder) from private MLS groups.

const (
	// ChannelPrivate uses MLS epoch keys, short TTLs, and >= 6 active group peers.
	ChannelPrivate ChannelKind = iota
	// ChannelPublic uses a shared group PSK, longer TTLs, and >= 2 active group peers.
	ChannelPublic
)

type ChannelState

type ChannelState struct {
	RoomID       string
	ChannelHash  uint32
	Kind         ChannelKind
	RoomKey      RoomKey
	BootstrapKey RoomKey // Initial PSK / K0 bootstrap key

	RingBuffer *RingBuffer

	// Public App Distribution metadata
	IsAppDist bool
	// contains filtered or unexported fields
}

ChannelState holds isolated cryptographic, MLS, attachment, and sync state for one channel.

type ChatPayload

type ChatPayload struct {
	Type string `json:"type"` // "chat"
	Text string `json:"text"`
}

ChatPayload is the plaintext content of an encrypted chat message envelope.

type ChunkRequest

type ChunkRequest struct {
	RoomID     string `json:"room_id,omitempty"`
	FileID     string `json:"file_id"`
	ChunkIndex int    `json:"chunk_index"`
}

ChunkRequest asks for a specific chunk of an attachment.

type ChunkResponse

type ChunkResponse struct {
	RoomID     string `json:"room_id,omitempty"`
	FileID     string `json:"file_id"`
	ChunkIndex int    `json:"chunk_index"`
	Data       []byte `json:"data"`
}

ChunkResponse carries an encrypted attachment chunk.

type Config

type Config struct {
	// Peer Topology & HyParView Parameters
	MaxPeers             int           `json:"maxPeers,omitempty"`             // Hard cap on active WebRTC links (default: 16)
	MinActivePeers       int           `json:"minActivePeers,omitempty"`       // Minimum general overlay peers (default: 6)
	MinPrivateGroupPeers int           `json:"minPrivateGroupPeers,omitempty"` // Target connected peers per private group (default: 6)
	MinPublicGroupPeers  int           `json:"minPublicGroupPeers,omitempty"`  // Target connected peers per public group (default: 2)
	PassiveViewSize      int           `json:"passiveViewSize,omitempty"`      // HyParView passive descriptor pool size (default: 30)
	ShuffleInterval      time.Duration `json:"shuffleInterval,omitempty"`      // HyParView shuffle / rotation period (default: 10s)
	ShuffleTTL           int           `json:"shuffleTTL,omitempty"`           // Random walk hop count for HyParView shuffle (default: 3)
	ShuffleFanout        int           `json:"shuffleFanout,omitempty"`        // Descriptors exchanged per shuffle (default: 4)
	MaxAnchorConnections int           `json:"maxAnchorConnections,omitempty"` // Maximum anchor connections (default: 3)
	MinAnchorConnections int           `json:"minAnchorConnections,omitempty"` // Minimum anchor connections (default: 1)

	// Expanding-Ring Broadcast & TTL Policy
	InitialBroadcastTTL    int           `json:"initialBroadcastTTL,omitempty"`    // Starting TTL for broadcasts (default: 1)
	InitialBroadcastFanout int           `json:"initialBroadcastFanout,omitempty"` // Starting peer fanout for broadcasts (default: 2)
	MaxBroadcastTTL        int           `json:"maxBroadcastTTL,omitempty"`        // Cap when doubling TTL (default: 8)
	BroadcastHopTimeout    time.Duration `json:"broadcastHopTimeout,omitempty"`    // Base hop unit; retries after 2*TTL*unit (default: 500ms)
	PrivateGroupTTL        int           `json:"privateGroupTTL,omitempty"`        // Short TTL for private MLS groups (default: 3)
	PublicGroupTTL         int           `json:"publicGroupTTL,omitempty"`         // Longer TTL for public PSK groups (default: 6)
	GossipTTL              int           `json:"gossipTTL,omitempty"`              // Default hop limit for general gossip (default: 3)
	GossipFanout           int           `json:"gossipFanout,omitempty"`           // Default fanout for general forwarding (default: 3)
	GossipCacheTTL         time.Duration `json:"gossipCacheTTL,omitempty"`         // Packet deduplication cache lifetime (default: 30s)

	// Messaging, Security & Media Parameters
	RingBufferCapacity int           `json:"ringBufferCapacity,omitempty"` // Retained messages per channel (default: 200)
	MessageTTL         time.Duration `json:"messageTTL,omitempty"`         // RingBuffer catch-up retention (default: 15m)
	ChunkSize          int           `json:"chunkSize,omitempty"`          // Attachment chunk size (default: 64 KB)
	STUNServers        []string      `json:"stunServers,omitempty"`        // STUN servers for ICE gathering
	ReplayWindow       time.Duration `json:"replayWindow,omitempty"`       // Live packet clock skew limit (default: 5m)
	SyncTimeout        time.Duration `json:"syncTimeout,omitempty"`        // Targeted sync batch timeout (default: 1500ms)
	InviteTTL          time.Duration `json:"inviteTTL,omitempty"`          // Signed invite lifetime (default: 15m)
	CallEpochGrace     time.Duration `json:"callEpochGrace,omitempty"`     // SFrame prior-epoch grace (default: 3s)
}

Config holds tunable parameters for a Cotilla mesh node.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration for a Cotilla mesh node.

func (Config) GroupTTL

func (c Config) GroupTTL(kind ChannelKind) int

GroupTTL returns the gossip hop limit for the given channel kind.

func (Config) GroupTargetPeers

func (c Config) GroupTargetPeers(kind ChannelKind) int

GroupTargetPeers returns the desired active peer count for the given channel kind.

type DMFrame

type DMFrame struct {
	Kind    string `json:"kind,omitempty"`
	Payload []byte `json:"payload"`
}

DMFrame carries a 1:1 encrypted DM or pairwise relay payload over a unicast Packet.

type DirectInvite

type DirectInvite struct {
	InviteID     string `json:"invite_id"`
	FromSignPub  string `json:"from_sign_pub"`
	FromEncPub   string `json:"from_enc_pub"`
	EphemeralPub string `json:"ephemeral_pub"`
	ToSignPub    string `json:"to_sign_pub"`
	Nonce        string `json:"nonce"`
	Ciphertext   string `json:"ciphertext"`
	Timestamp    int64  `json:"timestamp"`
	Signature    string `json:"signature"`
}

DirectInvite encapsulates a Noise_IK encrypted invite to a 1:1 DM or breakout room.

type DirectPath

type DirectPath struct {
	LeafIndex     int              `json:"leaf_index"`
	LeafPublicKey [32]byte         `json:"leaf_public_key"`
	Nodes         []DirectPathNode `json:"nodes"`
}

DirectPath represents a sequence of updated ancestor nodes from committer's leaf to root.

type DirectPathNode

type DirectPathNode struct {
	NodeIndex     int                `json:"node_index"`
	PublicKey     [32]byte           `json:"public_key"`
	EncryptedKeys map[int]HPKECipher `json:"encrypted_keys"` // copath node index -> ciphertext
}

DirectPathNode contains the public key and encrypted path secret for an ancestor node.

type Envelope

type Envelope struct {
	RoomID       string `json:"room_id"`
	AuthorPubKey string `json:"author_pub_key"`
	Nonce        string `json:"nonce"`
	Ciphertext   string `json:"ciphertext"`
	Timestamp    int64  `json:"timestamp"`
	Signature    string `json:"signature"`
	EpochID      int64  `json:"epoch_id,omitempty"`
	MsgID        string `json:"-"`
}

Envelope carries an encrypted chat message payload and author's Ed25519 signature. It is stored in RingBuffer for catch-up sync and delivered to Hooks.OnMessage.

func NewEnvelope

func NewEnvelope(id *Identity, roomID string, roomKey RoomKey, plaintext []byte) (*Envelope, error)

NewEnvelope creates, encrypts, and signs a message envelope for roomID at epoch 0.

func NewEnvelopeWithEpoch

func NewEnvelopeWithEpoch(id *Identity, roomID string, roomKey RoomKey, epochID int64, plaintext []byte) (*Envelope, error)

NewEnvelopeWithEpoch creates, encrypts, and signs a message envelope bound to epochID.

func (*Envelope) Decrypt

func (e *Envelope) Decrypt(roomKey RoomKey) ([]byte, error)

Decrypt opens the envelope using roomKey and verifies integrity against context AAD.

func (*Envelope) ID

func (e *Envelope) ID() string

ID returns the unique message identifier (SHA-256 hash of signature and nonce).

func (*Envelope) Verify

func (e *Envelope) Verify(expectedRoomID string, maxClockSkew time.Duration) error

Verify checks the envelope signature, room ID, and clock skew window.

type EpochCommit

type EpochCommit struct {
	EpochID         int64          `json:"epoch_id"`
	RoomID          string         `json:"room_id"`
	Evictor         string         `json:"evictor"`
	EvictorEncPub   string         `json:"evictor_enc_pub,omitempty"`
	EvictedPeer     string         `json:"evicted_peer,omitempty"`
	AddedPeer       string         `json:"added_peer,omitempty"`
	Reason          string         `json:"reason,omitempty"`
	MLSCommit       *MLSCommit     `json:"mls_commit,omitempty"`
	MLSWelcome      *MLSWelcome    `json:"mls_welcome,omitempty"`
	CommitterInvite *ChannelInvite `json:"committer_invite,omitempty"`
	Timestamp       int64          `json:"timestamp"`
	Signature       string         `json:"signature"`
}

EpochCommit encapsulates an MLS epoch ratchet commit (admission, eviction, or key rotation).

type ExpandingBroadcaster

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

ExpandingBroadcaster runs expanding-ring broadcasts that start with a short TTL and small fanout, doubling both TTL and peer fanout whenever no reply arrives within 2 * TTL * BroadcastHopTimeout.

func NewExpandingBroadcaster

func NewExpandingBroadcaster(cfg Config) *ExpandingBroadcaster

NewExpandingBroadcaster creates a scheduler bound to cfg.

func (*ExpandingBroadcaster) MarkSatisfied

func (b *ExpandingBroadcaster) MarkSatisfied(tag string)

MarkSatisfied cancels an in-flight expanding broadcast once a valid reply is received.

func (*ExpandingBroadcaster) Start

func (b *ExpandingBroadcaster) Start(tag string, maxTTL int, emit BroadcastEmitFunc)

Start begins (or restarts) an expanding-ring broadcast for tag.

func (*ExpandingBroadcaster) Stop

func (b *ExpandingBroadcaster) Stop()

Stop cancels all active expanding-ring broadcasts.

type ExportedNode

type ExportedNode struct {
	Index          int      `json:"index"`
	LeafIndex      int      `json:"leaf_index"`
	Blank          bool     `json:"blank"`
	PublicKey      [32]byte `json:"public_key"`
	SignPubHex     string   `json:"sign_pub_hex,omitempty"`
	JoinedEpoch    uint64   `json:"joined_epoch,omitempty"`
	UnmergedLeaves []int    `json:"unmerged_leaves,omitempty"`
	Parent         int      `json:"parent"`
	Left           int      `json:"left"`
	Right          int      `json:"right"`
}

ExportedNode is a serializable representation of a ratchet tree node for Welcome frames.

type GroupContext

type GroupContext struct {
	GroupID                 string   `json:"group_id"`
	Epoch                   uint64   `json:"epoch"`
	TreeHash                [32]byte `json:"tree_hash"`
	ConfirmedTranscriptHash [32]byte `json:"confirmed_transcript_hash"`
}

GroupContext binds the cryptographic context of an MLS epoch (RFC 9420 Section 8.1).

func (GroupContext) Bytes

func (gc GroupContext) Bytes() []byte

Bytes serializes GroupContext canonically.

type GroupDiscoverPayload

type GroupDiscoverPayload struct {
	RoomID  string `json:"room_id"`
	Want    int    `json:"want,omitempty"`
	IsReply bool   `json:"is_reply,omitempty"`
}

GroupDiscoverPayload announces interest in a group (encrypted with group PSK or epoch key).

type HPKECipher

type HPKECipher struct {
	EphemeralPub [32]byte `json:"ephemeral_pub"`
	Ciphertext   []byte   `json:"ciphertext"`
}

HPKECipher represents an encrypted secret using DHKEM(X25519, HKDF-SHA256) + ChaCha20-Poly1305.

type Hooks

type Hooks struct {
	OnMessage            func(env *Envelope, plaintext []byte)
	OnAttachmentOffer    func(meta *AttachmentMeta)
	OnAttachment         func(meta *AttachmentMeta, data []byte)
	OnAttachmentProgress func(fileID string, receivedChunks, totalChunks int)
	OnCallPresence       func(scopeID string, isDM bool, from string, payload *CallPresencePayload)
	OnCallSignal         func(sig *CallSignalPayload)
	OnSFrameKeysUpdated  func(scopeID string, isDM bool, bundle *SFrameKeyBundle)
	OnCallPeerClosed     func(scopeID string, peerAddr string)
	OnDirectInvite       func(invite *DirectInvite, payload *InvitePayload)
	OnInviteResponse     func(res *InviteResponse)
	OnPeerJoined         func(addr string)
	OnPeerLeft           func(addr string)
	OnRelayPayload       func(from, relayType string, payload []byte)
	OnMemberEvicted      func(evictedPeer, evictor, reason string, epochID int64)
	OnEpochCommit        func(commit *EpochCommit)
	OnAnchorIntro        func(anchors []string, fallback bool)
	OnAnchorDeficit      func(currentAnchors int, activePeers int)
	OnAnchorSolicit      func(needed int)
	OnChannelDiscovered  func(channelID string, peer string)
	OnPeerCandidate      func(peers []string)
	OnAppManifest        func(manifest *AppManifest, from string)
	OnAppBundleReady     func(manifest *AppManifest, data []byte)
	Log                  func(msg string)
}

Hooks defines event callbacks for incoming room, overlay, call, and app distribution activities.

type Identity

type Identity struct {
	SignPub  ed25519.PublicKey
	SignPriv ed25519.PrivateKey
	EncPub   [32]byte
	EncPriv  [32]byte
}

Identity holds a client's long-term Ed25519 signing keypair and X25519 encryption keypair.

func NewIdentity

func NewIdentity() (*Identity, error)

NewIdentity generates a fresh random client identity.

func NewIdentityFromSeed

func NewIdentityFromSeed(seed []byte) (*Identity, error)

NewIdentityFromSeed derives a deterministic Identity from a >=16 byte seed.

func (*Identity) Address

func (id *Identity) Address() string

Address returns the hex-encoded Ed25519 public key — the participant's identity.

func (*Identity) EncAddress

func (id *Identity) EncAddress() string

EncAddress returns the hex-encoded X25519 public encryption key.

func (*Identity) Sign

func (id *Identity) Sign(msg []byte) []byte

Sign signs msg with the Ed25519 private key.

type InvitePayload

type InvitePayload struct {
	Type      string `json:"type"` // "dm" | "breakout"
	RoomID    string `json:"room_id"`
	RoomKey   string `json:"room_key"`
	Title     string `json:"title,omitempty"`
	CreatedAt int64  `json:"created_at"`
}

InvitePayload is the decrypted body of a DirectInvite.

type InviteResponse

type InviteResponse struct {
	InviteID    string `json:"invite_id"`
	FromSignPub string `json:"from_sign_pub"`
	ToSignPub   string `json:"to_sign_pub"`
	Accepted    bool   `json:"accepted"`
	Timestamp   int64  `json:"timestamp"`
	Signature   string `json:"signature"`
}

InviteResponse conveys accept/decline status for a DirectInvite.

type KeyPackage

type KeyPackage struct {
	Identity  *Identity `json:"-"`
	InitPriv  *[32]byte `json:"-"`        // Ephemeral private key kept locally for Welcome decryption
	SignPub   string    `json:"sign_pub"` // hex Ed25519 identity
	InitKey   [32]byte  `json:"init_key"` // X25519 HPKE public key
	Timestamp int64     `json:"timestamp"`
	Signature []byte    `json:"signature"`
}

KeyPackage represents a client's pre-published public credentials (RFC 9420 Section 10).

func NewKeyPackage

func NewKeyPackage(id *Identity) (*KeyPackage, error)

NewKeyPackage creates a signed KeyPackage with fresh ephemeral init key for joining an MLS group.

func (*KeyPackage) Verify

func (kp *KeyPackage) Verify() bool

Verify validates the self-signature on a KeyPackage.

type LeafSnapshot

type LeafSnapshot struct {
	LeafIndex int
	Address   string
}

LeafSnapshot describes a non-blank member leaf in the MLS ratchet tree for key export.

type LeaveFrame

type LeaveFrame struct {
	RoomID    string `json:"room_id,omitempty"`
	Peer      string `json:"peer"`
	Timestamp int64  `json:"timestamp"`
	Signature string `json:"signature"`
}

LeaveFrame announces voluntary departure from the mesh or a channel.

type MLSCommit

type MLSCommit struct {
	GroupID         string         `json:"group_id,omitempty"`
	CommitterLeaf   int            `json:"committer_leaf"`
	Epoch           uint64         `json:"epoch"`
	RemovedLeaf     int            `json:"removed_leaf"` // -1 if no removal
	AddedPackage    *KeyPackage    `json:"added_package,omitempty"`
	Path            *DirectPath    `json:"path"`
	TreeNodes       []ExportedNode `json:"tree_nodes,omitempty"`
	ConfirmationTag [32]byte       `json:"confirmation_tag"`
	Signature       []byte         `json:"signature"`
}

MLSCommit represents a group state transition commit (RFC 9420 Section 12).

func (*MLSCommit) CanonicalBytes

func (c *MLSCommit) CanonicalBytes() []byte

ApplicationSecretBytes returns the 32-byte symmetric key for encrypting room traffic in this epoch.

func (*MLSCommit) CanonicalBytesWithConfirmation

func (c *MLSCommit) CanonicalBytesWithConfirmation() []byte

CanonicalBytesWithConfirmation returns canonical bytes including the confirmation tag for signature.

type MLSGroup

type MLSGroup struct {
	GroupID                 string
	Epoch                   uint64
	MyLeafIndex             int
	LocalIdentity           *Identity
	Tree                    *RatchetTree
	InitSecret              [32]byte
	EpochSecret             [32]byte
	ApplicationSecret       [32]byte
	ConfirmationKey         [32]byte
	ExporterSecret          [32]byte
	ConfirmedTranscriptHash [32]byte
	// contains filtered or unexported fields
}

func NewMLSGroup

func NewMLSGroup(groupID string, id *Identity) (*MLSGroup, error)

NewMLSGroup creates a new MLS group with the local peer as the group creator at leaf 0.

func NewMLSGroupFromWelcome

func NewMLSGroupFromWelcome(id *Identity, welcome *MLSWelcome, initPriv ...*[32]byte) (*MLSGroup, error)

NewMLSGroupFromWelcome initializes an MLSGroup for a newly invited member from a Welcome message. It strictly binds welcome decryption to the supplied ephemeral initPriv (when provided), verifies TreeHash, committer signature on MLSWelcome, and ConfirmationTag before accepting.

func (*MLSGroup) ApplicationSecretBytes

func (g *MLSGroup) ApplicationSecretBytes() [32]byte

func (*MLSGroup) CreateAddCommit

func (g *MLSGroup) CreateAddCommit(pkg *KeyPackage) (*MLSCommit, *MLSWelcome, error)

func (*MLSGroup) CreateRemoveCommit

func (g *MLSGroup) CreateRemoveCommit(targetLeaf int) (*MLSCommit, error)

CreateRemoveCommit proposes and commits removing (evicting) a member from targetLeaf.

func (*MLSGroup) CreateUpdateCommit

func (g *MLSGroup) CreateUpdateCommit() (*MLSCommit, error)

CreateUpdateCommit performs continuous asymmetric key ratcheting (PCS) for the committer.

func (*MLSGroup) EnsureMemberLeaf

func (g *MLSGroup) EnsureMemberLeaf(signPubHex string, initKey [32]byte) int

EnsureMemberLeaf ensures that a member with the given address and init key is present in a leaf. Returns the assigned leaf index.

func (*MLSGroup) Export

func (g *MLSGroup) Export(label string, context []byte, length int) ([]byte, error)

Export implements RFC 9420 Section 8.5 MLS-Exporter bound to the current epoch's ExporterSecret.

func (*MLSGroup) FindLeafByAddress

func (g *MLSGroup) FindLeafByAddress(signPubHex string) int

FindLeafByAddress returns the leaf index of the member with the given Ed25519 public address, or -1.

func (*MLSGroup) GroupContext

func (g *MLSGroup) GroupContext() GroupContext

GroupContext returns the current cryptographic group context.

func (*MLSGroup) ProcessCommit

func (g *MLSGroup) ProcessCommit(commit *MLSCommit) error

ProcessCommit verifies and applies an inbound commit atomically against a cloned ratchet tree.

func (*MLSGroup) SnapshotForSFrame

func (g *MLSGroup) SnapshotForSFrame(label string, context []byte) (epoch uint64, myLeaf int, leaves []LeafSnapshot, exported []byte, err error)

SnapshotForSFrame atomically captures the epoch, local leaf index, active tree leaves, and an exported base secret under a single read lock.

type MLSWelcome

type MLSWelcome struct {
	GroupID                 string         `json:"group_id"`
	Epoch                   uint64         `json:"epoch"`
	SignerLeaf              int            `json:"signer_leaf"`
	TreeNodes               []ExportedNode `json:"tree_nodes"`
	EncryptedGroupSecret    HPKECipher     `json:"encrypted_group_secret"`
	TreeHash                [32]byte       `json:"tree_hash"`
	ConfirmedTranscriptHash [32]byte       `json:"confirmed_transcript_hash"`
	ConfirmationTag         [32]byte       `json:"confirmation_tag"`
	Signature               []byte         `json:"signature,omitempty"`
}

MLSWelcome transports the initial group state and encrypted epoch secret to newcomers.

func (*MLSWelcome) CanonicalBytes

func (w *MLSWelcome) CanonicalBytes() []byte

type Node

type Node struct {
	ID        *Identity
	Cfg       Config
	Transport Transport
	Hooks     Hooks

	// Embedded primary channel keeps convenient direct accessors on Node.
	*ChannelState
	// contains filtered or unexported fields
}

Node is a participant in the Cotilla Meshtastic-inspired gossip mesh and MLS channels.

func NewNode

func NewNode(id *Identity, roomID string, roomKey RoomKey, cfg Config, tr Transport, hooks Hooks) *Node

NewNode initializes a Cotilla mesh node with its primary private channel.

func (*Node) ActiveCallPeers

func (n *Node) ActiveCallPeers(scopeID string) []CallPeerState

ActiveCallPeers returns a copy of currently known active call participants in scopeID.

func (*Node) ActiveChannels

func (n *Node) ActiveChannels() []string

ActiveChannels returns the list of joined channel IDs.

func (*Node) AddAnchorPeer

func (n *Node) AddAnchorPeer(addr string)

AddAnchorPeer registers addr as an anchor peer.

func (*Node) AddGatewayPeer

func (n *Node) AddGatewayPeer(addr string)

AddGatewayPeer marks addr as a signaling gateway DataChannel peer.

func (*Node) AddPeer

func (n *Node) AddPeer(addr string)

AddPeer records an open WebRTC peer in HyParView and triggers initial offer sync.

func (*Node) Address

func (n *Node) Address() string

Address returns this node's hex Ed25519 public address.

func (*Node) AnchorPeers

func (n *Node) AnchorPeers() []string

AnchorPeers returns known anchor peer addresses.

func (*Node) AttachmentOffers

func (n *Node) AttachmentOffers() []*AttachmentMeta

AttachmentOffers returns all known non-app-dist attachment metadata offers.

func (*Node) BootstrapApp

func (n *Node) BootstrapApp(cfg AppBootstrapConfig) (RoomKey, error)

BootstrapApp configures and joins the public app seeder group (ChannelPublic) using cfg, then starts an expanding-ring broadcast requesting the app manifest and chunks.

func (*Node) BroadcastPeerInfo

func (n *Node) BroadcastPeerInfo()

BroadcastPeerInfo announces this node's credentials, KeyPackage, and redacted invite on joined private channels.

func (*Node) ChannelCurrentEpoch

func (n *Node) ChannelCurrentEpoch(channelID string) int64

ChannelCurrentEpoch returns channelID's current epoch counter.

func (*Node) ChannelInvite

func (n *Node) ChannelInvite() *ChannelInvite

ChannelInvite returns the primary channel's active invite.

func (*Node) ChannelPeers

func (n *Node) ChannelPeers(channelID string) []string

ChannelPeers returns directly connected peers in channelID.

func (*Node) ChannelRingBuffer

func (n *Node) ChannelRingBuffer(channelID string) *RingBuffer

ChannelRingBuffer returns the RingBuffer for channelID.

func (*Node) CreateChannelInvite

func (n *Node) CreateChannelInvite(ttl time.Duration) (*ChannelInvite, error)

CreateChannelInvite generates a signed invitation for the primary room.

func (*Node) CreateChannelInviteForChannel

func (n *Node) CreateChannelInviteForChannel(channelID string, ttl time.Duration, inviteePub ...string) (*ChannelInvite, error)

CreateChannelInviteForChannel generates a signed invitation with provenance for channelID.

func (*Node) CurrentEpoch

func (n *Node) CurrentEpoch() int64

CurrentEpoch returns the primary room's current epoch counter.

func (*Node) DiscoverPeers

func (n *Node) DiscoverPeers()

DiscoverPeers initiates an expanding-ring peer_request broadcast to BroadcastAddr. Starts with InitialBroadcastTTL to InitialBroadcastFanout peers, doubling both every 2*TTL if unanswered.

func (*Node) DownloadAttachment

func (n *Node) DownloadAttachment(fileID string) error

DownloadAttachment initiates an on-demand pipelined download for fileID.

func (*Node) EvictPeer

func (n *Node) EvictPeer(targetAddr, reason string) (*EpochCommit, error)

EvictPeer locks targetAddr out of the primary room via an MLS Remove commit.

func (*Node) EvictPeerInChannel

func (n *Node) EvictPeerInChannel(channelID, targetAddr, reason string) (*EpochCommit, error)

EvictPeerInChannel locks targetAddr out of channelID while isolating other channels and DMs.

func (*Node) ExportSFrameKeys

func (n *Node) ExportSFrameKeys(scopeID string) (*SFrameKeyBundle, error)

ExportSFrameKeys computes and returns the current SFrameKeyBundle for scopeID.

func (*Node) GetAttachmentData

func (n *Node) GetAttachmentData(fileID string) ([]byte, error)

GetAttachmentData returns the assembled plaintext bytes for fileID if available.

func (*Node) HandleWire

func (n *Node) HandleWire(from string, data []byte)

HandleWire processes an incoming serialized Packet received over a WebRTC DataChannel.

func (*Node) InitChannelMLS

func (n *Node) InitChannelMLS(channelID string) error

InitChannelMLS establishes MLS Epoch 1 in channelID for the room creator.

func (*Node) InitGenesisEpoch

func (n *Node) InitGenesisEpoch() error

InitGenesisEpoch establishes MLS Epoch 1 in the primary room.

func (*Node) InvitedBy

func (n *Node) InvitedBy(peerAddr string) string

InvitedBy returns the inviter of peerAddr in the primary channel.

func (*Node) IsAdmittedMember

func (n *Node) IsAdmittedMember(addr string) bool

IsAdmittedMember reports whether addr is admitted in the primary channel.

func (*Node) IsAnchorPeer

func (n *Node) IsAnchorPeer(addr string) bool

IsAnchorPeer reports whether addr is currently marked as an anchor peer.

func (*Node) IsFallbackMode

func (n *Node) IsFallbackMode() bool

IsFallbackMode reports whether the node is in signaling fallback mode.

func (*Node) IsGatewayPeer

func (n *Node) IsGatewayPeer(addr string) bool

IsGatewayPeer reports whether addr is a signaling gateway peer.

func (*Node) IsInCall

func (n *Node) IsInCall(scopeID string) bool

IsInCall reports whether the local node is currently joined to a call in scopeID.

func (*Node) IsPeerEvicted

func (n *Node) IsPeerEvicted(addr string) bool

IsPeerEvicted reports whether addr has been evicted from the primary channel.

func (*Node) IsPeerEvictedInChannel

func (n *Node) IsPeerEvictedInChannel(channelID, addr string) bool

IsPeerEvictedInChannel reports whether addr has been evicted from channelID.

func (*Node) JoinAppDistChannel

func (n *Node) JoinAppDistChannel(roomID string, key RoomKey, pinnedPubHex string, minSeq uint64) error

JoinAppDistChannel joins a public app distribution group with a single pinned publisher key.

func (*Node) JoinCall

func (n *Node) JoinCall(scopeID string, isDM bool, opts CallOptions) (*SFrameKeyBundle, error)

JoinCall activates a call session scoped to an admitted MLS channel or 1:1 DM.

func (*Node) JoinChannel

func (n *Node) JoinChannel(channelID string) error

JoinChannel triggers expanding-ring discovery for an already-registered channel.

func (*Node) JoinChannelWithKey

func (n *Node) JoinChannelWithKey(channelID string, key RoomKey) error

JoinChannelWithKey registers and discovers a private channel.

func (*Node) JoinPrivateChannel

func (n *Node) JoinPrivateChannel(roomID string, key RoomKey, invite *ChannelInvite) error

JoinPrivateChannel joins an MLS-encrypted private group (>=6 target peers, short TTL).

func (*Node) JoinPublicChannel

func (n *Node) JoinPublicChannel(name string, psk RoomKey) error

JoinPublicChannel joins a PSK-encrypted public group (2 target peers, longer TTL).

func (*Node) JoinedEpoch

func (n *Node) JoinedEpoch() int64

JoinedEpoch returns the epoch when this node joined the primary channel.

func (*Node) Leave

func (n *Node) Leave() error

Leave broadcasts a signed voluntary departure packet and stops background loops.

func (*Node) LeaveCall

func (n *Node) LeaveCall(scopeID string) error

LeaveCall ends local participation in scopeID's call and notifies active peers.

func (*Node) MemberJoinEpoch

func (n *Node) MemberJoinEpoch(addr string) int64

MemberJoinEpoch returns the epoch at which addr joined the primary channel.

func (*Node) Overlay

func (n *Node) Overlay() *OverlayView

Overlay returns the node's HyParView membership view.

func (*Node) PeerEncKeys

func (n *Node) PeerEncKeys() map[string]string

PeerEncKeys returns a snapshot of known SignPub -> EncPub mappings.

func (*Node) Peers

func (n *Node) Peers() []string

Peers returns currently active non-gateway peer addresses.

func (*Node) QueryPeers

func (n *Node) QueryPeers()

QueryPeers is an alias for DiscoverPeers for convenient caller ergonomics.

func (*Node) RegisterAppBundle

func (n *Node) RegisterAppBundle(roomID string, key RoomKey, manifest *AppManifest, bundleBytes []byte, pinnedPubHex string) error

RegisterAppBundle verifies, chunks, and registers an application bundle for seeding in the public group.

func (*Node) RegisterDMScope

func (n *Node) RegisterDMScope(roomID, peerAddr string, key RoomKey) error

RegisterDMScope registers a 2-peer DM cryptographic scope for scoped A/V calls and SFrame keys.

func (*Node) RemoveGatewayPeer

func (n *Node) RemoveGatewayPeer(addr string)

RemoveGatewayPeer unmarks addr as a gateway peer.

func (*Node) RemovePeer

func (n *Node) RemovePeer(addr string)

RemovePeer removes a disconnected peer and triggers HyParView repair from the passive view.

func (*Node) RequestAppManifest

func (n *Node) RequestAppManifest(roomID, appID, channel string, minSeq uint64)

RequestAppManifest broadcasts an encrypted expanding-ring AppManifestRequest to the public seeder group.

func (*Node) RequestAttachment

func (n *Node) RequestAttachment(meta AttachmentMeta)

RequestAttachment stores meta and triggers DownloadAttachment.

func (*Node) RequestCatchUp

func (n *Node) RequestCatchUp() error

RequestCatchUp initiates expanding-ring targeted catch-up sync for the primary channel.

func (*Node) RequestCatchUpForChannel

func (n *Node) RequestCatchUpForChannel(channelID string) error

RequestCatchUpForChannel starts expanding-ring targeted sync (1 -> 2 -> 4 -> 8...) for channelID.

func (*Node) RequestCatchUpNextBatch

func (n *Node) RequestCatchUpNextBatch() ([]string, error)

RequestCatchUpNextBatch sends the next doubling batch of SyncRequest packets for the primary channel.

func (*Node) RequestCatchUpNextBatchForChannel

func (n *Node) RequestCatchUpNextBatchForChannel(channelID string) ([]string, error)

RequestCatchUpNextBatchForChannel targets live unqueried peers in doubling batches (1 -> 2 -> 4 -> 8).

func (*Node) RespondDirectInvite

func (n *Node) RespondDirectInvite(invite *DirectInvite, accepted bool) error

RespondDirectInvite sends a signed accept/decline response for invite.

func (*Node) RetryMissingChunks

func (n *Node) RetryMissingChunks(fileID string)

RetryMissingChunks broadcasts requests for any stale/missing chunks across the group mesh (swarm failover).

func (*Node) RotateEpochKey

func (n *Node) RotateEpochKey() (*EpochCommit, error)

RotateEpochKey ratchets the primary room to a new MLS epoch.

func (*Node) RotateEpochKeyInChannel

func (n *Node) RotateEpochKeyInChannel(channelID string) (*EpochCommit, error)

RotateEpochKeyInChannel ratchets channelID via an MLS Update commit.

func (*Node) SendCallSignal

func (n *Node) SendCallSignal(scopeID, target, kind, payload string) error

SendCallSignal encrypts a pairwise secondary WebRTC signal using Noise_IK and routes it via Packet.

func (*Node) SendChannelMessage

func (n *Node) SendChannelMessage(channelID, text string) (*Envelope, error)

SendChannelMessage encrypts, signs, and broadcasts a chat message in channelID.

func (*Node) SendDirectInvite

func (n *Node) SendDirectInvite(targetSignPub, inviteType, title string) (*DirectInvite, *InvitePayload, error)

SendDirectInvite creates and sends a Noise_IK encrypted 1:1 DM or breakout invite.

func (*Node) SendDirectInviteWithKey

func (n *Node) SendDirectInviteWithKey(targetSignPub, targetEncPubHex, inviteType, title string) (*DirectInvite, *InvitePayload, error)

SendDirectInviteWithKey creates and sends a Noise_IK encrypted invite using an explicit X25519 key.

func (*Node) SendMessage

func (n *Node) SendMessage(text string) (*Envelope, error)

SendMessage encrypts, signs, and broadcasts a chat message in the primary room.

func (*Node) SendViaRelay

func (n *Node) SendViaRelay(target, frameType string, payload []byte) error

SendViaRelay sends a unicast encrypted payload to target (used for DMs and pairwise frames).

func (*Node) SetChannelInvite

func (n *Node) SetChannelInvite(inv *ChannelInvite)

SetChannelInvite sets this node's invite for the primary channel.

func (*Node) SetChannelInviteForChannel

func (n *Node) SetChannelInviteForChannel(channelID string, inv *ChannelInvite)

SetChannelInviteForChannel associates an invite with channelID and announces PeerInfo.

func (*Node) SetFallbackMode

func (n *Node) SetFallbackMode(fb bool)

SetFallbackMode updates signaling fallback mode.

func (*Node) SetPeerEncKey

func (n *Node) SetPeerEncKey(signPub, encPub string)

SetPeerEncKey records a peer's X25519 encryption public key.

func (*Node) ShareAttachment

func (n *Node) ShareAttachment(name, mime string, data []byte) (*AttachmentMeta, error)

ShareAttachment chunks, encrypts, and announces a file attachment in the primary room.

func (*Node) ShareAttachmentInChannel

func (n *Node) ShareAttachmentInChannel(channelID, name, mime string, data []byte) (*AttachmentMeta, error)

ShareAttachmentInChannel broadcasts only AttachmentMeta (on-demand; chunks are never pushed).

func (*Node) SolicitAnchors

func (n *Node) SolicitAnchors(needed int, excludeAnchors []string)

SolicitAnchors asks healthy non-anchor peers to register with their signaling server.

func (*Node) StartMeshSupervisor

func (n *Node) StartMeshSupervisor(ctx context.Context, interval time.Duration)

StartMeshSupervisor runs the background HyParView + group quota maintenance loop.

func (*Node) StopMeshSupervisor

func (n *Node) StopMeshSupervisor()

StopMeshSupervisor stops all background mesh maintenance and expanding broadcasts.

func (*Node) UnregisterDMScope

func (n *Node) UnregisterDMScope(roomID string)

UnregisterDMScope closes any active call in roomID and deletes DM call key state.

func (*Node) UpdateCallOptions

func (n *Node) UpdateCallOptions(scopeID string, opts CallOptions) error

UpdateCallOptions broadcasts updated mic/cam/screen status within an active joined call.

func (*Node) VerifyChannelInvite

func (n *Node) VerifyChannelInvite(inv *ChannelInvite) error

VerifyChannelInvite validates a channel invitation's signature, expiry, and delegation chain.

type OverlayView

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

OverlayView implements HyParView Active/Passive peer views with group-aware quotas.

func NewOverlayView

func NewOverlayView(self string, cfg Config) *OverlayView

NewOverlayView creates a HyParView membership manager for local node self.

func (*OverlayView) ActivePeers

func (v *OverlayView) ActivePeers() []string

ActivePeers returns all active non-gateway peer addresses.

func (*OverlayView) AddActive

func (v *OverlayView) AddActive(signPub string, isGateway bool) bool

AddActive registers or refreshes an active peer connection.

func (*OverlayView) AddPassive

func (v *OverlayView) AddPassive(desc PeerDescriptor)

AddPassive inserts a peer descriptor into the bounded passive view.

func (*OverlayView) ChannelPeerCount

func (v *OverlayView) ChannelPeerCount(chHash uint32) int

ChannelPeerCount returns the number of active peers participating in chHash.

func (*OverlayView) EncKey

func (v *OverlayView) EncKey(signPub string) string

EncKey returns the known X25519 encryption key for signPub, if any.

func (*OverlayView) EncKeysSnapshot

func (v *OverlayView) EncKeysSnapshot() map[string]string

EncKeysSnapshot returns a copy of all known SignPub -> EncPub mappings.

func (*OverlayView) MarkAnchor

func (v *OverlayView) MarkAnchor(signPub string, isAnchor bool)

MarkAnchor sets anchor status on an active peer.

func (*OverlayView) MarkChannelPeer

func (v *OverlayView) MarkChannelPeer(signPub string, chHash uint32)

MarkChannelPeer associates an active peer with a channel hash.

func (*OverlayView) PassivePeers

func (v *OverlayView) PassivePeers() []PeerDescriptor

PassivePeers returns a snapshot of all passive descriptors.

func (*OverlayView) PickRepairCandidates

func (v *OverlayView) PickRepairCandidates(neededChannels map[uint32]bool, limit int) []PeerDescriptor

PickRepairCandidates selects up to limit disconnected peers from the passive view, prioritizing descriptors that advertise any channel hash in neededChannels.

func (*OverlayView) PickRotationVictim

func (v *OverlayView) PickRotationVictim(minByChannel map[uint32]int, grace time.Duration) string

PickRotationVictim returns a non-anchor, non-gateway active peer safe to rotate out without dropping any channel below its required minimum peer count.

func (*OverlayView) RemoveActive

func (v *OverlayView) RemoveActive(signPub string, keepInPassive bool) bool

RemoveActive removes a disconnected peer from the active view.

func (*OverlayView) RemovePassive

func (v *OverlayView) RemovePassive(signPub string)

RemovePassive deletes signPub from the passive view (e.g. on eviction).

func (*OverlayView) SampleDescriptors

func (v *OverlayView) SampleDescriptors(limit int, exclude string) []PeerDescriptor

SampleDescriptors returns up to limit random peer descriptors from active and passive views.

func (*OverlayView) SetEncKey

func (v *OverlayView) SetEncKey(signPub, encPub string)

SetEncKey records a peer's X25519 public encryption key.

type Packet

type Packet struct {
	ID          string `json:"id"`
	From        string `json:"from"`
	FromEnc     string `json:"from_enc,omitempty"`
	To          string `json:"to"`
	ChannelHash uint32 `json:"ch,omitempty"`
	EpochID     int64  `json:"epoch,omitempty"`
	HopLimit    int    `json:"hop"`
	HopStart    int    `json:"hop_start"`
	Timestamp   int64  `json:"ts"`
	Encrypted   bool   `json:"enc"`
	Port        Port   `json:"port,omitempty"`
	Payload     []byte `json:"payload"`
	Signature   string `json:"sig"`
}

Packet is the unified Meshtastic-inspired routed wire envelope for all Cotilla mesh traffic.

func NewGroupPacket

func NewGroupPacket(id *Identity, to string, chHash uint32, epochID int64, key RoomKey, port Port, hopLimit int, body any) (*Packet, error)

NewGroupPacket constructs a group-encrypted, Ed25519-signed packet for a public or private channel.

func NewPlainPacket

func NewPlainPacket(id *Identity, to string, port Port, hopLimit int, body any) (*Packet, error)

NewPlainPacket constructs and signs an unencrypted network discovery packet.

func NewUnicastPacket

func NewUnicastPacket(id *Identity, toSignPub, toEncPub string, port Port, hopLimit int, body any) (*Packet, error)

NewUnicastPacket constructs an X25519-encrypted, Ed25519-signed packet for one peer.

func UnmarshalPacket

func UnmarshalPacket(data []byte) (*Packet, error)

UnmarshalPacket deserializes a Packet from JSON.

type PacketCache

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

PacketCache provides bounded deduplication of seen packet IDs.

func NewPacketCache

func NewPacketCache(ttl time.Duration, maxSize int) *PacketCache

NewPacketCache creates a bounded PacketCache.

func (*PacketCache) MarkSeen

func (c *PacketCache) MarkSeen(id string) bool

MarkSeen records id and returns true if it was already present and unexpired.

type PeerDescriptor

type PeerDescriptor struct {
	SignPub       string   `json:"sign_pub"`
	EncPub        string   `json:"enc_pub,omitempty"`
	ChannelHashes []uint32 `json:"ch,omitempty"`
}

PeerDescriptor advertises a peer's addresses and joined channel hashes.

type PeerInfoFrame

type PeerInfoFrame struct {
	RoomID     string         `json:"room_id,omitempty"`
	SignPub    string         `json:"sign_pub"`
	EncPub     string         `json:"enc_pub"`
	Timestamp  int64          `json:"timestamp"`
	Signature  string         `json:"signature"`
	Invite     *ChannelInvite `json:"invite,omitempty"`
	KeyPackage *KeyPackage    `json:"key_package,omitempty"`
}

PeerInfoFrame announces a peer's credentials, invite provenance, and MLS KeyPackage.

type PeerRequestPayload

type PeerRequestPayload struct {
	WantCount     int      `json:"want"`
	KnownPeers    []string `json:"known,omitempty"`
	ChannelHashes []uint32 `json:"ch,omitempty"`
}

PeerRequestPayload is broadcast to BroadcastAddr to discover peers in the mesh.

type PeerResponsePayload

type PeerResponsePayload struct {
	RequestID string           `json:"req_id"`
	Peers     []PeerDescriptor `json:"peers"`
}

PeerResponsePayload is sent encrypted and signed back to the issuer of a PeerRequest.

type Port

type Port string

Port identifies the application or control handler for a Packet payload.

const (
	// Network & HyParView overlay ports
	PortPeerRequest       Port = "peer_request"
	PortPeerResponse      Port = "peer_response"
	PortWebRTCSignal      Port = "webrtc_signal"
	PortRootIntro         Port = "root_intro"
	PortAnchorSolicit     Port = "anchor_solicit"
	PortHyParViewShuffle  Port = "hyparview_shuffle"
	PortHyParViewNeighbor Port = "hyparview_neighbor"
	PortLeave             Port = "leave"

	// Group / Channel & MLS ports (always encrypted inside Packet.Payload)
	PortGroupDiscover Port = "group_discover"
	PortGroupPeerInfo Port = "group_peer_info"
	PortEpochCommit   Port = "epoch_commit"
	PortChat          Port = "chat"
	PortSyncReq       Port = "sync_req"
	PortSyncRes       Port = "sync_res"
	PortAttachMeta    Port = "attach_meta"
	PortChunkReq      Port = "chunk_req"
	PortChunkRes      Port = "chunk_res"

	// Public App Seeder Group ports (always encrypted inside Packet.Payload with group PSK)
	PortAppInviteReq   Port = "app_invite_req"
	PortAppManifestReq Port = "app_manifest_req"
	PortAppManifestRes Port = "app_manifest_res"

	// 1:1 Direct Messaging & Scoped Calls
	PortDirectInvite    Port = "direct_invite"
	PortDirectInviteRes Port = "direct_invite_res"
	PortDM              Port = "dm"
	PortCallCtrl        Port = "call_ctrl"
	PortCallSig         Port = "call_sig"
)

type RatchetTree

type RatchetTree struct {
	NumLeaves int
	Nodes     []*TreeKEMNode
}

RatchetTree represents an MLS Left-Balanced Binary Tree (RFC 9420 Section 7).

func NewRatchetTree

func NewRatchetTree(numLeaves int) *RatchetTree

NewRatchetTree constructs a left-balanced binary tree with numLeaves leaves.

func (*RatchetTree) Clone

func (t *RatchetTree) Clone() *RatchetTree

Clone returns an isolated deep copy of RatchetTree so failed commits never mutate live state.

func (*RatchetTree) CopathIndex

func (t *RatchetTree) CopathIndex(ancestorIdx, directChildIdx int) int

CopathIndex returns the sibling of the child along the direct path.

func (*RatchetTree) DirectPathIndices

func (t *RatchetTree) DirectPathIndices(leafIdx int) []int

DirectPathIndices returns the sequence of ancestor node indices from leaf to root.

func (*RatchetTree) Resolution

func (t *RatchetTree) Resolution(nodeIdx int) []int

Resolution returns the non-blank node indices that cover the subtree at nodeIdx, including any UnmergedLeaves on non-blank internal nodes (RFC 9420 Section 7.2).

func (*RatchetTree) RootIndex

func (t *RatchetTree) RootIndex() int

RootIndex returns the root node index of the tree.

func (*RatchetTree) TreeHash

func (t *RatchetTree) TreeHash() [32]byte

TreeHash computes the deterministic Merkle tree hash of the ratchet tree (RFC 9420 Section 7.7).

type RingBuffer

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

RingBuffer stores recent ephemeral envelopes in memory for catch-up and reconnect recovery.

func NewRingBuffer

func NewRingBuffer(capacity int, ttl time.Duration) *RingBuffer

NewRingBuffer creates a thread-safe ring buffer with the given capacity and message TTL.

func (*RingBuffer) All

func (rb *RingBuffer) All() []*Envelope

All returns a copy of all current unexpired envelopes in the ring buffer.

func (*RingBuffer) GetMissing

func (rb *RingBuffer) GetMissing(lastSeenID string, knownIDs []string) []*Envelope

GetMissing returns all unexpired envelopes that are not present in knownIDs. If lastSeenID is non-empty and found, only envelopes occurring after lastSeenID are considered.

func (*RingBuffer) GetMissingForEpochRange

func (rb *RingBuffer) GetMissingForEpochRange(lastSeenID string, knownIDs []string, minEpoch, maxEpoch int64) []*Envelope

GetMissingForEpochRange returns all unexpired envelopes not present in knownIDs within the specified epoch bounds. If minEpoch > 0, envelopes with EpochID < minEpoch are excluded (enforcing Pre-Join Forward Secrecy). If maxEpoch > 0, envelopes with EpochID > maxEpoch are excluded (enforcing Post-Eviction Confidentiality).

func (*RingBuffer) Len

func (rb *RingBuffer) Len() int

Len returns the number of active items in the ring buffer.

func (*RingBuffer) Push

func (rb *RingBuffer) Push(env *Envelope)

Push adds an envelope to the ring buffer, evicting expired items or the oldest items when full.

type RoomKey

type RoomKey [RoomKeySize]byte

RoomKey is a 256-bit symmetric room key.

func AppDistRoomKeyFor

func AppDistRoomKeyFor(distRoomID string) RoomKey

AppDistRoomKeyFor derives a deterministic RoomKey for any specified app-distribution room ID.

func DefaultAppDistRoomKey

func DefaultAppDistRoomKey() RoomKey

DefaultAppDistRoomKey derives a deterministic 256-bit symmetric RoomKey for the public distribution overlay channel.

func GenerateRoomKey

func GenerateRoomKey() (RoomKey, error)

GenerateRoomKey creates a new random 256-bit room key.

func ParseRoomKey

func ParseRoomKey(s string) (RoomKey, error)

ParseRoomKey parses a base64 (or hex) encoded 256-bit room key.

func (RoomKey) String

func (k RoomKey) String() string

String returns the URL-safe base64 encoding of the room key without padding.

type RootIntroFrame

type RootIntroFrame struct {
	AnchorPeers []string         `json:"anchor_peers"`
	Anchors     []PeerDescriptor `json:"anchors,omitempty"`
	Fallback    bool             `json:"fallback,omitempty"`
	IsAnchor    bool             `json:"is_anchor,omitempty"`
}

RootIntroFrame informs an arriving node of active anchor nodes and gateway encryption key.

type SFrameKeyBundle

type SFrameKeyBundle struct {
	ScopeID   string
	Epoch     uint64
	LeafIndex int
	Sender    SFrameKeyEntry
	Receivers []SFrameKeyEntry
}

SFrameKeyBundle represents a complete snapshot of sender and authorized receiver keys for an MLS channel epoch or 1:1 DM session.

func BuildDMSFrameBundle

func BuildDMSFrameBundle(roomID string, key RoomKey, selfAddr, peerAddr string) (*SFrameKeyBundle, error)

BuildDMSFrameBundle derives an SFrameKeyBundle for a 2-peer 1:1 DM session.

func (*SFrameKeyBundle) Zeroize

func (b *SFrameKeyBundle) Zeroize()

Zeroize overwrites all sensitive key material within the bundle.

type SFrameKeyEntry

type SFrameKeyEntry struct {
	KID       uint64
	Epoch     uint64
	LeafIndex int
	Address   string
	Key       [sframeKeySize]byte
	Salt      [sframeSaltSize]byte
}

SFrameKeyEntry stores derived RFC 9605 AES-128-GCM key + salt for a specific (epoch, leafIndex).

func DeriveLeafSFrameKey

func DeriveLeafSFrameKey(epochBaseSecret []byte, epoch uint64, leafIndex int, addr string) (SFrameKeyEntry, error)

DeriveLeafSFrameKey derives the RFC 9605 key and salt for (epoch, leafIndex, address) from an epoch-level 32-byte exported base secret. For open/DM rooms (useOpenKID=true), the KID is bound immutably to addr instead of mutable leaf indices.

func (*SFrameKeyEntry) Zeroize

func (e *SFrameKeyEntry) Zeroize()

Zeroize overwrites sensitive key/salt bytes in memory.

type SFrameKeyring

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

SFrameKeyring manages stateful SFrame encryption (monotonic TX counter) and decryption (anti-replay sliding window, epoch grace retention, and instant leaf revocation).

func NewSFrameKeyring

func NewSFrameKeyring() *SFrameKeyring

NewSFrameKeyring creates an empty SFrameKeyring.

func (*SFrameKeyring) Clear

func (kr *SFrameKeyring) Clear()

Clear zeroizes all keys in the keyring.

func (*SFrameKeyring) Decrypt

func (kr *SFrameKeyring) Decrypt(frame []byte, expectedFrom string) ([]byte, uint64, error)

Decrypt authenticates and decrypts an SFrame frame, validating peer ownership and counter replay bounds. If expectedFrom is non-empty, the matching KID's leaf address must match expectedFrom.

func (*SFrameKeyring) Encrypt

func (kr *SFrameKeyring) Encrypt(plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext under the current sender key with a strictly increasing counter.

func (*SFrameKeyring) InstallBundle

func (kr *SFrameKeyring) InstallBundle(b *SFrameKeyBundle, graceDuration time.Duration) error

InstallBundle replaces the active sender key and receiver keys, retaining previous epoch receiver keys for graceDuration so in-flight RTP packets across benign epoch transitions settle.

func (*SFrameKeyring) RevokeLeaf

func (kr *SFrameKeyring) RevokeLeaf(leafIndex int)

RevokeLeaf immediately zeroizes and removes all receiver keys for leafIndex across all epochs.

func (*SFrameKeyring) RevokePeer

func (kr *SFrameKeyring) RevokePeer(peerAddr string)

RevokePeer immediately zeroizes and removes all receiver keys belonging to peerAddr.

type SealedData

type SealedData struct {
	Port Port            `json:"port"`
	Body json.RawMessage `json:"body"`
}

SealedData is the decrypted inner payload when Packet.Encrypted is true.

func OpenGroupPacket

func OpenGroupPacket(key RoomKey, p *Packet) (*SealedData, error)

OpenGroupPacket decrypts a group Packet's inner SealedData using key.

func OpenUnicastPacket

func OpenUnicastPacket(id *Identity, p *Packet) (*SealedData, error)

OpenUnicastPacket decrypts a unicast Packet's inner SealedData.

type SeederGroupConfig

type SeederGroupConfig struct {
	Name    string `json:"name"`
	PSK     string `json:"psk,omitempty"`     // Optional base64 256-bit PSK; derived from Name if empty
	Channel string `json:"channel,omitempty"` // Distribution track, e.g. "stable"
}

SeederGroupConfig configures the public PSK group used for P2P app distribution.

type ShufflePayload

type ShufflePayload struct {
	Origin        PeerDescriptor   `json:"origin"`
	Peers         []PeerDescriptor `json:"peers"`
	RemainingHops int              `json:"hops,omitempty"`
	IsReply       bool             `json:"is_reply,omitempty"`
	RequestID     string           `json:"req_id,omitempty"`
}

ShufflePayload exchanges HyParView active/passive peer samples for mesh healing.

type SyncRequest

type SyncRequest struct {
	RoomID        string   `json:"room_id,omitempty"`
	LastSeenMsgID string   `json:"last_seen_msg_id,omitempty"`
	KnownIDs      []string `json:"known_ids,omitempty"`
	CurrentEpoch  int64    `json:"current_epoch,omitempty"`
}

SyncRequest asks connected peers for missing envelopes after joining or reconnecting.

type SyncResponse

type SyncResponse struct {
	RoomID    string            `json:"room_id,omitempty"`
	Envelopes []*Envelope       `json:"envelopes"`
	Offers    []*AttachmentMeta `json:"offers,omitempty"`
	Commits   []*EpochCommit    `json:"commits,omitempty"`
}

SyncResponse returns missing envelopes, attachment offers, and MLS epoch commits.

type Transport

type Transport interface {
	Send(addr string, data []byte) error
	Broadcast(data []byte)
	Peers() []string
	ClosePeer(addr string)
}

Transport defines the communication interface for sending packets over WebRTC DataChannels.

type TreeKEMNode

type TreeKEMNode struct {
	Index          int       `json:"index"`
	LeafIndex      int       `json:"leaf_index"` // >= 0 for leaves, -1 for internal nodes
	Blank          bool      `json:"blank"`
	PublicKey      [32]byte  `json:"public_key"`
	PrivateKey     *[32]byte `json:"-"` // held only if local peer knows this node's private key
	Identity       *Identity `json:"-"` // held for local or peer leaf credential
	SignPubHex     string    `json:"sign_pub_hex,omitempty"`
	JoinedEpoch    uint64    `json:"joined_epoch,omitempty"`
	UnmergedLeaves []int     `json:"unmerged_leaves,omitempty"` // RFC 9420 §7.2: leaves added under non-blank node lacking its private key
	Parent         int       `json:"parent"`
	Left           int       `json:"left"`
	Right          int       `json:"right"`
}

TreeKEMNode represents a node in the MLS ratchet tree (RFC 9420 Section 7). Even node indices represent leaves (node = 2*leaf); odd indices represent internal nodes.

type WebRTCSignalPayload

type WebRTCSignalPayload struct {
	Kind string `json:"kind"` // "offer" | "answer"
	SDP  string `json:"sdp"`
}

WebRTCSignalPayload carries an encrypted WebRTC SDP offer/answer routed across the mesh.

type WebRTCTransport

type WebRTCTransport interface {
	Transport
	CreateOffer(peerAddr string) (string, error)
	AcceptOffer(peerAddr, offerSDP string) (string, error)
	AcceptAnswer(peerAddr, answerSDP string) error
}

WebRTCTransport extends Transport with SDP offer/answer handshake methods.

Jump to

Keyboard shortcuts

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