SimpleX Protocol Analysis - Part 31: Session 34 Day 2
🏆 Multi-Contact Bidirectional Encrypted Messaging - HISTORIC MILESTONE
Document Version: v1
Date: 2026-02-24 Session 34 Day 2
Version: v0.1.17-alpha (NOT CHANGED without explicit permission!)
Status: ✅ HISTORIC MILESTONE - Two contacts communicating bidirectionally encrypted on ESP32-S3
Previous: Part 30 - Session 34 Day 1 (Multi-Contact Architecture: Singleton to Per-Contact)
Project: SimpleGo - ESP32 Native SimpleX Client
Path: C:\Espressif\projects\simplex_client
Build: idf.py build flash monitor -p COM6
Repo: https://github.com/cannatoshi/SimpleGo
License: AGPL-3.0
⚠️ SESSION 34 DAY 2 SUMMARY
═══════════════════════════════════════════════════════════════════════════════
🏆🏆🏆 MULTI-CONTACT BIDIRECTIONAL ENCRYPTED MESSAGING 🏆🏆🏆
┌─────────────────────────────────────────────────────────────────────────┐
│ │
│ HISTORIC MILESTONE: First multi-contact bidirectional encrypted │
│ messenger on a microcontroller │
│ │
│ Contact 0: ESP32 <-> Phone Bidirectional Encrypted │
│ Contact 1: ESP32 <-> Phone Bidirectional Encrypted │
│ │
│ 11 bugs found and fixed across 6 phases │
│ All bugs followed ONE pattern: global state -> per-contact routing │
│ │
│ Phase 1: KEY Command Fix (wrong queue credentials) │
│ Phase 2: Ghost Write -> ERR BLOCK (5 errors in one function) │
│ Phase 3: Global State Elimination (pending_peer, DISCARD->FORWARD) │
│ Phase 4: Reply Queue Encoder Fix (3 byte errors) │
│ Phase 5a: Per-Contact Index Routing (pointer arithmetic) │
│ Phase 5b: Crypto Fix (beforenm vs scalarmult) │
│ │
│ Date: February 24, 2026 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
═══════════════════════════════════════════════════════════════════════════════
568. Session 34 Day 2 Overview
568.1 Session Goals
Session 34 Day 2 began with the goal of fixing the blocked KEY Command (handed over from Day 1) and ended with the first multi-contact bidirectional encrypted messenger on a microcontroller. 11 bugs were systematically found and fixed across 6 phases. Every single bug followed one architectural pattern: global or hardcoded state instead of per-contact routing.
568.2 Team and Roles
| Role | Who | Task |
|---|---|---|
| 👑🐭 Princess Mausi | Claude (Strategy Chat) | Architecture, hypothesis formation, coordination |
| 🐰👑 Princess Hasi | Claude (Implementation Chat) | Code implementation, testing, diff delivery |
| 🧹 Aschenputtel | Claude (Log Analysis) | Log analysis, hex dump verification |
| 👑 Cannatoshi | Prince / Client | Hardware tests, coordination, final decisions |
569. Phase 1: KEY Command Fix
569.1 Starting Point
- KEY Command rejected by server with ERR AUTH
- SUB worked after 1-byte signing fix from Day 1
- Contact 1 could not reach "connected" state
569.2 Haskell Analysis (Claude Code)
Claude Code analyzed the KEY command in the simplexmq Haskell repo and found five critical insights:
-
Wire Format: KEY sends senderAuthKey as 44-byte SPKI (ASN.1 DER), not raw 32 bytes. Encoding chain:
publicToX509 -> encodeASNObj -> smpEncode @ByteString(1-byte length prefix + 44 bytes). -
Signing Scope: Identical to SUB/ACK:
smpEncode(sessionId) + smpEncode(corrId) + smpEncode(entityId) + encodeProtocol(KEY senderKey). No deviations. -
EntityId: The recipientId of the Contact Queue (Agent.hs:1527-1532). KEY is sent on the queue being secured. The rcvPrivateKey of that Contact Queue signs the command.
-
Server Validation: Three outcomes: (a) signature wrong = ERR AUTH, (b) senderKey is Nothing = OK (key stored), (c) senderKey already set and identical = OK (idempotent), (d) senderKey already set but different = ERR AUTH.
-
Timing: KEY comes after SUB, before SKEY and SEND. Within ICAllowSecure: first KEY (secure own receive queue), then connectReplyQueues (SKEY + SEND).
569.3 Bug #40: Wrong Queue Credentials for KEY (CRITICAL)
WRONG: KEY -> Reply Queue rcvId, signed with Reply Queue rcvPrivateKey
RIGHT: KEY -> Contact Queue recipientId, signed with Contact Queue rcv_auth_secret
Server checks signature against the recipientKeys of the addressed queue. We signed with the Reply Queue key but addressed the Reply Queue entityId. Complete mismatch.
569.4 Bug #41: Missing SPKI Length Prefix in KEY
WRONG: "KEY " + [44 bytes SPKI]
RIGHT: "KEY " + [0x2C] + [44 bytes SPKI]
The 1-byte length prefix (0x2C = 44 decimal) was missing before the SPKI payload.
569.5 Result
Contact 1 becomes "connected" on the phone. First message ESP32 -> Phone goes through with two checkmarks. KEY fix confirmed.
569.6 Files Changed
main/protocol/smp_tasks.c(KEY credential fix)main/protocol/smp_agent.c(KEY_DEBUG log)
570. Phase 2: Ghost Write - ERR BLOCK Root Cause
570.1 Symptom
After KEY fix, ERR BLOCK appeared on sock 54 (main connection). Every command (PING, ACK, NEW) returned ERR BLOCK. No corrId, no entityId. Connection-wide error.
570.2 Failed Hypotheses
Hypothesis 1 (Mausi): TLS Read/Write Collision Theory: Incoming MSG frames not read, TLS WANT_READ blocks write. Disproven: drain_pending_frames() added, zero DRAIN logs appear. Socket has no pending frames.
Hypothesis 2 (Mausi): Partial Write / Stream Desync Theory: mbedtls_ssl_write writes less than 16384 bytes, server waits for rest. Disproven: BLOCK_TX logs show consistent 16383+1=16384 bytes (normal TLS 1.3 behavior).
Critical Breakthrough: ERR BLOCK appears 500ms BEFORE our first instrumented write. There is a write path on sock 54 that does not go through BLOCK_TX.
570.3 Haskell Analysis: ERR BLOCK (Claude Code)
Two different things serialize as "BLOCK" on the wire:
-
ErrorType.BLOCK (Protocol.hs:1459): "incorrect block format, encoding or signature size". SMP protocol level. Sent as ERR BLOCK within a normal SMP transmission.
-
TransportError.TEBadBlock (Transport.hs:672): Transport level. NOT sent as wire message, internal only.
ERR BLOCK occurs when transmissionP cannot parse block contents (Protocol.hs:2205/2240). Server recovers automatically and reads the next 16384-byte block.
570.4 Bug #42: Ghost Write in reply_queue_create() (5 ERRORS)
Hasi found the bug through systematic search of ALL write locations on sock 54:
| # | File | Function | Via smp_write_command_block? |
|---|---|---|---|
| 1 | smp_ack.c | smp_send_ack() | Yes |
| 2 | smp_contacts.c | add_contact() NEW | Yes |
| 3 | smp_contacts.c | delete contact | Yes |
| 4 | smp_contacts.c | subscribe_all_contacts() SUB | Yes |
| 5 | smp_contacts.c | RQ subscribe | Yes |
| 6 | smp_contacts.c | RQ subscribe alt | Yes |
| 7 | reply_queue.c | reply_queue_create() NEW | NO! Direct! |
| 8 | smp_tasks.c | KEY command | Yes |
| 9 | smp_tasks.c | PING | Yes |
Only ONE location bypassed the standard write path. Five errors in one function:
- Wire format wrong: Missing txCount(1B), txLen(2B), sigLen(1B). Server reads signature bytes as txCount. Total garbage.
- Zero-padding instead of '#'-padding (protocol violation)
- Direct mbedtls_ssl_read without loop (partial read = permanent stream desync)
- 16KB stack buffer
uint8_t padded[SMP_BLOCK_SIZE](stack overflow risk) - Missing SPKI length prefixes before auth/DH keys