Documentation
¶
Index ¶
- Constants
- Variables
- func CanonicalAppManifest(m *AppManifest) []byte
- func CanonicalAttachMeta(roomID, fileID, hash, name, mime, author string, size int64, totalChunks int, ...) []byte
- func CanonicalCallControl(scopeID, authorPub, nonceHex, ciphertextHex string, epochID, timestamp int64, ...) []byte
- func CanonicalCallControlAAD(scopeID, authorPub string, epochID, timestamp int64, isDM bool) []byte
- func CanonicalCallSignal(fromSignPub, fromEncPub, toSignPub, ePubHex, nonceHex, ciphertextHex string, ...) []byte
- func CanonicalCallSignalAAD(fromSignPub, toSignPub string, timestamp int64) []byte
- func CanonicalChannelAnswer(channelID, sessionToken, targetPub, responderPub, sdpAnswer string, ...) []byte
- func CanonicalChannelInvite(roomID, inviterPub, roomKey string, epochID, expiresAt int64) []byte
- func CanonicalChannelInviteWithInvitee(roomID, inviterPub, inviteePub, roomKey string, epochID, expiresAt int64) []byte
- func CanonicalChannelOffer(queryID, channelID, sessionToken, responderPub, sdpOffer string, ...) []byte
- func CanonicalChannelQuery(queryID, channelID, sessionToken, senderPub string, timestamp int64) []byte
- func CanonicalDirectInvite(...) []byte
- func CanonicalEnvelopePayload(roomID, authorPubKey, nonce, ciphertext string, epochID, timestamp int64) []byte
- func CanonicalEpochCommit(epochID int64, ...) []byte
- func CanonicalEpochCommitFromCommit(c *EpochCommit) []byte
- func CanonicalInviteResponse(inviteID, fromSignPub, toSignPub string, accepted bool, timestamp int64) []byte
- func CanonicalLeave(peer string, timestamp int64) []byte
- func CanonicalPacket(p *Packet) []byte
- func CanonicalPeerInfo(signPub, encPub string, timestamp int64) []byte
- func CanonicalPeerSignal(signalID, kind, from, target, sdp string, timestamp int64) []byte
- func CanonicalRelayFrame(from, target, relayType string, payload []byte, timestamp int64) []byte
- func CanonicalSignalingMsg(msgType, peer, target, sdp string, timestamp int64) []byte
- func ComputeChannelHash(name string, psk RoomKey) uint32
- func ComputeMLSCommitDigest(c *EpochCommit) string
- func DecodeSFrameHeader(frame []byte) (kid, ctr uint64, headerLen int, err error)
- func DecryptDirectInvite(recipient *Identity, senderEncPub [32]byte, ePub [32]byte, ...) ([]byte, error)
- func DecryptRoomPayload(key RoomKey, nonce []byte, ciphertext []byte, aad []byte) ([]byte, error)
- func DeriveNoiseIKInviteKey(ePriv [32]byte, staticPriv [32]byte, peerEncPub [32]byte) ([]byte, error)
- func DeriveNoiseIKInviteKeyRecipient(recipientPriv [32]byte, ePub [32]byte, senderEncPub [32]byte) ([]byte, error)
- func EncodeCanonical(tag string, fields ...string) []byte
- func EncodeSFrameHeader(kid, ctr uint64) []byte
- func EncryptDirectInvite(sender *Identity, recipientEncPub [32]byte, payloadBytes []byte, aad []byte) (ePub [32]byte, nonce []byte, ciphertext []byte, err error)
- func EncryptRoomPayload(key RoomKey, plaintext []byte, aad []byte) (nonce []byte, ciphertext []byte, err error)
- func GeneratePublisherKeypair() (pubHex, privHex string, err error)
- func InviteKeyCommitment(roomKey string) string
- func MakeOpenSFrameKID(addr string) uint64
- func MakeSFrameKID(epoch uint64, leafIndex int) (uint64, error)
- func MarshalPacket(p *Packet) ([]byte, error)
- func OpenGroupPayload(key RoomKey, sealed, aad []byte) ([]byte, error)
- func OpenUnicast(recipient *Identity, senderEncHex string, sealed, aad []byte) ([]byte, error)
- func PacketAAD(p *Packet) []byte
- func ParseEncPub(hexStr string) ([32]byte, error)
- func RandomID() string
- func SFrameEncryptFrame(entry SFrameKeyEntry, ctr uint64, plaintext []byte) ([]byte, error)
- func SealGroupPayload(key RoomKey, plaintext, aad []byte) ([]byte, error)
- func SealUnicast(sender *Identity, recipientEncHex string, plaintext, aad []byte) ([]byte, error)
- func SignAppManifest(privHex string, m *AppManifest) error
- func SignPacket(id *Identity, p *Packet)
- func SplitSFrameKID(kid uint64) (epoch uint64, leafIndex int)
- func Verify(pubHex string, msg []byte, sigHex string) bool
- func VerifyAppBundle(m *AppManifest, bundleBytes []byte, ...) error
- func VerifyAppBundleWithKeys(m *AppManifest, bundleBytes []byte, validPubKeys []string, ...) error
- func VerifyAppManifest(m *AppManifest, pinnedPubHex, expectedAppID, expectedChannel string, ...) error
- func VerifyAppManifestWithKeys(m *AppManifest, validPubKeys []string, ...) error
- func VerifyPacket(p *Packet, maxHop int, replayWindow time.Duration) error
- type ActivePeer
- type AnchorSolicitFrame
- type AppBootstrapConfig
- type AppManifest
- type AppManifestRequest
- type AppManifestResponse
- type AttachmentAssembler
- func (a *AttachmentAssembler) AddChunk(index int, packedData []byte) (bool, error)
- func (a *AttachmentAssembler) Assemble() ([]byte, error)
- func (a *AttachmentAssembler) Data() []byte
- func (a *AttachmentAssembler) ExportRawChunks() [][]byte
- func (a *AttachmentAssembler) IsComplete() bool
- func (a *AttachmentAssembler) MissingChunks() []int
- func (a *AttachmentAssembler) NextMissingChunks(maxInFlight int) []int
- func (a *AttachmentAssembler) Progress() (int, int)
- func (a *AttachmentAssembler) RawChunk(index int) []byte
- func (a *AttachmentAssembler) ReceivedCount() int
- func (a *AttachmentAssembler) ResetUnreceivedRequests()
- func (a *AttachmentAssembler) RetryStaleRequests(timeout time.Duration) int
- type AttachmentMeta
- type BroadcastEmitFunc
- type CallControlFrame
- type CallOptions
- type CallPeerState
- type CallPresencePayload
- type CallSignalFrame
- type CallSignalPayload
- type ChannelInvite
- type ChannelKind
- type ChannelState
- type ChatPayload
- type ChunkRequest
- type ChunkResponse
- type Config
- type DMFrame
- type DirectInvite
- type DirectPath
- type DirectPathNode
- type Envelope
- type EpochCommit
- type ExpandingBroadcaster
- type ExportedNode
- type GroupContext
- type GroupDiscoverPayload
- type HPKECipher
- type Hooks
- type Identity
- type InvitePayload
- type InviteResponse
- type KeyPackage
- type LeafSnapshot
- type LeaveFrame
- type MLSCommit
- type MLSGroup
- func (g *MLSGroup) ApplicationSecretBytes() [32]byte
- func (g *MLSGroup) CreateAddCommit(pkg *KeyPackage) (*MLSCommit, *MLSWelcome, error)
- func (g *MLSGroup) CreateRemoveCommit(targetLeaf int) (*MLSCommit, error)
- func (g *MLSGroup) CreateUpdateCommit() (*MLSCommit, error)
- func (g *MLSGroup) EnsureMemberLeaf(signPubHex string, initKey [32]byte) int
- func (g *MLSGroup) Export(label string, context []byte, length int) ([]byte, error)
- func (g *MLSGroup) FindLeafByAddress(signPubHex string) int
- func (g *MLSGroup) GroupContext() GroupContext
- func (g *MLSGroup) ProcessCommit(commit *MLSCommit) error
- func (g *MLSGroup) SnapshotForSFrame(label string, context []byte) (epoch uint64, myLeaf int, leaves []LeafSnapshot, exported []byte, err error)
- type MLSWelcome
- type Node
- func (n *Node) ActiveCallPeers(scopeID string) []CallPeerState
- func (n *Node) ActiveChannels() []string
- func (n *Node) AddAnchorPeer(addr string)
- func (n *Node) AddGatewayPeer(addr string)
- func (n *Node) AddPeer(addr string)
- func (n *Node) Address() string
- func (n *Node) AnchorPeers() []string
- func (n *Node) AttachmentOffers() []*AttachmentMeta
- func (n *Node) BootstrapApp(cfg AppBootstrapConfig) (RoomKey, error)
- func (n *Node) BroadcastPeerInfo()
- func (n *Node) ChannelCurrentEpoch(channelID string) int64
- func (n *Node) ChannelInvite() *ChannelInvite
- func (n *Node) ChannelPeers(channelID string) []string
- func (n *Node) ChannelRingBuffer(channelID string) *RingBuffer
- func (n *Node) CreateChannelInvite(ttl time.Duration) (*ChannelInvite, error)
- func (n *Node) CreateChannelInviteForChannel(channelID string, ttl time.Duration, inviteePub ...string) (*ChannelInvite, error)
- func (n *Node) CurrentEpoch() int64
- func (n *Node) DiscoverPeers()
- func (n *Node) DownloadAttachment(fileID string) error
- func (n *Node) EvictPeer(targetAddr, reason string) (*EpochCommit, error)
- func (n *Node) EvictPeerInChannel(channelID, targetAddr, reason string) (*EpochCommit, error)
- func (n *Node) ExportSFrameKeys(scopeID string) (*SFrameKeyBundle, error)
- func (n *Node) GetAttachmentData(fileID string) ([]byte, error)
- func (n *Node) HandleWire(from string, data []byte)
- func (n *Node) InitChannelMLS(channelID string) error
- func (n *Node) InitGenesisEpoch() error
- func (n *Node) InvitedBy(peerAddr string) string
- func (n *Node) IsAdmittedMember(addr string) bool
- func (n *Node) IsAnchorPeer(addr string) bool
- func (n *Node) IsFallbackMode() bool
- func (n *Node) IsGatewayPeer(addr string) bool
- func (n *Node) IsInCall(scopeID string) bool
- func (n *Node) IsPeerEvicted(addr string) bool
- func (n *Node) IsPeerEvictedInChannel(channelID, addr string) bool
- func (n *Node) JoinAppDistChannel(roomID string, key RoomKey, pinnedPubHex string, minSeq uint64) error
- func (n *Node) JoinCall(scopeID string, isDM bool, opts CallOptions) (*SFrameKeyBundle, error)
- func (n *Node) JoinChannel(channelID string) error
- func (n *Node) JoinChannelWithKey(channelID string, key RoomKey) error
- func (n *Node) JoinPrivateChannel(roomID string, key RoomKey, invite *ChannelInvite) error
- func (n *Node) JoinPublicChannel(name string, psk RoomKey) error
- func (n *Node) JoinedEpoch() int64
- func (n *Node) Leave() error
- func (n *Node) LeaveCall(scopeID string) error
- func (n *Node) MemberJoinEpoch(addr string) int64
- func (n *Node) Overlay() *OverlayView
- func (n *Node) PeerEncKeys() map[string]string
- func (n *Node) Peers() []string
- func (n *Node) QueryPeers()
- func (n *Node) RegisterAppBundle(roomID string, key RoomKey, manifest *AppManifest, bundleBytes []byte, ...) error
- func (n *Node) RegisterDMScope(roomID, peerAddr string, key RoomKey) error
- func (n *Node) RemoveGatewayPeer(addr string)
- func (n *Node) RemovePeer(addr string)
- func (n *Node) RequestAppManifest(roomID, appID, channel string, minSeq uint64)
- func (n *Node) RequestAttachment(meta AttachmentMeta)
- func (n *Node) RequestCatchUp() error
- func (n *Node) RequestCatchUpForChannel(channelID string) error
- func (n *Node) RequestCatchUpNextBatch() ([]string, error)
- func (n *Node) RequestCatchUpNextBatchForChannel(channelID string) ([]string, error)
- func (n *Node) RespondDirectInvite(invite *DirectInvite, accepted bool) error
- func (n *Node) RetryMissingChunks(fileID string)
- func (n *Node) RotateEpochKey() (*EpochCommit, error)
- func (n *Node) RotateEpochKeyInChannel(channelID string) (*EpochCommit, error)
- func (n *Node) SendCallSignal(scopeID, target, kind, payload string) error
- func (n *Node) SendChannelMessage(channelID, text string) (*Envelope, error)
- func (n *Node) SendDirectInvite(targetSignPub, inviteType, title string) (*DirectInvite, *InvitePayload, error)
- func (n *Node) SendDirectInviteWithKey(targetSignPub, targetEncPubHex, inviteType, title string) (*DirectInvite, *InvitePayload, error)
- func (n *Node) SendMessage(text string) (*Envelope, error)
- func (n *Node) SendViaRelay(target, frameType string, payload []byte) error
- func (n *Node) SetChannelInvite(inv *ChannelInvite)
- func (n *Node) SetChannelInviteForChannel(channelID string, inv *ChannelInvite)
- func (n *Node) SetFallbackMode(fb bool)
- func (n *Node) SetPeerEncKey(signPub, encPub string)
- func (n *Node) ShareAttachment(name, mime string, data []byte) (*AttachmentMeta, error)
- func (n *Node) ShareAttachmentInChannel(channelID, name, mime string, data []byte) (*AttachmentMeta, error)
- func (n *Node) SolicitAnchors(needed int, excludeAnchors []string)
- func (n *Node) StartMeshSupervisor(ctx context.Context, interval time.Duration)
- func (n *Node) StopMeshSupervisor()
- func (n *Node) UnregisterDMScope(roomID string)
- func (n *Node) UpdateCallOptions(scopeID string, opts CallOptions) error
- func (n *Node) VerifyChannelInvite(inv *ChannelInvite) error
- type OverlayView
- func (v *OverlayView) ActivePeers() []string
- func (v *OverlayView) AddActive(signPub string, isGateway bool) bool
- func (v *OverlayView) AddPassive(desc PeerDescriptor)
- func (v *OverlayView) ChannelPeerCount(chHash uint32) int
- func (v *OverlayView) EncKey(signPub string) string
- func (v *OverlayView) EncKeysSnapshot() map[string]string
- func (v *OverlayView) MarkAnchor(signPub string, isAnchor bool)
- func (v *OverlayView) MarkChannelPeer(signPub string, chHash uint32)
- func (v *OverlayView) PassivePeers() []PeerDescriptor
- func (v *OverlayView) PickRepairCandidates(neededChannels map[uint32]bool, limit int) []PeerDescriptor
- func (v *OverlayView) PickRotationVictim(minByChannel map[uint32]int, grace time.Duration) string
- func (v *OverlayView) RemoveActive(signPub string, keepInPassive bool) bool
- func (v *OverlayView) RemovePassive(signPub string)
- func (v *OverlayView) SampleDescriptors(limit int, exclude string) []PeerDescriptor
- func (v *OverlayView) SetEncKey(signPub, encPub string)
- type Packet
- func NewGroupPacket(id *Identity, to string, chHash uint32, epochID int64, key RoomKey, port Port, ...) (*Packet, error)
- func NewPlainPacket(id *Identity, to string, port Port, hopLimit int, body any) (*Packet, error)
- func NewUnicastPacket(id *Identity, toSignPub, toEncPub string, port Port, hopLimit int, body any) (*Packet, error)
- func UnmarshalPacket(data []byte) (*Packet, error)
- type PacketCache
- type PeerDescriptor
- type PeerInfoFrame
- type PeerRequestPayload
- type PeerResponsePayload
- type Port
- type RatchetTree
- func (t *RatchetTree) Clone() *RatchetTree
- func (t *RatchetTree) CopathIndex(ancestorIdx, directChildIdx int) int
- func (t *RatchetTree) DirectPathIndices(leafIdx int) []int
- func (t *RatchetTree) Resolution(nodeIdx int) []int
- func (t *RatchetTree) RootIndex() int
- func (t *RatchetTree) TreeHash() [32]byte
- type RingBuffer
- func (rb *RingBuffer) All() []*Envelope
- func (rb *RingBuffer) GetMissing(lastSeenID string, knownIDs []string) []*Envelope
- func (rb *RingBuffer) GetMissingForEpochRange(lastSeenID string, knownIDs []string, minEpoch, maxEpoch int64) []*Envelope
- func (rb *RingBuffer) Len() int
- func (rb *RingBuffer) Push(env *Envelope)
- type RoomKey
- type RootIntroFrame
- type SFrameKeyBundle
- type SFrameKeyEntry
- type SFrameKeyring
- func (kr *SFrameKeyring) Clear()
- func (kr *SFrameKeyring) Decrypt(frame []byte, expectedFrom string) ([]byte, uint64, error)
- func (kr *SFrameKeyring) Encrypt(plaintext []byte) ([]byte, error)
- func (kr *SFrameKeyring) InstallBundle(b *SFrameKeyBundle, graceDuration time.Duration) error
- func (kr *SFrameKeyring) RevokeLeaf(leafIndex int)
- func (kr *SFrameKeyring) RevokePeer(peerAddr string)
- type SealedData
- type SeederGroupConfig
- type ShufflePayload
- type SyncRequest
- type SyncResponse
- type Transport
- type TreeKEMNode
- type WebRTCSignalPayload
- type WebRTCTransport
Constants ¶
const ( DefaultAppDistRoomID = "cotilla-app-dist-v1" DefaultAppID = "cotilla-web" DefaultAppChannel = "stable" FormatSingleHTMLV1 = "single-html-v1" FormatBundleV1 = "bundle-v1" )
Public distribution constants
const BroadcastAddr = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
BroadcastAddr is the universal destination address for mesh broadcasts (32-byte 0xFF hex).
const DefaultChunkSize = 64 * 1024
DefaultChunkSize is 64 KB as specified.
const MaxAttachmentChunks = 16384 // 16384 * 64KB = 1 GB
MaxAttachmentChunks caps allocated chunk slots to guard against OOM / DoS on untrusted metadata.
const MaxAttachmentSize int64 = 1 << 30 // 1 GB
MaxAttachmentSize caps declared file size.
const MaxTreeLeaves = 8192
MaxTreeLeaves caps decoded RatchetTree leaf count to prevent DoS allocations on malformed commits.
const RoomKeySize = 32
RoomKeySize is 32 bytes (256 bits).
const (
SFrameCipherAES128GCM uint16 = 0x0001
)
RFC 9605 SFrame constants for AES_128_GCM_SHA256_128.
Variables ¶
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") )
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 ¶
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 ¶
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 ¶
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 ¶
CanonicalLeave returns length-prefixed canonical bytes for signing a voluntary departure frame.
func CanonicalPacket ¶
CanonicalPacket computes immutable canonical bytes for Ed25519 signing (excludes HopLimit).
func CanonicalPeerInfo ¶
CanonicalPeerInfo returns length-prefixed canonical bytes for signing peer discovery frames.
func CanonicalPeerSignal ¶
CanonicalPeerSignal returns canonical bytes for authenticating PeerSignal frames.
func CanonicalRelayFrame ¶
CanonicalRelayFrame returns canonical bytes for authenticating a peer-to-peer relay envelope.
func CanonicalSignalingMsg ¶
CanonicalSignalingMsg returns canonical bytes for authenticating WebRTC signaling /ws control messages.
func ComputeChannelHash ¶
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 ¶
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 ¶
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 ¶
EncodeCanonical serializes a domain tag and variable-length string fields using unambiguous length-prefixing. Format: tag + "|" + len(f0) + ":" + f0 + "|" + len(f1) + ":" + f1 ...
func EncodeSFrameHeader ¶
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 ¶
GeneratePublisherKeypair generates a new random Ed25519 keypair for signing app bundles.
func InviteKeyCommitment ¶
InviteKeyCommitment derives a non-reversible SHA-256 key commitment for channel invitations.
func MakeOpenSFrameKID ¶
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 ¶
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 ¶
MarshalPacket serializes a Packet to JSON (see TODO.md §4 for future Protobuf migration).
func OpenGroupPayload ¶
OpenGroupPayload decrypts a [24B nonce || ciphertext] group payload.
func OpenUnicast ¶
OpenUnicast decrypts a payload produced by SealUnicast from senderEncHex.
func PacketAAD ¶
PacketAAD binds immutable routing headers into the AEAD additional authenticated data.
func ParseEncPub ¶
ParseEncPub decodes a hex-encoded 32-byte X25519 public key.
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 ¶
SealGroupPayload encrypts plaintext with key and AAD into [24B nonce || ciphertext].
func SealUnicast ¶
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 ¶
SignPacket signs p with id and populates p.Signature.
func SplitSFrameKID ¶
SplitSFrameKID extracts the epoch and leaf index (or epoch=0, leafIndex=-1 for open KIDs).
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.
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 ¶
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 ¶
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 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 ¶
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 ¶
Decrypt opens the envelope using roomKey and verifies integrity against context AAD.
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 ¶
NewIdentity generates a fresh random client identity.
func NewIdentityFromSeed ¶
NewIdentityFromSeed derives a deterministic Identity from a >=16 byte seed.
func (*Identity) Address ¶
Address returns the hex-encoded Ed25519 public key — the participant's identity.
func (*Identity) EncAddress ¶
EncAddress returns the hex-encoded X25519 public encryption 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 ¶
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 ¶
ApplicationSecretBytes returns the 32-byte symmetric key for encrypting room traffic in this epoch.
func (*MLSCommit) CanonicalBytesWithConfirmation ¶
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 ¶
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 (*MLSGroup) CreateAddCommit ¶
func (g *MLSGroup) CreateAddCommit(pkg *KeyPackage) (*MLSCommit, *MLSWelcome, error)
func (*MLSGroup) CreateRemoveCommit ¶
CreateRemoveCommit proposes and commits removing (evicting) a member from targetLeaf.
func (*MLSGroup) CreateUpdateCommit ¶
CreateUpdateCommit performs continuous asymmetric key ratcheting (PCS) for the committer.
func (*MLSGroup) EnsureMemberLeaf ¶
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 ¶
Export implements RFC 9420 Section 8.5 MLS-Exporter bound to the current epoch's ExporterSecret.
func (*MLSGroup) FindLeafByAddress ¶
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 ¶
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 ¶
ActiveChannels returns the list of joined channel IDs.
func (*Node) AddAnchorPeer ¶
AddAnchorPeer registers addr as an anchor peer.
func (*Node) AddGatewayPeer ¶
AddGatewayPeer marks addr as a signaling gateway DataChannel peer.
func (*Node) AddPeer ¶
AddPeer records an open WebRTC peer in HyParView and triggers initial offer sync.
func (*Node) AnchorPeers ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GetAttachmentData returns the assembled plaintext bytes for fileID if available.
func (*Node) HandleWire ¶
HandleWire processes an incoming serialized Packet received over a WebRTC DataChannel.
func (*Node) InitChannelMLS ¶
InitChannelMLS establishes MLS Epoch 1 in channelID for the room creator.
func (*Node) InitGenesisEpoch ¶
InitGenesisEpoch establishes MLS Epoch 1 in the primary room.
func (*Node) IsAdmittedMember ¶
IsAdmittedMember reports whether addr is admitted in the primary channel.
func (*Node) IsAnchorPeer ¶
IsAnchorPeer reports whether addr is currently marked as an anchor peer.
func (*Node) IsFallbackMode ¶
IsFallbackMode reports whether the node is in signaling fallback mode.
func (*Node) IsGatewayPeer ¶
IsGatewayPeer reports whether addr is a signaling gateway peer.
func (*Node) IsInCall ¶
IsInCall reports whether the local node is currently joined to a call in scopeID.
func (*Node) IsPeerEvicted ¶
IsPeerEvicted reports whether addr has been evicted from the primary channel.
func (*Node) IsPeerEvictedInChannel ¶
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 ¶
JoinChannel triggers expanding-ring discovery for an already-registered channel.
func (*Node) JoinChannelWithKey ¶
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 ¶
JoinPublicChannel joins a PSK-encrypted public group (2 target peers, longer TTL).
func (*Node) JoinedEpoch ¶
JoinedEpoch returns the epoch when this node joined the primary channel.
func (*Node) Leave ¶
Leave broadcasts a signed voluntary departure packet and stops background loops.
func (*Node) LeaveCall ¶
LeaveCall ends local participation in scopeID's call and notifies active peers.
func (*Node) MemberJoinEpoch ¶
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 ¶
PeerEncKeys returns a snapshot of known SignPub -> EncPub mappings.
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 ¶
RegisterDMScope registers a 2-peer DM cryptographic scope for scoped A/V calls and SFrame keys.
func (*Node) RemoveGatewayPeer ¶
RemoveGatewayPeer unmarks addr as a gateway peer.
func (*Node) RemovePeer ¶
RemovePeer removes a disconnected peer and triggers HyParView repair from the passive view.
func (*Node) RequestAppManifest ¶
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 ¶
RequestCatchUp initiates expanding-ring targeted catch-up sync for the primary channel.
func (*Node) RequestCatchUpForChannel ¶
RequestCatchUpForChannel starts expanding-ring targeted sync (1 -> 2 -> 4 -> 8...) for channelID.
func (*Node) RequestCatchUpNextBatch ¶
RequestCatchUpNextBatch sends the next doubling batch of SyncRequest packets for the primary channel.
func (*Node) RequestCatchUpNextBatchForChannel ¶
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 ¶
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 ¶
SendCallSignal encrypts a pairwise secondary WebRTC signal using Noise_IK and routes it via Packet.
func (*Node) SendChannelMessage ¶
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 ¶
SendMessage encrypts, signs, and broadcasts a chat message in the primary room.
func (*Node) SendViaRelay ¶
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 ¶
SetFallbackMode updates signaling fallback mode.
func (*Node) SetPeerEncKey ¶
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 ¶
SolicitAnchors asks healthy non-anchor peers to register with their signaling server.
func (*Node) StartMeshSupervisor ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GenerateRoomKey creates a new random 256-bit room key.
func ParseRoomKey ¶
ParseRoomKey parses a base64 (or hex) encoded 256-bit room key.
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 ¶
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.
Source Files
¶
- app_dist.go
- app_manifest.go
- attachment.go
- broadcast.go
- calls_media.go
- calls_signaling.go
- channel.go
- config.go
- crypto.go
- dm.go
- hyparview.go
- membership.go
- membership_commit.go
- node.go
- overlay_handlers.go
- packet.go
- ringbuffer.go
- router.go
- sframe.go
- sync.go
- transfer.go
- treekem_group.go
- treekem_process.go
- treekem_tree.go
- types.go