-
Notifications
You must be signed in to change notification settings - Fork 2
feat(l2ps-messaging): add crypto and integration tests for messaging … #686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Shitikyan
wants to merge
3
commits into
testnet
Choose a base branch
from
feat-l2ps-messaging
base: testnet
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
42e09a9
feat(l2ps-messaging): add crypto and integration tests for messaging …
Shitikyan 4df26f3
feat(l2ps-messaging): enforce registration checks before peer discove…
Shitikyan 540a783
feat(l2ps-messaging): enhance message processing and error handling f…
Shitikyan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,249 @@ | ||
| #!/usr/bin/env bun | ||
| /** | ||
| * L2PS Messaging E2E Test | ||
| * | ||
| * Connects two peers to the L2PS messaging server, exchanges messages, | ||
| * and verifies delivery. Requires a running node with L2PS_MESSAGING_ENABLED=true. | ||
| * | ||
| * Usage: | ||
| * bun scripts/l2ps-messaging-test.ts [--port 3006] [--l2ps-uid testnet_l2ps_001] | ||
| */ | ||
|
|
||
| import { parseArgs } from "node:util" | ||
| import * as forge from "node-forge" | ||
|
|
||
| // ─── CLI Args ──────────────────────────────────────────────────── | ||
|
|
||
| const { values: args } = parseArgs({ | ||
| options: { | ||
| port: { type: "string", default: "3006" }, | ||
| "l2ps-uid": { type: "string", default: "testnet_l2ps_001" }, | ||
| host: { type: "string", default: "localhost" }, | ||
| }, | ||
| }) | ||
|
|
||
| const PORT = args.port ?? "3006" | ||
| const HOST = args.host ?? "localhost" | ||
| const L2PS_UID = args["l2ps-uid"] ?? "testnet_l2ps_001" | ||
| const WS_URL = `ws://${HOST}:${PORT}` | ||
|
|
||
| // ─── Helpers ───────────────────────────────────────────────────── | ||
|
|
||
| function generateEd25519KeyPair() { | ||
| const seed = forge.random.getBytesSync(32) | ||
| const keyPair = forge.pki.ed25519.generateKeyPair({ seed }) | ||
| return { | ||
| publicKey: Buffer.from(keyPair.publicKey).toString("hex"), | ||
| privateKey: keyPair.privateKey, | ||
| publicKeyBytes: keyPair.publicKey, | ||
| } | ||
| } | ||
|
|
||
| function signMessage(message: string, privateKey: any): string { | ||
| // Sign using forge ed25519 — message as UTF-8 string (matches SDK's Cryptography.verify) | ||
| const sig = forge.pki.ed25519.sign({ | ||
| message, | ||
| encoding: "utf8", | ||
| privateKey, | ||
| }) | ||
| return Buffer.from(sig).toString("hex") | ||
| } | ||
|
|
||
| function frame(type: string, payload: Record<string, unknown>, ts?: number) { | ||
| return JSON.stringify({ type, payload, timestamp: ts ?? Date.now() }) | ||
| } | ||
|
|
||
| function connectWS(name: string): Promise<WebSocket> { | ||
| return new Promise((resolve, reject) => { | ||
| const ws = new WebSocket(WS_URL) | ||
| const timeout = setTimeout(() => reject(new Error(`${name}: Connection timeout`)), 5000) | ||
| ws.addEventListener("open", () => { | ||
| clearTimeout(timeout) | ||
| log(name, "Connected") | ||
| resolve(ws) | ||
| }) | ||
| ws.addEventListener("error", () => { | ||
| clearTimeout(timeout) | ||
| reject(new Error(`${name}: Connection failed`)) | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| function waitFor(ws: WebSocket, type: string, timeout = 5000): Promise<any> { | ||
| return new Promise((resolve, reject) => { | ||
| const timer = setTimeout(() => reject(new Error(`Timeout waiting for '${type}'`)), timeout) | ||
| const handler = (event: MessageEvent) => { | ||
| const msg = JSON.parse(event.data) | ||
| if (msg.type === type) { | ||
| clearTimeout(timer) | ||
| ws.removeEventListener("message", handler) | ||
| resolve(msg) | ||
| } | ||
| } | ||
| ws.addEventListener("message", handler) | ||
| }) | ||
| } | ||
|
|
||
| function waitForAny(ws: WebSocket, types: string[], timeout = 5000): Promise<any> { | ||
| return new Promise((resolve, reject) => { | ||
| const timer = setTimeout(() => reject(new Error(`Timeout waiting for '${types.join("|")}'`)), timeout) | ||
| const handler = (event: MessageEvent) => { | ||
| const msg = JSON.parse(event.data) | ||
| if (types.includes(msg.type)) { | ||
| clearTimeout(timer) | ||
| ws.removeEventListener("message", handler) | ||
| resolve(msg) | ||
| } | ||
| } | ||
| ws.addEventListener("message", handler) | ||
| }) | ||
| } | ||
|
|
||
| function log(tag: string, msg: string) { | ||
| console.log(` [${tag}] ${msg}`) | ||
| } | ||
|
|
||
| // ─── Main Test ─────────────────────────────────────────────────── | ||
|
|
||
| async function main() { | ||
| console.log(`\n L2PS Messaging E2E Test`) | ||
| console.log(` Server: ${WS_URL}`) | ||
| console.log(` L2PS UID: ${L2PS_UID}\n`) | ||
|
|
||
| // Generate two key pairs | ||
| const alice = generateEd25519KeyPair() | ||
| const bob = generateEd25519KeyPair() | ||
| log("SETUP", `Alice: ${alice.publicKey.slice(0, 16)}...`) | ||
| log("SETUP", `Bob: ${bob.publicKey.slice(0, 16)}...`) | ||
|
|
||
| // ── Step 1: Connect ────────────────────────────────────────── | ||
| console.log("\n [1/5] Connecting...") | ||
| let wsAlice: WebSocket | ||
| let wsBob: WebSocket | ||
| try { | ||
| wsAlice = await connectWS("Alice") | ||
| wsBob = await connectWS("Bob") | ||
| } catch (e: any) { | ||
| console.error(`\n FAIL: ${e.message}`) | ||
| console.error(` Make sure the node is running with L2PS_MESSAGING_ENABLED=true`) | ||
| process.exit(1) | ||
| } | ||
|
|
||
| // ── Step 2: Register ───────────────────────────────────────── | ||
| console.log("\n [2/5] Registering peers...") | ||
|
|
||
| // Alice registration — timestamp must match between proof and frame | ||
| const aliceTs = Date.now() | ||
| const aliceProof = signMessage(`register:${alice.publicKey}:${aliceTs}`, alice.privateKey) | ||
| wsAlice.send(frame("register", { | ||
| publicKey: alice.publicKey, | ||
| l2psUid: L2PS_UID, | ||
| proof: aliceProof, | ||
| }, aliceTs)) | ||
|
|
||
| const aliceReg = await waitForAny(wsAlice, ["registered", "error"]) | ||
| if (!aliceReg || aliceReg.type === "error") { | ||
| console.error(`\n FAIL: Alice registration failed`) | ||
| if (aliceReg) console.error(` Error: ${aliceReg.payload.code} - ${aliceReg.payload.message}`) | ||
| wsAlice.close(); wsBob.close() | ||
| process.exit(1) | ||
| } | ||
| log("Alice", `Registered. Online peers: ${aliceReg.payload.onlinePeers.length}`) | ||
|
|
||
| // Bob registration | ||
| const bobTs = Date.now() | ||
| const bobProof = signMessage(`register:${bob.publicKey}:${bobTs}`, bob.privateKey) | ||
| const bobJoinedPromise = waitFor(wsAlice, "peer_joined") | ||
| wsBob.send(frame("register", { | ||
| publicKey: bob.publicKey, | ||
| l2psUid: L2PS_UID, | ||
| proof: bobProof, | ||
| }, bobTs)) | ||
|
|
||
| const bobReg = await waitForAny(wsBob, ["registered", "error"]) | ||
| if (!bobReg || bobReg.type === "error") { | ||
| console.error(`\n FAIL: Bob registration failed`) | ||
| if (bobReg) console.error(` Error: ${bobReg.payload.code} - ${bobReg.payload.message}`) | ||
| wsAlice.close(); wsBob.close() | ||
| process.exit(1) | ||
| } | ||
| log("Bob", `Registered. Online peers: ${bobReg.payload.onlinePeers.length}`) | ||
|
|
||
| const joined = await bobJoinedPromise | ||
|
Check warning on line 172 in scripts/l2ps-messaging-test.ts
|
||
| log("Alice", `Received peer_joined notification for Bob`) | ||
|
|
||
| // ── Step 3: Discover ───────────────────────────────────────── | ||
| console.log("\n [3/5] Discovering peers...") | ||
| wsAlice.send(frame("discover", {})) | ||
| const discoverResp = await waitFor(wsAlice, "discover_response") | ||
| log("Alice", `Online peers: [${discoverResp.payload.peers.map((p: string) => p.slice(0, 12) + "...").join(", ")}]`) | ||
|
|
||
| // ── Step 4: Send messages ──────────────────────────────────── | ||
| console.log("\n [4/5] Exchanging messages...") | ||
|
|
||
| // Alice -> Bob | ||
| const msgPromiseBob = waitFor(wsBob, "message") | ||
| wsAlice.send(frame("send", { | ||
| to: bob.publicKey, | ||
| encrypted: { | ||
| ciphertext: Buffer.from("Hello Bob from Alice!").toString("base64"), | ||
| nonce: Buffer.from("test_nonce_1").toString("base64"), | ||
| }, | ||
| messageHash: "hash_alice_to_bob_" + Date.now(), | ||
| })) | ||
|
|
||
| const msgBob = await msgPromiseBob | ||
| log("Bob", `Received message from ${msgBob.payload.from.slice(0, 12)}...`) | ||
| log("Bob", `Decoded: ${Buffer.from(msgBob.payload.encrypted.ciphertext, "base64").toString()}`) | ||
|
|
||
| const ackAlice = await waitForAny(wsAlice, ["message_sent", "message_queued", "error"]) | ||
| log("Alice", `Ack: type=${ackAlice.type}`) | ||
|
|
||
| // Bob -> Alice | ||
| const msgPromiseAlice = waitFor(wsAlice, "message") | ||
| wsBob.send(frame("send", { | ||
| to: alice.publicKey, | ||
| encrypted: { | ||
| ciphertext: Buffer.from("Hey Alice, got your message!").toString("base64"), | ||
| nonce: Buffer.from("test_nonce_2").toString("base64"), | ||
| }, | ||
| messageHash: "hash_bob_to_alice_" + Date.now(), | ||
| })) | ||
|
|
||
| const msgAlice = await msgPromiseAlice | ||
| log("Alice", `Received message from ${msgAlice.payload.from.slice(0, 12)}...`) | ||
| log("Alice", `Decoded: ${Buffer.from(msgAlice.payload.encrypted.ciphertext, "base64").toString()}`) | ||
|
|
||
| const ackBob = await waitForAny(wsBob, ["message_sent", "message_queued", "error"]) | ||
| log("Bob", `Ack: type=${ackBob.type}`) | ||
|
|
||
| // ── Step 5: Disconnect ─────────────────────────────────────── | ||
| console.log("\n [5/5] Testing disconnect...") | ||
| const leftPromise = waitFor(wsAlice, "peer_left") | ||
| wsBob.close() | ||
| const left = await leftPromise | ||
| log("Alice", `Received peer_left for ${left.payload.publicKey.slice(0, 12)}...`) | ||
| wsAlice.close() | ||
|
|
||
| // ── Results ────────────────────────────────────────────────── | ||
| console.log("\n ══════════════════════════════════════════") | ||
| console.log(" All E2E tests passed!") | ||
| console.log(" ══════════════════════════════════════════") | ||
| console.log(` | ||
| Summary: | ||
| - WebSocket connection: OK | ||
| - Peer registration: OK (with ed25519 proof) | ||
| - Peer discovery: OK | ||
| - Message delivery: OK (Alice -> Bob, Bob -> Alice) | ||
| - L2PS submission: ${ackAlice.type === "message_sent" ? "OK" : "WARN: " + ackAlice.type} | ||
| - Peer notifications: OK (join + leave) | ||
| - Disconnect handling: OK | ||
| `) | ||
|
|
||
| process.exit(0) | ||
| } | ||
|
|
||
| main().catch((err) => { | ||
|
Check warning on line 246 in scripts/l2ps-messaging-test.ts
|
||
| console.error(`\n FAIL: ${err.message}`) | ||
| process.exit(1) | ||
| }) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Arm the sender ACK waiter before awaiting the recipient frame.
Both flows subscribe for
"message_sent" | "message_queued" | "error"only afterawait msgPromise.... IfprocessMessage()finishes quickly, the ACK can arrive on the sender socket beforewaitForAny()is attached, so this script will fail intermittently.Suggested fix
Apply the same pattern to the Bob → Alice block.
Also applies to: 203-218
🤖 Prompt for AI Agents