### Complete Moss Node Example Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Demonstrates initializing a Moss node, setting up message and event callbacks, starting the node, subscribing to a channel, publishing a message, retrieving mesh info, and performing cleanup. Includes compilation and execution instructions. ```c #include #include #include #include #include "moss.h" static void on_message(const char* channel, const uint8_t* sender_id, const uint8_t* data, uint32_t len) { printf("[%s] %.*s\n", channel, (int)len, (const char*)data); } static void on_event(int32_t event_type, const char* detail_json) { printf("event %d: %s\n", event_type, detail_json); } int main(void) { // Initialize node MossHandle handle = Moss_Init("demo-mesh", NULL, NULL); if (handle <= 0) { fprintf(stderr, "Init failed\n"); return 1; } // Register callbacks Moss_SetCallback(handle, on_message); Moss_SetEventCallback(handle, on_event); // Start node if (Moss_Start(handle) != MOSS_OK) { fprintf(stderr, "Start failed\n"); Moss_Stop(handle); return 1; } // Subscribe to channel if (Moss_Subscribe(handle, "chat") != MOSS_OK) { fprintf(stderr, "Subscribe failed\n"); Moss_Stop(handle); return 1; } // Publish message const uint8_t msg[] = "hello mesh"; if (Moss_Publish(handle, "chat", msg, 10) != MOSS_OK) { fprintf(stderr, "Publish failed\n"); } // Get info const char* info = Moss_GetMeshInfo(handle); if (info) { printf("Info: %s\n", info); Moss_Free((void*)info); } // Wait sleep(5); // Cleanup Moss_Stop(handle); return 0; } ``` ```bash gcc -o demo demo.c -l moss -L . LD_LIBRARY_PATH=. ./demo ``` -------------------------------- ### Run Python Example Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Navigate to the Python example directory and run the demo script. ```bash cd examples/python_example python moss_demo.py ``` -------------------------------- ### Safely Start a Moss Node Source: https://github.com/redstone-md/moss/blob/main/_autodocs/errors.md Demonstrates how to safely initialize and start a Moss node, handling potential errors like the node already being started. ```go node, err := moss.NewNode("mesh-id", nil, cfg) if err != nil { log.Fatalf("failed to create node: %v", err) } if err := node.Start(); err != nil { if errors.Is(err, moss.ErrAlreadyStarted) { log.Print("warning: node was already started") } else { log.Fatalf("failed to start: %v", err) } } defer node.Stop() ``` -------------------------------- ### Start Method Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Starts the node, binding to the configured listen port and initiating peer discovery, relay service, and the gossip protocol. This method is essential for activating the node's network functionalities. ```APIDOC ## Start Method ### Description Starts the node, binding to the configured listen port and beginning peer discovery, relay service, and gossip protocol. ### Signature ```go func (n *Node) Start() error ``` ### Return - `error` or `nil` on success ### Errors - `ErrAlreadyStarted` if the node is already running - `ErrConfig` if socket binding fails - OS-level network errors ### Behavior - Initializes TCP listener and UDP listener on the configured port - Launches background goroutines for peer acceptance, bootstrap discovery, maintenance, and dispatch - Begins announcing to trackers at `AnnounceIntervalSec` - Begins NAT profiling via STUN if enabled - Enables relay service if supernode eligibility is met ### Example ```go node, _ := moss.NewNode("mesh-id", nil, moss.Config{ListenPort: 0}) if err := node.Start(); err != nil { log.Printf("failed to start: %v", err) } ``` ``` -------------------------------- ### Implement and Set Key Store Callbacks Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Example implementation for persisting identity to a file and registering these callbacks. ```c // Persist identity in files static uint32_t load_identity(uint8_t* buffer, uint32_t capacity) { FILE* f = fopen("/var/lib/moss/identity.key", "rb"); if (!f) return 0; uint32_t n = fread(buffer, 1, capacity, f); fclose(f); return n; } static void save_identity(const uint8_t* data, uint32_t len) { FILE* f = fopen("/var/lib/moss/identity.key", "wb"); if (f) { fwrite(data, 1, len, f); fclose(f); } } Moss_SetKeyStore(load_identity, save_identity); ``` -------------------------------- ### Moss_Start Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Starts the node, enabling listeners, background goroutines, and peer discovery. Requires a valid MossHandle. ```APIDOC ## Moss_Start ### Description Starts the node: binds listeners, launches background goroutines, begins peer discovery and relay service. ### Signature ```c int32_t Moss_Start(MossHandle handle); ``` ### Parameters #### Path Parameters - **handle** (MossHandle) - Yes - Node handle from `Moss_Init` ### Return `MOSS_OK` (0) on success; negative error code on failure. Error codes: `MOSS_ERR_INVALID_HANDLE` (-1), `MOSS_ERR_ALREADY_STARTED` (-2), `MOSS_ERR_CONFIG_INVALID` (-8) ### Example ```c if (Moss_Start(handle) != MOSS_OK) { fprintf(stderr, "start failed\n"); Moss_Stop(handle); return 1; } ``` ``` -------------------------------- ### Start a Moss Node Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Initializes and starts a Moss node. Ensure to stop the node when done using `defer node.Stop()` or `Moss_Stop(h)`. ```go cfg := moss.Config{ListenPort: 41001} node, _ := moss.NewNode("mesh-id", nil, cfg) node.Start() defer node.Stop() ``` -------------------------------- ### Example Usage of Moss_GetPublicKey Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Demonstrates how to retrieve the public key, print it in hexadecimal format, and free the allocated buffer. ```c const uint8_t* key = Moss_GetPublicKey(handle); if (key != NULL) { printf("public key: "); for (int i = 0; i < 32; i++) { printf("%02x", key[i]); } printf("\n"); Moss_Free((void*)key); // Must free! } ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Installs the necessary Python packages for the chat client. Ensure you are in the repository root. ```powershell python -m pip install -r examples\python_chat\requirements.txt ``` -------------------------------- ### Example Usage of Moss_GetMeshInfo Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Demonstrates how to call Moss_GetMeshInfo, print the resulting JSON, and free the allocated memory. ```c const char* info = Moss_GetMeshInfo(handle); if (info != NULL) { printf("mesh info: %s\n", info); Moss_Free((void*)info); // Must free! } ``` -------------------------------- ### Start Moss Node Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Starts the initialized Moss node, enabling network listeners and background services. Checks for successful startup and handles potential errors. ```c if (Moss_Start(handle) != MOSS_OK) { fprintf(stderr, "start failed\n"); Moss_Stop(handle); return 1; } ``` -------------------------------- ### Moss_Start Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Starts mesh operations such as tracker announcements and network profiling. Requires a valid Moss handle. ```APIDOC ## Moss_Start ### Description Starts mesh operations (tracker announces, network profiling). ### Parameters #### Path Parameters - **handle** (MossHandle) - Required - The handle obtained from Moss_Init. ### Returns - **int32_t** - 0 on success, negative error code on failure. ``` -------------------------------- ### Start a Moss Node Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Initializes and starts a Moss node. Ensure to stop the node when done using `defer node.Stop()` or `Moss_Stop(h)`. ```c MossHandle h = Moss_Init("mesh-id", NULL, NULL); Moss_Start(h); // ... Moss_Stop(h); ``` -------------------------------- ### Build Moss Shared Library for Windows Source: https://github.com/redstone-md/moss/blob/main/README.md Builds the CGO shared library for Windows. Ensure Go is installed and configured. ```bash CGO_ENABLED=1 GOOS=windows GOARCH=amd64 \ go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi ``` -------------------------------- ### Local Integration Example Configuration Source: https://github.com/redstone-md/moss/blob/main/README.md Configuration for two Moss nodes to connect on localhost. One node is configured with static peer information for the other. ```json { "trackers": [], "static_peers": ["127.0.0.1:41001"], "listen_port": 41002 } ``` -------------------------------- ### Minimal C Host Pattern Source: https://github.com/redstone-md/moss/blob/main/docs/SHARED_INTEGRATION.md A basic C program demonstrating how to initialize Moss, set callbacks, start the service, subscribe to a channel, publish a message, and stop the service. ```c #include "moss.h" #include #include static void on_message(const char* channel, const uint8_t* sender_id, const uint8_t* data, uint32_t len) { (void)sender_id; printf("message on %s: %.*s\n", channel, (int)len, (const char*)data); } static void on_event(int32_t event_type, const char* detail_json) { printf("event %d: %s\n", (int)event_type, detail_json); } int main(void) { const char* config = "{\"listen_port\":41030}"; MossHandle handle = Moss_Init("my-mesh", NULL, config); if (handle < 0) { return 1; } Moss_SetCallback(handle, on_message); Moss_SetEventCallback(handle, on_event); Moss_Start(handle); Moss_Subscribe(handle, "lobby"); const char* text = "hello"; Moss_Publish(handle, "lobby", (const uint8_t*)text, (uint32_t)strlen(text)); Moss_Stop(handle); return 0; } ``` -------------------------------- ### Example Node Initialization with Custom Config Source: https://github.com/redstone-md/moss/blob/main/_autodocs/types.md Demonstrates how to create a new Moss node with a custom configuration, specifying parameters like listen port, trackers, maximum peers, high throughput mode, and identity path. ```go cfg := moss.Config{ ListenPort: 41001, Trackers: []string{ "udp://tracker.opentrackr.org:1337/announce", "http://tracker.opentrackr.org:1337/announce", }, MaxPeers: 100, HighThroughput: &trueVal, IdentityPath: "/tmp/moss-identity", } node, _ := moss.NewNode("my-mesh", nil, cfg) ``` -------------------------------- ### Moss_Start Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Starts listeners, bootstrap, maintenance loops, NAT profiling, and mesh operations for a given node handle. ```APIDOC ## Moss_Start ### Description Starts listeners, bootstrap, maintenance loops, NAT profiling, and mesh operations. ### Signature ```c int32_t Moss_Start(MossHandle handle); ``` ``` -------------------------------- ### Run All Tests Source: https://github.com/redstone-md/moss/blob/main/README.md Executes all unit and integration tests for the Moss project. Ensure Go is installed. ```bash go test ./... ``` -------------------------------- ### Moss_GetMeshInfo JSON Output Example Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Example JSON output for the Moss_GetMeshInfo function, detailing current node status and network information. ```json { "mesh_id": "example", "listen_port": 41030, "peer_count": 3, "peers": ["10.0.0.10:41031"], "channels": ["alpha"], "nat_type": "unknown", "public_key": "hex-encoded-32-byte-key", "supernode_ready": false } ``` -------------------------------- ### Build Moss Shared Library for Linux Source: https://github.com/redstone-md/moss/blob/main/README.md Builds the CGO shared library for Linux. Ensure Go is installed and configured. ```bash CGO_ENABLED=1 GOOS=linux GOARCH=amd64 \ go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi ``` -------------------------------- ### Moss Runtime Initialization and Flow Source: https://github.com/redstone-md/moss/blob/main/docs/ARCHITECTURE.md Illustrates the sequence of calls and internal processes involved in initializing, starting, publishing messages, and stopping the Moss runtime from a host application perspective. ```text Host app -> Moss_Init(mesh_id, psk, config_json) -> mesh.NewNode(...) -> bootstrap manager setup -> transport listener setup -> gossip manager setup -> NAT profiler and relay state setup -> Moss_SetCallback / Moss_SetEventCallback -> Moss_Start -> TCP and UDP accept loops -> tracker announce loop -> static peer dials -> NAT and reachability probing -> pubsub dispatch loop -> maintenance loop -> Moss_Subscribe(channel) -> Moss_Publish(channel, payload) -> local envelope creation -> gossip cache and scoring checks -> mesh broadcast / flood publish -> host callback delivery on receiving peers -> Moss_Stop -> listener shutdown -> peer/session cleanup -> goroutine wait ``` -------------------------------- ### Start the Moss Node Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Starts the Moss node, enabling peer discovery, relay services, and the gossip protocol. Ensure the node is created and configured before calling this method. It binds to the configured listen port and initiates network operations. ```Go node, _ := moss.NewNode("mesh-id", nil, moss.Config{ListenPort: 0}) if err := node.Start(); err != nil { log.Printf("failed to start: %v", err) } ``` -------------------------------- ### Moss Initialization Configuration JSON Source: https://github.com/redstone-md/moss/blob/main/docs/SHARED_INTEGRATION.md Provides an example of the JSON configuration object passed to Moss_Init. This allows customization of network listeners, trackers, and NAT behavior. ```json { "listen_port": 41030, "trackers": [ "udp://tracker.opentrackr.org:1337/announce" ], "static_peers": [], "gossipsub": { "heartbeat_ms": 1000 }, "nat": { "upnp_enabled": false, "natpmp_enabled": false, "pcp_enabled": false } } ``` -------------------------------- ### JNI Entrypoints for MossNode Initialization and Listener Setup Source: https://github.com/redstone-md/moss/blob/main/docs/SHARED_INTEGRATION.md These C functions serve as JNI entry points for initializing a Moss node and setting up a Java listener. They handle string conversions, Moss initialization, global reference management for the listener, and caching of Java method IDs. ```c JNIEXPORT jlong JNICALL Java_com_example_moss_MossNode_nativeInit(JNIEnv* env, jclass cls, jstring meshId, jstring configJson) { (void)cls; const char* mesh = (*env)->GetStringUTFChars(env, meshId, NULL); const char* cfg = configJson ? (*env)->GetStringUTFChars(env, configJson, NULL) : NULL; MossHandle handle = Moss_Init(mesh, NULL, cfg); if (cfg) { (*env)->ReleaseStringUTFChars(env, configJson, cfg); } (*env)->ReleaseStringUTFChars(env, meshId, mesh); return (jlong)handle; } JNIEXPORT void JNICALL Java_com_example_moss_MossNode_nativeSetListener(JNIEnv* env, jclass cls, jlong handle, jobject listener) { (void)cls; if (g_listener) { (*env)->DeleteGlobalRef(env, g_listener); g_listener = NULL; } g_listener = (*env)->NewGlobalRef(env, listener); jclass listenerCls = (*env)->GetObjectClass(env, listener); g_onMessage = (*env)->GetMethodID(env, listenerCls, "onMessage", "(Ljava/lang/String;[B[B)V"); g_onEvent = (*env)->GetMethodID(env, listenerCls, "onEvent", "(ILjava/lang/String;)V"); Moss_SetCallback((MossHandle)handle, on_message_cb); Moss_SetEventCallback((MossHandle)handle, on_event_cb); } ``` -------------------------------- ### Start Chat Client with PSK Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Launches a chat client instance using a Pre-Shared Key (PSK) for encrypted and identity-sensitive communication. The same PSK must be used by all participants. ```powershell python examples\python_chat\moss_chat.py --nickname Alice --psk-hex 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff ``` -------------------------------- ### Start Chat Client - Terminal 2 Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Launches the second instance of the Python chat client, connecting to the first instance via localhost and the specified port. ```powershell python examples\python_chat\moss_chat.py --nickname Bob --listen-port 41031 --peer 127.0.0.1:41030 --room lobby ``` -------------------------------- ### Start Chat Client - Terminal 1 Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Launches the first instance of the Python chat client. This instance will listen on a specific port and join the 'lobby' room. ```powershell python examples\python_chat\moss_chat.py --nickname Alice --listen-port 41030 --room lobby ``` -------------------------------- ### Node Lifecycle Methods (Go) Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Methods to control the lifecycle of a Moss node. `Start()` initiates network listeners and background tasks, while `Stop()` performs a graceful shutdown. ```Go Start() → error Stop() → error ``` -------------------------------- ### Build Moss Shared Library for macOS Source: https://github.com/redstone-md/moss/blob/main/README.md Builds the CGO shared library for macOS (ARM64 architecture). Ensure Go is installed and configured. ```bash CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 \ go build -buildmode=c-shared -o libmoss.dylib ./cmd/moss-ffi ``` -------------------------------- ### JSON Configuration for Trackers Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Example of how to specify a list of tracker URLs in JSON format. This is used for peer bootstrap. ```json { "trackers": [ "udp://tracker.opentrackr.org:1337/announce", "udp://open.stealth.si:80/announce", "http://tracker.opentrackr.org:1337/announce" ] } ``` -------------------------------- ### Moss_Start Function Signature Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Starts listeners, bootstrap, maintenance loops, NAT profiling, and mesh operations. Returns an integer status code. ```c int32_t Moss_Start(MossHandle handle); ``` -------------------------------- ### Implement and Set Scoring Callback Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Example implementation of a scoring callback that penalizes slow peers and registers it with the node. ```c static double score_peer(const uint8_t* peer_id, double base_score) { // Penalize slow peers return base_score * 0.5; } Moss_SetScoringCallback(handle, score_peer); ``` -------------------------------- ### Start Chat Client - LAN Peer Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Launches a chat client instance connecting to another machine on the local network using its hostname or IP address. Ensure the port is firewall-accessible. ```powershell python examples\python_chat\moss_chat.py --nickname Pi --listen-port 41030 --peer rpi1.local:41030 --room lobby ``` -------------------------------- ### Moss Core C-API - Lifecycle Functions Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Functions for initializing, starting, and stopping the Moss core. Moss_Init returns a handle, Moss_Start begins operations, and Moss_Stop gracefully shuts down the system. ```c typedef int64_t MossHandle; MossHandle Moss_Init(const char* mesh_id, const uint8_t* psk, const char* config); int32_t Moss_Start(MossHandle handle); int32_t Moss_Stop(MossHandle handle); ``` -------------------------------- ### Example: Custom High-Throughput Transport Buffers Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configure custom, larger buffer sizes for streams and UDP packets to reduce silent drops during traffic bursts, intended for high-throughput scenarios. ```go cfg := moss.Config{ Transport: moss.TransportConfig{ StreamBufferSize: 32768, UDPBufferSize: 16384, }, } ``` -------------------------------- ### Example: High-latency, high-redundancy Gossipsub Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configure Gossipsub with a wider degree (D) for increased redundancy and potentially lower latency, suitable for high-latency network conditions. ```go cfg := moss.Config{ GossipSub: moss.GossipSubConfig{ D: 8, DLo: 6, DHigh: 15, }, } ``` -------------------------------- ### Example: Large Message Size for File Transfers Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configure the maximum message payload size to 10MB to support large file transfers. Messages exceeding this limit will be rejected. ```go cfg := moss.Config{ Security: moss.SecurityConfig{ MaxMessageSizeBytes: 10 * 1024 * 1024, }, } ``` -------------------------------- ### Set Bootstrap Timeout for Slow Networks Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configure a longer timeout for initial tracker bootstrap and peer discovery on slow or lossy networks. This setting does not prevent the node from starting if the timeout is exceeded. ```go cfg := moss.Config{ BootstrapTimeoutSec: 10, // 10 seconds instead of 3 } ``` -------------------------------- ### Connectivity Method (Go) Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Establishes a direct connection to a specified peer address. This is used for bootstrapping or direct peer interaction. ```Go Connect(addr) → error ``` -------------------------------- ### Configure Quick Supernode Promotion for Testing Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Set a short minimum uptime in seconds before a node becomes eligible for supernode roles. This is useful for testing but not recommended for production. ```go cfg := moss.Config{ NAT: moss.NATConfig{ SuperNodeMinUptimeSec: 10, }, } ``` -------------------------------- ### Node Constructor (Go) Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Initializes a new Moss node. Requires a mesh ID, a pre-shared key (PSK), and a configuration object. Returns the initialized node or an error. ```Go NewNode(meshID, psk, cfg) → *Node, error ``` -------------------------------- ### Example Mesh Information JSON Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/mesh-info.md A complete JSON object representing the information of a node within a 5-peer mesh. ```json { "mesh_id": "example", "listen_port": 41001, "advertised_addr": "203.0.113.10:41001", "peer_count": 5, "direct_peer_count": 4, "relayed_peer_count": 1, "peers": [ "10.0.0.11:41002", "10.0.0.12:41003", "10.0.0.13:41004", "10.0.0.14:41005", "192.168.1.50:41006" ], "channels": [ "chat", "game_updates", "news" ], "known_peer_count": 12, "known_peers": [ "abc12345@10.0.0.15:41007[known]", "def67890@10.0.0.16:41008[known]", "ghi34567@10.0.0.17:41009[known]", "jkl89012@10.0.0.18:41010[direct]" ], "relay_capable_peer_count": 3, "relay_session_count": 2, "relay_route_count": 1, "nat_type": "port_restricted_cone", "public_key": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1", "supernode_ready": true } ``` -------------------------------- ### Node Lifecycle Steps Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Illustrates the typical lifecycle of a Moss node, from creation to stopping. These steps outline the sequence of operations for initializing, running, and shutting down a node. ```Go 1. **Create**: `NewNode(meshID, psk, config)` — Initialize without starting 2. **Start**: `node.Start()` — Bind listeners, launch background tasks 3. **Operate**: `Subscribe()`, `Publish()`, `Connect()` — Pub/sub and connectivity 4. **Monitor**: `MeshInfoJSON()`, `PublicKey()`, `NATType()` — Diagnostics 5. **Stop**: `node.Stop()` — Graceful shutdown, release resources ``` -------------------------------- ### Get NAT Type Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Retrieves the detected NAT type of the node. The returned string must be freed using Moss_Free. ```c const char* Moss_GetNATType(MossHandle handle); ``` ```c const char* nat_type = Moss_GetNATType(handle); if (nat_type != NULL) { printf("NAT type: %s\n", nat_type); Moss_Free((void*)nat_type); // Must free! } ``` -------------------------------- ### Get NAT Type Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Retrieves the current NAT type of the network connection. The returned string indicates the NAT configuration. ```c const char* Moss_GetNATType(MossHandle handle); ``` -------------------------------- ### Recommended Moss Function Call Order Source: https://github.com/redstone-md/moss/blob/main/docs/SHARED_INTEGRATION.md Illustrates the recommended sequence for calling Moss library functions during application startup, operation, and shutdown. ```text Moss_SetKeyStore(...) optional, global Moss_Init(...) Moss_SetCallback(...) Moss_SetEventCallback(...) Moss_SetScoringCallback(...) optional, per-handle Moss_Start(...) Moss_Subscribe(...) Moss_Publish(...) Moss_Stop(...) ``` -------------------------------- ### Example: Bandwidth-constrained Gossipsub Heartbeat Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Increase the heartbeat interval to 3000ms to reduce control traffic and CPU overhead, suitable for bandwidth-constrained environments. ```go cfg := moss.Config{ GossipSub: moss.GossipSubConfig{ HeartbeatMS: 3000, }, } ``` -------------------------------- ### Moss_Init Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Creates a node instance and returns an opaque handle. It takes a mesh ID, an optional pre-shared key, and optional JSON configuration. ```APIDOC ## Moss_Init ### Description Creates a node instance and returns an opaque handle. - `mesh_id`: required UTF-8 mesh identifier. - `psk`: optional 32-byte pre-shared key; pass `NULL` for an open mesh. - `config`: optional JSON config; pass `NULL` for defaults. Returns a positive handle on success or a negative error code on failure. ### Signature ```c MossHandle Moss_Init(const char* mesh_id, const uint8_t* psk, const char* config); ``` ``` -------------------------------- ### Get Mesh Information Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Retrieve mesh information as a JSON string. This can be inspected using tools like `jq` or a JSON parser for debugging. ```go info := node.MeshInfoJSON() // Use `jq` or JSON parser to inspect ``` -------------------------------- ### Subscribe to a Channel and Receive Messages Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Sets up a callback function to print incoming messages and then subscribes to the specified channel. The callback handles messages from any sender. ```c void on_msg(const char* ch, const uint8_t* sender, const uint8_t* data, uint32_t len) { printf("[%s] %.*s\n", ch, (int)len, (const char*)data); } Moss_SetCallback(h, on_msg); Moss_Subscribe(h, "chat"); ``` -------------------------------- ### Example: Low-latency Gossipsub Heartbeat Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Reduce the heartbeat interval to 500ms for faster mesh and gossip state maintenance, suitable for low-latency network requirements. ```go cfg := moss.Config{ GossipSub: moss.GossipSubConfig{ HeartbeatMS: 500, }, } ``` -------------------------------- ### Build Windows DLL Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Command to build a Dynamic Link Library (DLL) for Windows (moss.dll) using Go's CGO and a specific GCC compiler. ```bash # Windows DLL CGO_ENABLED=1 GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc \ go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi ``` -------------------------------- ### Launch Local Demo Script Source: https://github.com/redstone-md/moss/blob/main/examples/python_chat/README.md Executes a PowerShell script to automatically launch multiple instances of the chat demo for local testing. This simplifies setting up multiple clients. ```powershell powershell -ExecutionPolicy Bypass -File examples\python_chat\start_local_demo.ps1 ``` -------------------------------- ### Go Configuration for Tracker-Free Local Testing Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configures a Moss node to use an empty tracker list and a static peer for local testing. The listen port is explicitly set. ```go cfg := moss.Config{ Trackers: []string{}, StaticPeers: []string{"127.0.0.1:41001"}, ListenPort: 41002, } ``` -------------------------------- ### Get Node Listening Port Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Returns the port the node is currently listening on. This is particularly useful when the `ListenPort` was configured to 0, allowing the OS to assign a port. ```go func (n *Node) ListenPort() int ``` ```go node, _ := moss.NewNode("mesh", nil, moss.Config{ListenPort: 0}) node.Start() actualPort := node.ListenPort() log.Printf("listening on port %d", actualPort) ``` -------------------------------- ### Go Configuration for Hybrid Tracker and Seed Peers Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Sets up a Moss node to use both tracker discovery and a fallback static seed peer. ```go cfg := moss.Config{ Trackers: []string{ "udp://tracker.opentrackr.org:1337/announce", }, StaticPeers: []string{ "fallback-seed.example.com:41001", }, } ``` -------------------------------- ### Get Detected NAT Type Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Returns the detected NAT type as a string. This information is crucial for understanding network reachability and potential limitations in peer connections. ```go func (n *Node) NATType() string ``` ```go natType := node.NATType() log.Printf("detected NAT: %s", natType) if natType == "symmetric_nat" { log.Print("hole punching will be limited") } ``` -------------------------------- ### Build C Shared Library Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Builds the Moss runtime as a C-shared library using CGO. Ensure the correct path to the Moss FFI main package is specified. ```bash CGO_ENABLED=1 go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi ``` -------------------------------- ### Memory Cleanup on Initialization or Start Error Source: https://github.com/redstone-md/moss/blob/main/_autodocs/errors.md Ensure proper memory cleanup by calling Moss_Stop if Moss_Init fails or if Moss_Start returns an error. This prevents resource leaks. ```c MossHandle handle = Moss_Init(mesh_id, psk, config); if (handle <= 0) { fprintf(stderr, "Moss_Init failed: %lld\n", (long long)handle); return 1; } int32_t start_code = Moss_Start(handle); if (start_code != MOSS_OK) { Moss_Stop(handle); // Cleanup on error return 1; } ``` -------------------------------- ### Go Noise Library Usage Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Demonstrates the use of the 'github.com/flynn/noise' library for implementing the Noise Protocol Framework, a production-ready solution also used in the WireGuard ecosystem. ```Go import "github.com/flynn/noise" ``` -------------------------------- ### Run All Tests Source: https://github.com/redstone-md/moss/blob/main/CONTRIBUTING.md Execute all Go tests in the project. Use the -count=1 flag to ensure tests are run fresh and -timeout to set a maximum execution time. ```bash go test ./... -count=1 -timeout 1800s ``` -------------------------------- ### Go Noise net.Conn Wrapper Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Illustrates using the 'github.com/go-i2p/go-noise' library to wrap net.Conn with Noise Protocol encryption for secure communication. ```Go import "github.com/go-i2p/go-noise" ``` -------------------------------- ### Build Shared Library for Windows Source: https://github.com/redstone-md/moss/blob/main/docs/SHARED_INTEGRATION.md Builds the moss shared library for Windows using Go's c-shared build mode. ```bash # Windows go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi ``` -------------------------------- ### Subscribe to a Channel and Receive Messages Source: https://github.com/redstone-md/moss/blob/main/_autodocs/INDEX.md Sets up a callback to log incoming messages on a specific channel and then subscribes to that channel. The callback function processes messages from any sender. ```go node.SetEventCallback(func(channel string, senderID [32]byte, data []byte) { log.Printf("[%s] %s", channel, string(data)) }) node.Subscribe("chat") ``` -------------------------------- ### Example: Long Handshake Timeout for Satellite Links Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Increase the Noise XX handshake timeout to 30 seconds to accommodate high-latency or lossy network conditions, such as satellite or international links. ```go cfg := moss.Config{ Security: moss.SecurityConfig{ HandshakeTimeoutSec: 30, }, } ``` -------------------------------- ### Load JSON Configuration from File Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Loads a JSON configuration from the specified file path. Handles file reading and JSON parsing errors. Initializes a new node with the loaded configuration. ```go func loadConfigFromFile(path string) (moss.Config, error) { data, err := os.ReadFile(path) if err != nil { return moss.Config{}, err } return moss.ConfigFromJSON(string(data)) } cfg, err := loadConfigFromFile("/etc/moss/config.json") if err != nil { log.Fatal(err) } node, _ := moss.NewNode("mesh-id", nil, cfg) ``` -------------------------------- ### Go Configuration for Private Mesh Bootstrap Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configures a Moss node to bootstrap a private mesh using static peers and disabling tracker discovery. ```go cfg := moss.Config{ Trackers: []string{}, StaticPeers: []string{ "seed1.example.com:41001", "seed2.example.com:41001", }, } ``` -------------------------------- ### Example: Conservative Rate Limiting for DDoS Hardening Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Set conservative burst and sustained rate limits for inbound messages to enhance DDoS resilience. Excess messages exceeding these limits will be dropped. ```go cfg := moss.Config{ Security: moss.SecurityConfig{ RateLimitBurst: 100000, RateLimitSustained: 10000, }, } ``` -------------------------------- ### Build Linux Shared Library Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Command to build a shared library for Linux (libmoss.so) using Go's CGO. ```bash # Linux shared library CGO_ENABLED=1 GOOS=linux GOARCH=amd64 \ go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi ``` -------------------------------- ### Moss Project Directory Structure Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION-OPERATIONS.md This snippet displays the hierarchical structure of the Moss project, including its command-line tools, internal packages, examples, and build files. It helps understand the organization of the codebase. ```tree moss/ ├── cmd/ │ └── moss-ffi/ │ └── main.go # CGO exports, empty main(), //export directives ├── internal/ │ ├── bootstrap/ │ │ ├── tracker_udp.go # BEP 15 UDP tracker client │ │ ├── tracker_http.go # BEP 3 HTTP tracker client │ │ ├── infohash.go # SHA-1 InfoHash generation + HKDF-PSK mixing │ │ └── tracker_manager.go # Concurrent tracker rotation, retry logic │ ├── transport/ │ │ ├── noise.go # Noise XX/IK handshake (flynn/noise) │ │ ├── conn.go # Encrypted connection wrapper (net.Conn) │ │ ├── multiplexer.go # Stream multiplexing over single connection │ │ ├── listener.go # TCP listener with accept logic │ │ ├── udp.go # UDP listener public surface and shared state │ │ ├── udp_handshake.go # UDP Noise handshake packet flow │ │ ├── udp_observe.go # UDP/STUN endpoint observation helpers │ │ └── udp_session.go # UDP carrier/session lifecycle │ ├── nat/ │ │ ├── profiler.go # NAT type classification │ │ ├── upnp.go # UPnP IGD port mapping │ │ ├── pmp.go # NAT-PMP / PCP port mapping │ │ ├── holepunch.go # UDP/TCP hole-punching coordinator │ │ ├── relay.go # SuperNode relay session manager │ │ └── supernode.go # SuperNode promotion/demotion logic │ ├── gossip/ │ │ ├── pubsub.go # GossipSub v1.1 mesh manager │ │ ├── scoring.go # Peer scoring engine │ │ ├── messages.go # GRAFT, PRUNE, IHAVE, IWANT, IDONTWANT │ │ └── cache.go # Message ID cache (deduplication) │ ├── mesh/ │ │ ├── node_types.go # Core Node state and private helper structs │ │ ├── node_lifecycle.go # construction, start/stop, public Node API │ │ ├── node_accept.go # inbound/outbound peer connection lifecycle │ │ ├── node_advertise.go # local address and announce-port selection │ │ ├── node_envelope.go # gossip envelope delivery and flood publish │ │ ├── node_gossip_control.go # IHAVE/IWANT/IDONTWANT control flow │ │ ├── node_peer_*.go # peer announcement, discovery, topic mesh upkeep │ │ ├── node_relay_*.go # relay API, selection, and relay control flow │ │ ├── node_nat_control.go # binding, reachability, and hole-punch messages │ │ ├── node_reachability.go # external address and reachability probes │ │ ├── node_maintenance.go # latency probing, pruning, and housekeeping │ │ ├── config.go # JSON config parsing + defaults │ │ └── events.go # Event bus (peer join/leave, supernode, etc.) │ └── crypto/ │ ├── keys.go # Ed25519 identity, Curve25519 derivation │ └── hkdf.go # HKDF-SHA256 key derivation ├── examples/ │ ├── c_example/ │ │ ├── main.c # C integration example │ │ └── Makefile │ ├── python_example/ │ │ └── moss_demo.py # Minimal Python ctypes integration │ ├── cpp_example/ │ │ └── main.cpp # C++ integration example │ ├── csharp_example/ │ │ ├── Program.cs # C# integration example │ │ └── MossDemo.csproj │ ├── python_chat/ │ │ ├── moss_chat.py # Compatibility entrypoint │ │ └── README.md │ └── rust_example/ │ ├── src/main.rs # Rust FFI integration │ └── build.rs ├── Makefile # Cross-platform build targets ├── go.mod ├── go.sum └── README.md ``` -------------------------------- ### Initialize Moss Node Instance Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/ffi.md Initializes a new Moss node instance with a given mesh ID, optional pre-shared key, and configuration. Handles successful initialization and reports errors. ```c #include #include "moss.h" int main(void) { const char* mesh_id = "my-mesh"; const char* config = "{\"listen_port\": 41001, \"trackers\": []}"; MossHandle handle = Moss_Init(mesh_id, NULL, config); if (handle <= 0) { fprintf(stderr, "Moss_Init failed: %lld\n", (long long)handle); return 1; } // ... use handle ... Moss_Stop(handle); return 0; } ``` -------------------------------- ### Get Node Public Key Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Retrieves the node's Ed25519 public key as a 32-byte array. This key is consistent throughout the node's lifetime and can be used for authentication and relay negotiation. ```go func (n *Node) PublicKey() [32]byte ``` ```go pubKey := node.PublicKey() log.Printf("node public key: %x", pubKey[:]) ``` -------------------------------- ### Go Configuration for Stable Low-Bandwidth Tracker Interval Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Sets a longer tracker announce interval of 300 seconds for stable, low-bandwidth environments. ```go cfg := moss.Config{ AnnounceIntervalSec: 300, // Announce every 5 minutes } ``` -------------------------------- ### Get Node Mesh Information as JSON Source: https://github.com/redstone-md/moss/blob/main/_autodocs/api-reference/node.md Retrieves a JSON string detailing the node's current state, including peer count, subscriptions, NAT type, and relay status. This is useful for monitoring and debugging. ```go func (n *Node) MeshInfoJSON() string ``` ```json { "mesh_id": "example", "listen_port": 41001, "advertised_addr": "203.0.0.113:41001", "peer_count": 5, "direct_peer_count": 3, "relayed_peer_count": 2, "peers": ["10.0.0.11:41002", "10.0.0.12:41003"], "channels": ["news", "chat"], "known_peer_count": 8, "known_peers": ["abc123@10.0.0.20:41001[direct]"], "relay_capable_peer_count": 2, "relay_session_count": 1, "relay_route_count": 0, "nat_type": "port_restricted_cone", "public_key": "a1b2c3d4...", "supernode_ready": true } ``` ```go info := node.MeshInfoJSON() var state map[string]interface{} json.Unmarshal([]byte(info), &state) log.Printf("connected peers: %d", state["peer_count"]) ``` -------------------------------- ### Noise Protocol Framework - XX Pattern Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Example of using the Noise Protocol Framework with the XX handshake pattern for initial peer connections. This pattern provides mutual authentication, forward secrecy, and identity hiding over 1.5 RTT. ```Go import ( "github.com/flynn/noise" ) // Noise_XX_25519_ChaChaPoly_BLAKE2s handshake pattern var handshakePattern = noise.HandshakeXX ``` -------------------------------- ### Noise Protocol Framework - IK Pattern Source: https://github.com/redstone-md/moss/blob/main/docs/SPECIFICATION.md Example of using the Noise Protocol Framework with the IK handshake pattern for reconnections. This pattern leverages cached responder static keys for 0-RTT encrypted payloads and forward secrecy, requiring only 1 RTT. ```Go import ( "github.com/flynn/noise" ) // Noise_IK_25519_ChaChaPoly_BLAKE2s handshake pattern var handshakePattern = noise.HandshakeIK ``` -------------------------------- ### Go Configuration for High-Churn Network Tracker Interval Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Configures an aggressive tracker announce interval of 30 seconds for networks with high peer churn. ```go cfg := moss.Config{ AnnounceIntervalSec: 30, // Aggressive refresh every 30s } ``` -------------------------------- ### Build Moss as a C-shared library Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Build Moss as a C-shared library for Linux, Windows, or macOS. The generated C header is emitted next to the library. ```bash # Linux go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi # Windows go build -buildmode=c-shared -o moss.dll ./cmd/moss-ffi # macOS go build -buildmode=c-shared -o libmoss.dylib ./cmd/moss-ffi ``` -------------------------------- ### Run Tests with Custom Cache Paths Source: https://github.com/redstone-md/moss/blob/main/README.md Runs tests while specifying local paths for Go's build cache and temporary files. Useful in environments with restricted default cache locations. ```bash GOCACHE=$PWD/.gocache GOTMPDIR=$PWD/.gotmp go test ./... ``` -------------------------------- ### Go Configuration for Corporate Tracker Source: https://github.com/redstone-md/moss/blob/main/_autodocs/configuration.md Sets up a Moss node to use a custom corporate tracker URL for peer discovery. ```go cfg := moss.Config{ Trackers: []string{ "http://internal-tracker.corp:6969/announce", }, } ``` -------------------------------- ### Moss_Init Function Signature Source: https://github.com/redstone-md/moss/blob/main/docs/API.md Creates a node instance and returns an opaque handle. Parameters include mesh ID, an optional pre-shared key, and optional JSON configuration. Returns a positive handle on success or a negative error code on failure. ```c MossHandle Moss_Init(const char* mesh_id, const uint8_t* psk, const char* config); ``` -------------------------------- ### Build Unix-like FFI Shared Library Source: https://github.com/redstone-md/moss/blob/main/CONTRIBUTING.md Build the C-shared library for Unix-like systems (libmoss.so) from the cmd/moss-ffi package. This is required if FFI behavior is modified. ```bash go build -buildmode=c-shared -o libmoss.so ./cmd/moss-ffi ```