Building games with LRGP
LRGP (Lightweight Reticulum Gaming Protocol) carries peer-to-peer turn-based games inside ordinary LXMF messages — no central game server required. Built-in games are Tic-Tac-Toe, Chess, and Four in a Row. Both lrgp-rs (Rust, MSRV 1.87+) and lrgp-py (Python 3.8+) are MIT-licensed and wire-compatible under marker lrgp.v1.
1. Session lifecycle & wire contract
Every LRGP action rides inside standard LXMF fields plus a human-readable fallback body for non-LRGP clients:
| LXMF field / envelope key | Value & constraint |
|---|---|
Field 0xFB (FIELD_CUSTOM_TYPE) | Native MessagePack string "lrgp.v1". |
Field 0xFD (FIELD_CUSTOM_META) | Native MessagePack map capped at 200 packed bytes (ENVELOPE_MAX_PACKED). |
Key a (KEY_APP) | "<app_id>.<version>" (for example "ttt.1" or "coin.1"). |
Key c (KEY_COMMAND) | Action verb ("challenge", "accept", "decline", "move", "resign", "draw_offer", "draw_accept", "draw_decline", "error"). |
Key s (KEY_SESSION) | Canonical 16-character lowercase hex session ID. |
Key p (KEY_PAYLOAD) | Compact game-specific map (move deltas, not full snapshots when avoidable). |
Key n (KEY_NONCE) | 8-byte random replay nonce. |
2. Rust tutorial (lrgp-rs)
Add lrgp (tag v0.4.1) to Cargo.toml:
[dependencies]
lrgp = { git = "https://github.com/ratspeak/lrgp-rs.git", tag = "v0.4.1" }
rmpv = "1"
Step A: Pack, budget-check, and embed into LXMF (lrgp::protocol)
Start with the canonical lrgp::protocol facade (verified against lrgp-rs/examples/basic_envelope.rs) and install pre-encoded MessagePack bytes into LxMessageDraft:
use std::collections::HashMap;
use lrgp::protocol::*;
use lrgp::transport::pack_into_preencoded_fields;
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
fn build_lrgp_lxmf_draft(
dest_hash: [u8; 16],
src_hash: [u8; 16],
) -> Result<LxMessageDraft, Box<dyn std::error::Error>> {
// 1. Build a compact move payload and pack the LRGP envelope
let mut payload = HashMap::new();
payload.insert("i".to_string(), rmpv::Value::Integer(4.into()));
payload.insert("b".to_string(), rmpv::Value::String("____X____".into()));
payload.insert("n".to_string(), rmpv::Value::Integer(1.into()));
payload.insert("t".to_string(), rmpv::Value::String("remote_identity".into()));
payload.insert("x".to_string(), rmpv::Value::String("".into()));
let move_env = pack_envelope("ttt", 1, "move", "a1b2c3d4e5f60718", Some(payload), None)?;
assert!(validate_envelope_size(&move_env)? <= ENVELOPE_MAX_PACKED);
// 2. Encode each LXMF field as one complete native MessagePack value
let preencoded = pack_into_preencoded_fields(&move_env)?;
// 3. Install into LxMessageDraft with set_msgpack_field (NEVER set_field)
let mut draft = LxMessageDraft::new(
dest_hash,
src_hash,
"",
"[LRGP TTT] Move 1: X plays center",
DeliveryMethod::Direct,
)?;
for (field_id, bytes) in preencoded {
draft.set_msgpack_field(field_id, bytes)?;
}
Ok(draft)
}
set_msgpack_field gotcha with lxmf-coreAlways install fields from pack_into_preencoded_fields using LxMessageDraft::set_msgpack_field, never set_field. Calling set_field encodes them as MessagePack binary blobs (bin("lrgp.v1") instead of str("lrgp.v1")), which Python lrgp-py and Ratspeak clients reject as non-interoperable.
Step B: Drive a session through LrgpRouter
For full session lifecycle, participant binding, and replay deduplication, route every action through LrgpRouter (verified against lrgp-rs/examples/tictactoe_game.rs):
use std::collections::HashMap;
use lrgp::app_base::IncomingDispatch;
use lrgp::apps::tictactoe::TicTacToeApp;
use lrgp::router::LrgpRouter;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let router = LrgpRouter::new();
router.register(Box::new(TicTacToeApp::new()));
let player_a = "aaaa1111bbbb2222";
let player_b = "cccc3333dddd4444";
// 1. Player A challenges Player B (empty session_id auto-generates a 16-hex ID)
let challenge = router.dispatch_outgoing_to(
"ttt", 1, "challenge", "", &HashMap::new(), player_a, player_b,
)?;
let sid = challenge.session_id.clone();
// 2. Player B receives the challenge (authenticated sender_hash from LXMF!)
match router.dispatch_incoming(&challenge.envelope, player_a, player_b)? {
IncomingDispatch::Applied(res) => println!("Challenge applied: {:?}", res.emit),
IncomingDispatch::RemoteError(err) => println!("Peer error: {} ({})", err.message, err.code),
IncomingDispatch::Replay => println!("Duplicate nonce ignored"),
}
// 3. Player B accepts, Player A receives accept
let accept = router.dispatch_outgoing_to(
"ttt", 1, "accept", &sid, &HashMap::new(), player_b, player_a,
)?;
router.dispatch_incoming(&accept.envelope, player_b, player_a)?;
// 4. Player A plays center cell (4)
let mut move_payload = HashMap::new();
move_payload.insert("i".to_string(), rmpv::Value::Integer(4.into()));
let mv = router.dispatch_outgoing_to(
"ttt", 1, "move", &sid, &move_payload, player_a, player_b,
)?;
println!("Fallback text: {}", mv.fallback_text);
router.dispatch_incoming(&mv.envelope, player_a, player_b)?;
Ok(())
}
Step C: Implementing a custom GameApp in Rust
To create a new Rust game, implement lrgp::app_base::GameApp (Send + Sync):
- Metadata:
app_id(&self),version(&self), andmanifest(&self) -> AppManifest(declaresactions,preferred_delivery,ttl,validation,max_players). - Action validation: Implement both
validate_action(...)(for enriched incoming wire payloads) and overridevalidate_outgoing_action(...)(for concise local UI intents beforehandle_outgoingmutates state). - State transitions: Implement
handle_outgoing(...) -> OutgoingResult(returns enriched wirepayload+fallback_text) andhandle_incoming(...) -> IncomingResult(returns updatedsession, UIemit, orerror). - Inspection & fallback: Implement
get_session_state(...)andrender_fallback(...). - Registration: Call
router.register(Box::new(MyGame::new()))(and add tolrgp::apps::builtin_games()if extending the built-in crate set).
Run the complete Rust examples locally:
cd lrgp-rs
cargo run --example basic_envelope
cargo run --example tictactoe_game
cargo run --features test-helpers --example chess_game
3. Python tutorial (lrgp-py)
Install lrgp-py in a virtual environment (pip install -e '.[chess,dev]', Python 3.8+).
Subclass GameBase and implement all five abstract hooks (handle_incoming, handle_outgoing, validate_action, get_session_state, render_fallback), then drive both peers through LrgpRouter:
from lrgp.app_base import GameBase
from lrgp.constants import CMD_CHALLENGE, CMD_ACCEPT, CMD_DECLINE, CMD_MOVE
from lrgp.router import LrgpRouter
from lrgp.session import Session, SessionStateMachine
class NumberGuessGame(GameBase):
"""Minimal runnable two-player LRGP game: guess 1..5."""
app_id = "guess"
version = 1
display_name = "Number Guess"
icon = "hash"
session_type = "single_round"
min_players = 2
max_players = 2
validation = "both"
actions = [CMD_CHALLENGE, CMD_ACCEPT, CMD_DECLINE, CMD_MOVE]
preferred_delivery = {a: "direct" for a in actions}
ttl = {"pending": 86400, "active": 3600}
def validate_action(self, session_id, command, payload, sender_hash, identity_id=""):
if command == CMD_MOVE:
val = payload.get("g")
if not isinstance(val, int) or not (1 <= val <= 5):
return False, "guess 'g' must be an integer 1..5"
return True, None
def handle_outgoing(self, session_id, command, payload, identity_id):
if command == CMD_CHALLENGE:
session = Session(
session_id=session_id, app_id=self.app_id, app_version=self.version,
identity_id=identity_id, initiator=identity_id, status="pending",
metadata={"guesses": {}},
)
self._save_session(session)
return {}, self.render_fallback(command, {})
session = self._get_session(session_id, identity_id)
if command == CMD_ACCEPT:
SessionStateMachine.apply_command(session, CMD_ACCEPT)
self._save_session(session)
return {}, self.render_fallback(command, {})
if command == CMD_MOVE:
ok, err = self.validate_action(session_id, command, payload, identity_id, identity_id)
if not ok:
raise ValueError(err)
out = {"g": payload["g"]}
session.metadata["guesses"][identity_id] = payload["g"]
done = len(session.metadata["guesses"]) >= 2
SessionStateMachine.apply_command(session, CMD_MOVE, terminal=done)
self._save_session(session)
return out, self.render_fallback(command, out)
return dict(payload), self.render_fallback(command, payload)
def handle_incoming(self, session_id, command, payload, sender_hash, identity_id):
ok, err = self.validate_action(session_id, command, payload, sender_hash, identity_id)
if not ok:
return {"session": None, "emit": None, "error": {"code": "invalid_move", "msg": err}}
if command == CMD_CHALLENGE:
session = Session(
session_id=session_id, app_id=self.app_id, app_version=self.version,
identity_id=identity_id, contact_hash=sender_hash,
initiator=sender_hash, status="pending",
metadata={"guesses": {}},
)
self._save_session(session)
return {"session": session.to_dict(), "emit": {"type": "challenge", "session_id": session_id}, "error": None}
session = self._get_session(session_id, identity_id)
if command == CMD_ACCEPT:
SessionStateMachine.apply_command(session, CMD_ACCEPT)
elif command == CMD_MOVE:
session.metadata["guesses"][sender_hash] = payload["g"]
done = len(session.metadata["guesses"]) >= 2
SessionStateMachine.apply_command(session, CMD_MOVE, terminal=done)
self._save_session(session)
return {"session": session.to_dict(), "emit": {"type": command, "payload": payload}, "error": None}
def get_session_state(self, session_id, identity_id):
session = self._get_session(session_id, identity_id)
return session.to_dict() if session else {}
def render_fallback(self, command, payload):
if command == CMD_MOVE:
return f"[LRGP Guess] Played {payload.get('g')}"
return f"[LRGP Guess] {command}"
# Drive two players in-memory via LrgpRouter
router = LrgpRouter()
router.register(NumberGuessGame())
alice, bob = "aaaa1111bbbb2222", "cccc3333dddd4444"
chal = router.dispatch_outgoing_to("guess", CMD_CHALLENGE, {}, "", alice, bob)
router.dispatch_incoming(chal.envelope, alice, bob)
acc = router.dispatch_outgoing_to("guess", CMD_ACCEPT, {}, chal.session_id, bob, alice)
router.dispatch_incoming(acc.envelope, bob, alice)
mv = router.dispatch_outgoing_to("guess", CMD_MOVE, {"g": 3}, chal.session_id, alice, bob)
verdict = router.dispatch_incoming(mv.envelope, alice, bob)
print("Fallback:", mv.fallback_text, "| Verdict:", verdict.kind, verdict["emit"])
Run the bundled Python simulations locally:
cd lrgp-py
python examples/ttt_local.py
python examples/chess_local.py
python examples/envelope_sizes.py
4. Security, replay, and persistence rules
- Authenticate at the LXMF boundary: Always pass the cryptographically verified LXMF
source_hashassender_hashintodispatch_incomingand your receiving local identity asidentity_id. Never trust a sender field embedded inside a payload or display name. - Handle retransmissions and remote errors cleanly:
LrgpRouterenforces a bounded replay cache (512 nonces per(identity, session)scope, 1,024 scopes, 10-minute absolute TTL). TreatIncomingDispatch::Replayas a no-op, and treatIncomingDispatch::RemoteErroras observational (never reply to anerrorwith anothererror). - Serialize persistence & rollback: If
dispatch_outgoing_tosucceeds in memory but your SQLite write or LXMF submission fails, follow the router's snapshot/rollback contract so local game state never diverges from what was actually persisted or sent. - Stay well under the 200-byte envelope budget: Send compact move deltas (such as UCI strings
e2e4for Chess or a single column index for Four in a Row) and reconstruct full boards deterministically on both peers.
Next steps
- Review the wire spec summary in LRGP reference and
lrgp-rs/SPEC.md. - Try the built-in games in Games.