moss

package module
v0.8.19 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 8 Imported by: 0

README

Moss

CI Main CI Dev

Moss is an embeddable P2P mesh core written in Go and exported through CGO as a C-shared library. This repository is the runtime layer, not the end-user chat application.

The current implementation follows the public technical specification in docs/SPECIFICATION.md with a pragmatic v1 runtime:

  • tracker-based bootstrapping via BEP 15 UDP and BEP 3 HTTP announces
  • encrypted peer transport with Noise XX (25519_ChaChaPoly_BLAKE2s) plus identity binding
  • topic-based pub/sub routing with GRAFT/PRUNE control messages, BLAKE2s message IDs, and peer scoring
  • NAT profiling, relay rate limiting primitives, and supernode eligibility checks
  • C FFI surface with examples for C, C++, C#, Python (ctypes), and Rust
  • unit, integration, and shared-library smoke tests

Desktop clients now live in the separate MOSH repository, which consumes MOSS through the shared runtime and a Git submodule pin for compatibility.

Repository role

  • MOSS = runtime, protocol, NAT/relay logic, FFI, examples
  • MOSH = desktop chat client built on top of MOSS

FFI docs:

Repository policy:

Layout

cmd/moss-ffi/              CGO shared library entrypoint
internal/bootstrap/        tracker clients and infohash generation
internal/transport/        encrypted sessions and handshake
internal/gossip/           pubsub cache, scoring, envelopes
internal/nat/              NAT profiling and relay primitives
internal/mesh/             runtime node orchestration
examples/                  C, C++, C#, Python, Python chat, Rust FFI examples

Build

# Linux
CGO_ENABLED=1 GOOS=linux GOARCH=amd64 \
  go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi

# Windows
CGO_ENABLED=1 GOOS=windows GOARCH=amd64 \
  go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi

# macOS
CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 \
  go build -buildmode=c-shared -o libmoss.dylib ./cmd/moss-ffi

The generated header is emitted next to the shared library as moss.h or libmoss.h, depending on the output name.

Quick Start

Build the shared runtime:

go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi

Then integrate it from your host application through the FFI surface described in:

GitHub Actions publishes release artifacts only from tags.

Main release tags (v*) publish separate shared-library artifacts for both macOS architectures:

  • moss-macos-amd64-shared
  • moss-macos-arm64-shared

Regular main / dev branch CI now runs tests and smoke builds only. It does not upload release artifacts on every push.

Test

go test ./...

If your environment blocks the default Go cache location, set workspace-local cache paths:

GOCACHE=$PWD/.gocache GOTMPDIR=$PWD/.gotmp go test ./...

FFI API

Current exported functions:

  • Moss_Init
  • Moss_Start
  • Moss_Stop
  • Moss_Subscribe
  • Moss_Connect
  • Moss_Unsubscribe
  • Moss_Publish
  • Moss_SetCallback
  • Moss_SetEventCallback
  • Moss_SetScoringCallback
  • Moss_SetKeyStore
  • Moss_GetMeshInfo
  • Moss_GetNetworkStats
  • Moss_GetPublicKey
  • Moss_GetNATType
  • Moss_Free

See docs/API.md for signatures, config fields, event IDs, and error codes.

Web frontend & telemetry

site/ is the static site (landing page, network explorer, and mosh-web), built with Tailwind and deployed to GitHub Pages (see .github/workflows/pages.yml).

make site      # build Tailwind CSS + both wasm bundles into ./site
# serve locally:
python -m http.server 8095 --directory site

Supporting commands:

  • cmd/moss-gateway — node with telemetry on, serving a read-only HTTP/SSE API the explorer reads and verifies (make gateway).
  • cmd/moss-signal — WebRTC signaling relay for browser peers (make signal).
  • cmd/moss-wasm — browser telemetry verifier; cmd/moss-node-wasm — full peer in wasm.

Telemetry is opt-in (telemetry.enabled), privacy-preserving (HyperLogLog node count, DP-noised bandwidth, unlinkable per-epoch ids), and self-verifying via a BLAKE2s hash chain. See docs/API.md.

Stability Notes

  • The repository is public-ready as a runtime/core project.
  • NAT traversal and relay fallback are implemented and tested, but network behavior still depends on real-world topology.
  • Public client-facing UX issues should go to MOSH.

Local integration example

Two nodes on localhost can be started with one node configured as a static peer of the other:

{
  "trackers": [],
  "static_peers": ["127.0.0.1:41001"],
  "listen_port": 41002
}

The second node connects automatically, exchanges subscriptions, and forwards published messages over the encrypted session.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// NetworkID selects the shared substrate (discovery + handshake + relay).
	// Leave empty to join the one public network; set only for an isolated
	// testnet. This is NOT the room — the room is the meshID passed to NewNode.
	NetworkID           string   `json:"network_id,omitempty"`
	Trackers            []string `json:"trackers,omitempty"`
	AnnounceIntervalSec int      `json:"announce_interval_sec,omitempty"`
	ListenPort          int      `json:"listen_port,omitempty"`
	MaxPeers            int      `json:"max_peers,omitempty"`
	StaticPeers         []string `json:"static_peers,omitempty"`
	BootstrapTimeoutSec int      `json:"bootstrap_timeout_sec,omitempty"`
	LANDiscoveryEnabled *bool    `json:"lan_discovery_enabled,omitempty"`

	RelayMaxBandwidthKBPS int   `json:"relay_max_bandwidth_kbps,omitempty"`
	RelayMaxSessions      int   `json:"relay_max_sessions,omitempty"`
	RelaySessionTTLSec    int   `json:"relay_session_ttl_sec,omitempty"`
	SuperNodeMinUptimeSec int   `json:"supernode_min_uptime_sec,omitempty"`
	UPnPEnabled           *bool `json:"upnp_enabled,omitempty"`
	NATPMPEnabled         *bool `json:"natpmp_enabled,omitempty"`
	PCPEnabled            *bool `json:"pcp_enabled,omitempty"`
	HolePunchAttempts     int   `json:"hole_punch_attempts,omitempty"`

	HighThroughput      *bool `json:"high_throughput,omitempty"`
	StreamBufferSize    int   `json:"stream_buffer_size,omitempty"`
	UDPBufferSize       int   `json:"udp_buffer_size,omitempty"`
	HandshakeTimeoutSec int   `json:"handshake_timeout_sec,omitempty"`
	MaxMessageSizeBytes int   `json:"max_message_size_bytes,omitempty"`

	// TelemetryEnabled turns on the privacy-preserving observability layer: the
	// node contributes DP-noised, per-epoch aggregate metrics under an
	// unlinkable ephemeral id and gossips a self-verifying network snapshot.
	// Nothing here exposes the node's address or stable identity.
	TelemetryEnabled  *bool `json:"telemetry_enabled,omitempty"`
	TelemetryEpochSec int   `json:"telemetry_epoch_sec,omitempty"`
	TelemetryKAnon    int   `json:"telemetry_k_anon,omitempty"`

	// Axiom error/log telemetry (opt-in). When AxiomToken and AxiomDataset are
	// both set, the node ships structured errors (listen/relay/handshake
	// failures, plus anything reported via LogEvent) and periodic node-stats
	// (peer/supernode/relay counts) to Axiom. AxiomEndpoint is the ingest base
	// URL — leave empty for the cloud default, or set the region edge (e.g.
	// https://eu-central-1.aws.edge.axiom.co). AxiomService identifies the host
	// (e.g. "mossspore-0.6.9", "gse-4576510"). The token is ingest-only.
	AxiomToken    string `json:"axiom_token,omitempty"`
	AxiomDataset  string `json:"axiom_dataset,omitempty"`
	AxiomEndpoint string `json:"axiom_endpoint,omitempty"`
	AxiomService  string `json:"axiom_service,omitempty"`

	// DHTEnabled toggles the BitTorrent-DHT peer-discovery source. Nil keeps the
	// default (on). Set false to rely solely on trackers/static peers.
	DHTEnabled *bool `json:"dht_enabled,omitempty"`

	// Veil configures the DPI-resistant "Reality" transport bearer. A relay
	// sets Role="listener"; a client behind DPI lists the relays to reach in
	// Relays. Omitted (nil) leaves it disabled.
	Veil *VeilConfig `json:"veil,omitempty"`

	IdentityPath string `json:"identity_path,omitempty"`
}

Config mirrors the subset of mesh.Config relevant for external consumers.

func ConfigFromJSON

func ConfigFromJSON(raw string) (Config, error)

ConfigFromJSON parses a JSON-encoded configuration string.

type Node

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

Node wraps the internal mesh node, providing the public API for MossSpore and other consumers of the Moss library.

func NewNode

func NewNode(meshID string, psk []byte, cfg Config) (*Node, error)

NewNode creates a new Moss node with the given mesh ID, optional PSK, and configuration. The identity is either loaded from the path specified in Config.IdentityPath or generated and saved to that path.

func (*Node) Connect

func (n *Node) Connect(addr string) error

Connect dials a specific peer address and adds it to the mesh.

func (*Node) ListenPort

func (n *Node) ListenPort() int

ListenPort returns the port the node is listening on. Useful when ListenPort was set to 0 (OS-assigned port).

func (*Node) LogEvent added in v0.6.18

func (n *Node) LogEvent(level, kind, message string, fields map[string]any)

LogEvent ships a structured event to Axiom when the sink is enabled (a no-op otherwise). level is "error" | "warn" | "info", kind a short slug, message free text, and fields optional context (no PII). Lets a Go host report its own errors alongside moss's.

func (*Node) MeshInfoJSON

func (n *Node) MeshInfoJSON() string

MeshInfoJSON returns a JSON string describing the current node state, including peer count, NAT type, relay status, and channel subscriptions.

func (*Node) NATType

func (n *Node) NATType() string

NATType returns the detected NAT type as a string (e.g. "public", "full_cone", "restricted_cone", "symmetric_nat").

func (*Node) NoiseStaticPublicHex added in v0.6.21

func (n *Node) NoiseStaticPublicHex() string

NoiseStaticPublicHex returns the node's X25519 Noise static public key as hex. A relay operator publishes this so Veil dialers can pin it in their veil relay config (`pubkey`); it is the key the masked-tunnel auth secret is derived from, distinct from PublicKey (the Ed25519 identity key).

func (*Node) PublicKey

func (n *Node) PublicKey() [32]byte

PublicKey returns the node's Ed25519 public key as a 32-byte array.

func (*Node) Publish

func (n *Node) Publish(channel string, data []byte) error

Publish sends a message to a pub/sub channel.

func (*Node) SetEventCallback

func (n *Node) SetEventCallback(cb func(eventType int32, detailJSON string))

SetEventCallback registers a callback for lifecycle and network events. Pass nil to clear.

func (*Node) SetMessageCallback added in v0.6.19

func (n *Node) SetMessageCallback(cb func(channel string, senderID [32]byte, data []byte))

SetMessageCallback registers a callback for pub/sub messages delivered on the channels this node is subscribed to. cb receives the channel, the sender's public key, and the payload. Pass nil to clear.

func (*Node) SetRelayCallback

func (n *Node) SetRelayCallback(cb func(senderID [32]byte, data []byte))

SetRelayCallback registers a callback for relayed data packets. Pass nil to clear.

func (*Node) Start

func (n *Node) Start() error

Start starts the node, binding to the configured listen port and beginning peer discovery, relay service, and gossip protocol.

func (*Node) Stop

func (n *Node) Stop() error

Stop gracefully shuts down the node, closing all peer connections and releasing resources.

func (*Node) Subscribe

func (n *Node) Subscribe(channel string) error

Subscribe joins a pub/sub channel.

type VeilConfig added in v0.6.21

type VeilConfig struct {
	Enabled    bool        `json:"enabled"`
	Role       string      `json:"role,omitempty"`        // "listener" or "dialer" (default)
	ListenAddr string      `json:"listen_addr,omitempty"` // listener bind, host:port
	CoverSNI   string      `json:"cover_sni,omitempty"`
	TargetAddr string      `json:"target_addr,omitempty"` // listener: real origin for spliced probes
	Relays     []VeilRelay `json:"relays,omitempty"`      // dialer: known Veil-fronted relays
}

VeilConfig is the public mirror of the Veil "Reality" DPI-mask settings (see mesh.VeilConfig). CoverSNI must match on both legs and SHOULD be a real domain the listener can reach.

type VeilRelay added in v0.6.21

type VeilRelay struct {
	Addr      string `json:"addr"`
	CoverSNI  string `json:"cover_sni"`
	PubKeyHex string `json:"pubkey"`
}

VeilRelay is a public mirror of mesh.VeilRelay: a Veil-fronted relay a dialer bootstraps through. PubKeyHex is the relay's 32-byte static Noise public key in hex.

Directories

Path Synopsis
cmd
moss-ffi command
moss-gateway command
Command moss-gateway runs Moss nodes with telemetry enabled and exposes a read-only HTTP surface so a browser explorer (e.g.
Command moss-gateway runs Moss nodes with telemetry enabled and exposes a read-only HTTP surface so a browser explorer (e.g.
moss-node-wasm command
This package targets WebAssembly (GOOS=js GOARCH=wasm).
This package targets WebAssembly (GOOS=js GOARCH=wasm).
moss-signal command
Command moss-signal is a minimal WebRTC signaling relay for browser Moss peers.
Command moss-signal is a minimal WebRTC signaling relay for browser Moss peers.
moss-wasm command
This package targets WebAssembly (GOOS=js GOARCH=wasm).
This package targets WebAssembly (GOOS=js GOARCH=wasm).
internal
geo
Package geo maps peer IP addresses to a coarse location (country / continent) so relay selection can prefer a relay close to the peer it must reach, shortening the relay↔target leg.
Package geo maps peer IP addresses to a coarse location (country / continent) so relay selection can prefer a relay close to the peer it must reach, shortening the relay↔target leg.
nat
observe
Package observe provides the read-only, client-side primitives a network explorer needs to TRUST telemetry it did not produce: hash-chain continuity verification, cross-gateway agreement, and a deterministic topology *simulation* derived from aggregate statistics.
Package observe provides the read-only, client-side primitives a network explorer needs to TRUST telemetry it did not produce: hash-chain continuity verification, cross-gateway agreement, and a deterministic topology *simulation* derived from aggregate statistics.
overlay
Package overlay implements the Kademlia-style routing layer moss uses to find things at scale: which nodes exist, where a peer is attached, and who subscribes to a channel.
Package overlay implements the Kademlia-style routing layer moss uses to find things at scale: which nodes exist, where a peer is attached, and who subscribes to a channel.
telemetry
Package telemetry provides an opt-in, best-effort sink that ships structured events (errors and host-supplied logs) to Axiom.
Package telemetry provides an opt-in, best-effort sink that ships structured events (errors and host-supplied logs) to Axiom.

Jump to

Keyboard shortcuts

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