C# and Unity
Join a host by a short room code (HK4M-7TRW) over WebRTC, with the SDP carried through public Nostr relays and an optional password (CPace). This is the C# implementation of Atyha v1. It reproduces vectors/atyha-v1.json byte for byte and works with the TypeScript reference over the real relays.
| path | what |
|---|---|
Atyha/ | the core: netstandard2.1, pure managed C# (no native code, no unsafe, no reflection, no JSON library) |
Atyha.Tests/ | console tests: standard vectors for every primitive, the Atyha vectors, sessions over an in-memory bus |
Atyha.Echo/ | the echo example on SIPSorcery (managed WebRTC), the same output lines as ts/tools/peer.ts |
unity/com.ngspades.atyha/ | the Unity package: the core, main-thread pump, WebGL WebSocket, com.unity.webrtc glue, an Echo sample |
tools/sync-unity.sh | copies Atyha/ into the package and writes its .meta files (run it after changing the core) |
Licence: MIT.
Core API
using Atyha;
using Atyha.Json;
// host
var host = new Host(new HostOptions {
App = "my-game", // 1 to 64 UTF-8 bytes
Password = "", // "" or null: the code alone opens the room
Ice = new[] { new IceServer("stun:stun.l.google.com:19302") }, // sent to joiners
Meta = new JsonObject { { "name", "Gustavo's room" } }, // sent to joiners
OnOpen = () => Show(host.DisplayCode), // a relay confirmed: the code works now
OnOffer = async offer => { // offer.Sdp, offer.Meta, offer.Joiner
if (full) return OfferReply.Reject("server full");
return OfferReply.Answer(await MakeAnswer(offer.Sdp)); // complete SDP, no trickle
},
});
host.Close();
// joiner
try {
Joined j = await Joiner.JoinAsync(new JoinOptions {
App = "my-game", Code = typedText, Password = typedPassword,
Meta = new JsonObject { { "player", "p1" } },
MakeOffer = async (ice, hostMeta) => await MakeOffer(ice), // ice: the host's list, or null
}, cancellationToken);
SetAnswer(j.Sdp); // j.HostMeta
} catch (JoinException e) {
// e.Code: BadCode, NoRelay, NoRoom, WrongPassword, Rejected (e.Message is the reason), NoAnswer, Cancelled
// e.CodeName: "bad_code", "no_relay", ...
}Also public: RoomCode (Generate, Parse, Display), Protocol (Topic, Prs, Ci, Keys, Seal, Open, the CPace sides), CPace, Message, B64u, the bus (Atyha.Transport: IBus, BusFactory, Nostr.Bus(options), Nostr.DefaultRelays, MemoryHub, IWebSocketFactory, ClientWebSocketFactory), the JSON model (Atyha.Json) and the primitives (Atyha.Crypto: Sha256, Sha512, Hkdf, ChaCha20Poly1305, Ristretto255, Schnorr, SecureRandom).
Behaviour follows the TypeScript reference: hello every 2 s until a pake, offer every 2 s until a reply, no_relay when no relay confirms in 10 s, no_room 25 s after the first hello, wrong_password 4 s after a pake that does not open, no_answer 25 s after the first offer; the host answers at most 20 hellos per 60 s (HelloBudget), keeps attempts 60 s, sends the same pake/reply again for a repeated hello/offer; events outside ±60 s, our own events and seen event ids are dropped; a relay that says rate-limited: is closed and reopened after 60 s, one that says blocked:, restricted:, auth-required: or pow: is dropped for the session, other closes reconnect after 2 s doubling to 30 s.
Threads
Every session runs on an AtyhaLoop. All its state is touched only inside loop.Update(), and every callback you give (OnOffer, OnOpen, MakeOffer, Log) runs there, so **the thread that pumps the loop is the thread you hear from**:
- Unity: the package sets
AtyhaLoop.Defaultto a loop pumped from a hidden MonoBehaviour'sUpdate(): callbacks run on the main thread, and nothing needs threads (WebGL).await Joiner.JoinAsync(...)from a MonoBehaviour resumes on the main thread as usual. - Elsewhere:
AtyhaLoop.Defaultis a loop with its own background thread; callbacks run on that thread. - Your own pump:
var loop = new AtyhaLoop();pass it asoptions.Loopand callloop.Update()from your game loop.
JoinAsync's task completes with RunContinuationsAsynchronously, so your continuation never runs inside the loop.
Platform notes
- SHA-2, HMAC/HKDF, ChaCha20-Poly1305, ristretto255 and secp256k1 BIP-340 are managed code (
System.Security.Cryptographyis not used exceptRandomNumberGenerator, replaceable throughSecureRandom.Source; the Unity package usescrypto.getRandomValueson WebGL). - ristretto255 and secp256k1 use
System.Numerics.BigInteger, with Montgomery ladders (the same operation sequence for every scalar) but BigInteger itself is not constant time. One handshake is a few scalar multiplications (about 10 ms each on a desktop) plus one BIP-340 signature per published event. Poly1305 is the 26-bit-limb donna code, no BigInteger. - C# 9 at most, so Unity 2021.3+ compiles it.
Running
brew install dotnet # the .NET SDK (this was built with 11.0.100 from Homebrew)
dotnet build Atyha.Tests && dotnet Atyha.Tests/bin/Debug/net8.0/Atyha.Tests.dll [filter]
dotnet build Atyha.Echo
dotnet Atyha.Echo/bin/Debug/net8.0/Atyha.Echo.dll host [--app A] [--password P] [--verbose]
dotnet Atyha.Echo/bin/Debug/net8.0/Atyha.Echo.dll join HK4M-7TRW [--app A] [--password P](The projects target net8.0 with RollForward=Major, so any .NET 8+ runtime runs them. Note that dotnet run -nologo hands -nologo to the program; run the built dll, or dotnet run --.)
The echo contract is the reference peer's: the host answers a text x on reliable with echo x and sends binary back on the channel it came by; the joiner prints CONNECTED <host meta>, RELIABLE <text>, UNRELIABLE 1,2,3 and exits 0, or prints FAILED <code> <message>.
Unity
Install by git URL (Package Manager > Add package from git URL), pointing at this folder of the repository:
https://<your git host>/<repo>.git?path=/atyha/csharp/unity/com.ngspades.atyhaor add it to Packages/manifest.json the same way. For WebRTC add com.unity.webrtc 3.x (3.0.0-pre.7 or later); the Atyha.WebRtc assembly (UnityPeers.JoinPeerAsync, UnityPeers.HostPeers, the section 9 DataChannel profile, no trickle: gathering is awaited up to 5 s) compiles only when that package is present. Import the Echo sample from the Package Manager, put EchoSample on a GameObject and press play: Host shows the code, Join takes code and password.
The signalling core works on WebGL (browser WebSockets through AtyhaWebSocket.jslib), but com.unity.webrtc does not support WebGL: there you need your own WebRTC (the browser's, through a .jslib) and Host/Joiner with MakeOffer/OnOffer around it.
What is tested and what is not
Tested here (macOS, .NET 11):
- every primitive against standard vectors: NIST SHA-256/SHA-512 (plus every length 0..300 against System.Security.Cryptography), RFC 4231 HMAC, RFC 5869 HKDF, RFC 8439 ChaCha20 / Poly1305 (with the A.3 edge cases) / AEAD, RFC 9496 appendix A (generator multiples, all invalid encodings, element derivation, SQRT_RATIO_M1), the BIP-340
test-vectors.csv(signing and verification), a NIP-01 event id; vectors/atyha-v1.json, every value of every case, byte for byte;- sessions over the in-memory bus: no password, right password, wrong and empty password (
wrong_passwordafter 4 s), other app (no_room), reject with reason, a throwingOnOffer, the hello budget, bad code, cancellation, eight joiners at once, a loop pumped by the caller; - interop over the real public relays with SIPSorcery: C# host with the TS joiner, TS host with the C# joiner, C# with C#, with and without a password (including a non-ASCII one), wrong password both ways.
Not tested (no Unity available when this was written): everything under unity/ except the core sources it copies: AtyhaUnity (main-thread pump), the WebGL WebSocket (WebGLWebSocket.cs and the .jslib), the com.unity.webrtc glue (UnityPeers) and the Echo sample. They were compiled only against hand-written stand-ins for the UnityEngine and com.unity.webrtc API, which checks the C# but not that the real API matches. Also untested: ClientWebSocket and BigInteger performance under IL2CPP on devices.