Protocol reference
The wire facts of a 1:1 WhatsApp voice call from the caller's side, stanza by stanza and byte by byte.
This is the reference an implementer works from. It describes wire facts only:
stanza shapes, byte layouts, constants, key derivations, timings and ordering.
It was written by reading a working TypeScript caller (baileys-voip) and checking
its claims against a JSONL trace of a real call placed with it on 2026-12-02
(CALL_RELAY_PORT_MODE=web). Where the reference has env switches, the default
path is described and deviations used in our test are called out.
Every fact is tagged where it matters:
- [trace] confirmed by decoding bytes from the real call trace
- [ref] what the reference implementation does; not independently confirmed
- [inferred] a reasoned conclusion that neither source states directly
Placeholders: <self> is our LID user part, <peer> the callee's LID user part,
<selfDev> our device number, <callid> the call ID, <ssrc> our uplink SSRC.
No phone numbers, LIDs or keys from the trace appear here.
0. Already implemented (do not re-derive)
These match the real call byte for byte and live in srtp and ssrc:
- Per-direction E2E SRTP keys:
master = HKDF-SHA256(ikm = callKey[0:32], salt = 32 zero bytes, info = sender's device-qualified LID, L = 46),master_key = master[0:16],master_salt = master[16:30], then the RFC 3711 AES-CM PRF with labels 0x00 (16-byte cipher key), 0x01 (20-byte auth key), 0x02 (14-byte salt). IV per RFC 3711 4.1.1 from salt, SSRC and(ROC << 16) | seq. - WARP MI tag on RTP:
HMAC-SHA1(authKey, packet_without_tag || ROC as BE32)[0:4], appended after the ciphertext. No other SRTP auth tag. - Participant SSRC:
HKDF-SHA256(ikm = callId UTF-8, salt = slot as LE32, info = device-qualified LID, L = 4)read as little-endian uint32. Uplink SSRC is our slot 0. - 9-entry relay stream plan: slot words
[0, 1, 4, 2, 3, 5, 7, 8, 6]derived from our own LID, assigned in order to(participant, stream)=(0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2).
New in this document, beyond the above: SRTCP uses different PRF labels and tag length on the native side (section 5.6), and the downlink keys are now confirmed (section 6).
1. Identities and JIDs
| Name | Form | Source |
|---|---|---|
| Our device LID | <self>:<selfDev>@lid | session credentials (me.lid). Used as call-creator, as HKDF info for uplink keys and as SSRC info. |
| Peer bare LID | <peer>@lid | LID mapping for the peer's phone number |
| Peer device list | <peer>@lid for device 0, <peer>:<n>@lid for others | USync device query for the peer bare LID. Device 0 (the primary phone) is written without :0 on the wire. |
| Device-qualified LID for crypto | always <user>:<device>@lid, device 0 written as :0 | needed for keys and SSRCs, see section 6 |
The offer <to> children and the relay's <participant> list both use the
bare form for device 0 [trace]. The native peer derives its SSRC and keys
from <peer>:0@lid [trace]. A Go implementation must keep both forms.
2. Signaling
All call signaling is a <call> stanza with exactly one child. The envelope
carries only to and id; id is a fresh message tag from the session
(Baileys format NNNNN.NNNNN-<counter>, any unique string works) [ref].
<call to="<destination jid>" id="<message tag>">
<child .../>
</call>The server answers every outgoing <call> with an <ack> that has the same
id (section 2.6). Incoming <call> and <receipt> stanzas must themselves be
acked; Baileys and whatsmeow do that automatically (section 2.7).
2.1 Before the offer
- Resolve the peer bare LID from the phone number.
- Fetch the peer's device list (USync,
context=message, device protocol). Keep all devices, including device 0 as<peer>@lid. - Make sure a Signal session exists for every device. For missing ones fetch prekey bundles:
<iq xmlns="encrypt" type="get" to="s.whatsapp.net"><key><user jid="..."/>...</key></iq>and build sessions. This is the normal message-sending path. - Generate
callId= 16 random bytes as 32 uppercase hex characters [ref] (the trace shows 32 uppercase hex). - Generate
callKey= 32 random bytes. - Derive uplink keys, uplink SSRC (slot 0) and the 9-entry stream plan now. The ack can arrive about 500 ms after the offer [trace], and relay setup needs them.
2.2 Call key encryption, per device
Plaintext is a serialized WhatsApp Message protobuf followed by random padding:
| Layer | Field | Number | Wire type | Value |
|---|---|---|---|---|
Message | call | 10 | length-delimited | the Call message below |
Message.Call | callKey | 1 | length-delimited (bytes) | the 32-byte call key |
So the protobuf is exactly 52 22 0A 20 <32 key bytes> (36 bytes). Padding is
the standard WhatsApp message padding: pick n = (random byte & 0x0F) + 1
(1 to 16) and append n bytes each equal to n.
Encrypt with the Signal session of that device (normal msg or pkmsg
ciphertext) and wrap it:
<enc v="2" type="msg|pkmsg" count="0">RAW SIGNAL CIPHERTEXT BYTES</enc>type is pkmsg when the session has an unacknowledged prekey message, else
msg. count is always "0" in the reference.
Reference quirk [ref]: it encrypts once for the peer bare LID only to learn
whether the result is pkmsg, throws that ciphertext away, then encrypts again
per device. That wastes one Signal message counter. A clean implementation
should encrypt once per device and include <device-identity> if any of those
<enc> nodes is pkmsg (that matches normal message sending).
2.3 Outgoing <offer>
Envelope: to = <peer>@lid (bare) [ref]. An earlier WASM-based caller sent
the same offer to <peer>:0@lid and it also worked, so the server accepts
either.
Children, in this order:
| # | Element | Attributes | Content | Notes |
|---|---|---|---|---|
| 1 | privacy | none | 11 raw bytes | Reference sends the constant 04 01 2b d2 d6 dd bc c7 dd c1 2c (override CALL_PRIVACY_HEX). The WASM caller sent the peer's own 11-byte trusted-contact token (tctoken) here, which also begins 04 01. [inferred] This is the peer's tctoken; the server did not reject the reference's constant. |
| 2 | audio | enc="opus" rate="8000" | none | |
| 3 | audio | enc="opus" rate="16000" | none | |
| 4 | net | medium="3" | none | Meaning of 3 unknown. The accept carried medium="2". |
| 5 | capability | ver="1" | 7 raw bytes 01 05 f7 09 e4 bb 13 | Opaque capability bitfield. Peers answer with their own (seen: 0105f509e0bb53, 0105f509e0fa73, 0105fd09e0fa73). |
| 6 | destination | none | one <to jid="<device jid>"> per peer device, each holding one <enc> (2.2) | Bare form for device 0, then the others. With no devices known, a single <to jid="<peer>@lid">. |
| 7 | encopt | keygen="2" | none | See section 6. |
| 8 | device-identity | none | ADVSignedDeviceIdentity protobuf bytes | Only when an <enc> is pkmsg. Fields: 1 details, 2 accountSignatureKey (included when present), 3 accountSignature, 4 deviceSignature. This is our stored account identity, the same blob normal pkmsg messages carry. |
Offer element attributes: call-id="<callid>", call-creator="<self>:<selfDev>@lid".
No video child: an audio call is signalled by its absence.
Rendered (bytes shown as hex, which is how Baileys prints binary content):
<call to="<peer>@lid" id="<tag>">
<offer call-id="<callid>" call-creator="<self>:<selfDev>@lid">
<privacy>04012bd2d6ddbcc7ddc12c</privacy>
<audio enc="opus" rate="8000"/>
<audio enc="opus" rate="16000"/>
<net medium="3"/>
<capability ver="1">0105f709e4bb13</capability>
<destination>
<to jid="<peer>@lid"><enc v="2" type="pkmsg" count="0">...</enc></to>
<to jid="<peer>:6@lid"><enc v="2" type="msg" count="0">...</enc></to>
...
</destination>
<encopt keygen="2"/>
<device-identity>...</device-identity>
</offer>
</call>2.4 The offer ack: relay allocation
The server replies with <ack class="call" type="offer" id="<same tag>" from="<peer>@lid">.
error absent means success (the reference treats a missing error as 0).
Its children, as seen in a real ack [trace of WASM caller log]:
| Child | Used by reference | Content |
|---|---|---|
relay | yes (it is the first child, and the reference only reads the first child) | relay allocation, below |
user jid="<peer>@lid" country_code=".." with <device jid=.../> children | no | the device list the server fanned out to |
rte | no | 6 bytes: IPv4 + BE16 port. [inferred] our public reflexive address as seen by the server |
uploadfieldstat, userrate | no | empty |
voip_settings uncompressed="1" jid="<device>" | no | one per peer device, about 13.6 KB of JSON tuning (aec, bwe, ...) |
<relay> element
Attributes:
| Attribute | Example | Meaning |
|---|---|---|
call-id | <callid> | |
call-creator | <self>:<selfDev>@lid | |
uuid | 16 chars, URL-safe base64 alphabet | relay session id. Not used by the reference. |
self_pid | 1 | our participant id |
peer_pid | 0 | the peer's primary participant id |
joinable | 1 | not used |
attribute_padding | 1 | not used. [inferred] tells the client the relay pads STUN attributes to 4 bytes |
Children are flat under <relay> (no <transport> wrapper in practice; the
reference parser accepts both). Order seen: participants, tokens, auth tokens,
key, endpoints, hbh_key.
| Child | Attributes | Content (raw binary node bytes) | Use |
|---|---|---|---|
participant | pid, jid | none | pid to JID map. pid 0 = <peer>@lid (the phone), 2..n = other peer devices. pid 1 (us) is not listed. |
token | id (index) | relay token, raw bytes (192 to 195 bytes seen, starting 09 0f 01) | STUN RELAY-TOKEN for endpoints whose token_id equals this id |
auth_token | id | raw bytes (70 seen, starting 09 03) | ICE ufrag for the DataChannel transport (base64 of these bytes), selected by the endpoint's auth_token_id |
key | none | 24 ASCII characters: standard base64 text of 16 bytes | Used as the ASCII text, not decoded: STUN MESSAGE-INTEGRITY key and ICE pwd |
hbh_key | none | 40 ASCII characters: base64 text of 30 bytes | hop-by-hop SRTP material, only for group calls. Unused for 1:1 E2E. |
te2 (or te) | relay_id, relay_name, token_id, auth_token_id, domain_name, c2r_rtt, optionally is_fna="1", protocol | endpoint blob, below | one relay address each |
warp_mi_tag_len | none | decimal text | absent in the real ack; default 4 |
conn_id | none | 8 bytes | absent in the real ack; then derived (section 3.5) |
Other transport fields the parser knows (all absent in our ack): auth_token_id,
xtoken_id, prefer_relay, peer_dl, prefer_ipv6, smart_transport_signal,
c2r_rtt, relay_name, domain_name as direct children. te and te2 never
appear together (the parser rejects that).
Endpoint blob, the content of each te2/te:
| Length | Layout |
|---|---|
| 6 bytes | IPv4 address (4 bytes, network order) + port (BE16) |
| 18 bytes | IPv6 address (16 bytes) + port (BE16) |
If the blob has neither length the reference falls back to an addr attribute
(ip or ip:port) and a port attribute. A relay normally appears twice, once
per address family, with identical attributes. The real ack listed three relays,
six endpoints, ordered by ascending c2r_rtt (13, 35, 49 ms): one ISP-hosted
relay (is_fna="1", port 3480) then two Meta edge relays (port 3478) [trace].
Selecting credentials for an endpoint:
relayToken = token whose id == endpoint.token_id (fallback: first token)
authToken = auth_token whose id == endpoint.auth_token_id (may be absent)
relayKey = <key> text bytes, shared by all relaysText-format note for anyone feeding a printed stanza: Baileys renders binary
content as hex. The reference undoes that: tokens are hex-decoded to bytes;
key is hex-decoded and, when the result is base64-looking ASCII, that ASCII is
kept. With whatsmeow nodes you get the raw bytes directly.
2.5 After the ack
The reference applies the relay block immediately: derives keys (already done in 2.1), creates one relay controller per IPv4 endpoint (section 3) and hands the relay list to the transport (section 4). Nothing else is sent to the server at this point.
2.6 Acks for our other stanzas
Every outgoing <call> gets <ack class="call" type="<child tag>" id="<same id>" from="<peer>@lid">.
Seen: the ack for relaylatency echoes <relaylatency call-creator=".." call-id=".."/>;
acks for terminate, transport and mute_v2 are empty [WASM caller log].
The reference waits up to 15 s per ack and only parses the offer ack.
2.7 What we must ack
Incoming <call from="<device jid>" id=".." t=".."> stanzas and call
<receipt>s are acked with <ack id="<their id>" to="<their from>" class="call|receipt" [type] [participant]>.
Both Baileys and whatsmeow do this in their stanza handlers, so a library on top
of whatsmeow gets it for free. Peer devices also send a <receipt> for the offer.
2.8 Incoming <preaccept>
One per ringing device, each in its own <call from="<device jid>">:
<preaccept call-id="<callid>" call-creator="<self>:<selfDev>@lid">
<audio enc="opus" rate="16000"/>
<capability ver="1">7 bytes</capability>
</preaccept>Meaning: that device is ringing. Reference reaction: mark state "ringing" and
send relaylatency (2.9). First preaccept arrived about 1.0 s after the offer
[trace].
2.9 Outgoing <relaylatency>
Purpose [ref comment]: tells the peer which relays we reach and how fast, so both converge on a common relay. Without it, the reference notes, the receiver never reaches relay-create success.
When:
- on every incoming
preaccept - on every incoming
relaylatencyfrom the peer (the peer sends several) - only if at least one relay transport is open; otherwise skip
Shape: one <call> per open IPv4 relay, to = <peer>@lid, fresh id:
<call to="<peer>@lid" id="<tag>">
<relaylatency call-id="<callid>" call-creator="<self>:<selfDev>@lid">
<te latency="<decimal>" relay_name="<relay_name>">6 bytes: IPv4 + BE16 port</te>
<destination> (only in the very first relaylatency stanza of the call)
<to jid="<peer>@lid"/>
<to jid="<peer>:6@lid"/>
...
</destination>
</relaylatency>
</call>latency=0x02000000 | clamp(round(rttMs), 1, 65535)written in decimal (for 30 ms:33554462).rttMsis the ICE round trip time of that relay's transport; 30 when unknown. The meaning of the0x02high byte is unknown.- The port in the 6-byte body is the relay's port from the ack (3480 or 3478), not a remapped local port.
destinationlists the same device JIDs as the offer, with no<enc>.
2.10 Incoming <accept>
<call from="<accepting device jid>" ...>
<accept call-id="<callid>" call-creator="<self>:<selfDev>@lid">
<audio enc="opus" rate="16000"/>
<net medium="2"/>
<encopt keygen="2"/>
</accept>
</call>Observed [trace]: no <relay>, no <raw_e2e>, no <device>. The
accepting device is the envelope's from (bare <peer>@lid means device 0).
Reference reaction: state "active", remember from as the active device, then
ignore later terminate/reject from any other device. If an accept ever
carries <relay>, the reference re-targets uplink media to its first IPv4
endpoint; if it carries <raw_e2e> (base64, at least 32 bytes) it would key
from that instead of the call key. Neither happened.
Downlink media from the phone arrived about 0.3 s before the accept stanza [trace].
2.11 Outgoing <mute_v2>
Sent once, right after the accept:
<call to="<peer>@lid" id="<tag>">
<mute_v2 call-id="<callid>" call-creator="<self>:<selfDev>@lid" mute-state="0"/>
</call>mute-state="0" = unmuted. The phone sends its own mute_v2 too.
2.12 <terminate> and <reject>
Outgoing, when we hang up (only if the peer has not already ended the call):
<call to="<peer>@lid" id="<tag>">
<terminate call-id="<callid>" call-creator="<self>:<selfDev>@lid" reason="accepted"/>
</call>reason="accepted" is what the reference sends for a normal hang-up after an
answered call; other reason values were not exercised. Incoming terminate or
reject (reason may be accepted_elsewhere, rejected_elsewhere, or other
strings) ends the call, except that after an accept they are ignored unless
they come from the accepting device. If no accept arrives within 60 s
(CALL_ACCEPT_WAIT_MS), the reference gives up and sends terminate.
2.13 Addressing summary
| Stanza | Direction | Envelope to | Notes |
|---|---|---|---|
offer | out | <peer>@lid | ack carries <relay> |
relaylatency | out | <peer>@lid | one stanza per open relay |
mute_v2 | out | <peer>@lid | after accept |
terminate | out | <peer>@lid | at hang-up |
preaccept, relaylatency, accept, mute_v2, terminate, reject | in | from a device JID | ack each |
Inside stanzas, call-creator is always our device-qualified LID.
3. Relay control (STUN)
3.1 Framing
Standard RFC 5389 framing: 20-byte header (type BE16, length BE16 = bytes
after the header, magic cookie 0x2112A442, 12-byte transaction ID), then TLV
attributes (type BE16, length BE16 = unpadded value length, value, zero
padding to a 4-byte boundary).
MESSAGE-INTEGRITY (0x0008, 20 bytes) [trace, verified on allocate, allocate
success, binding request and binding success]:
key = the <key> text as ASCII bytes (24 bytes), not base64-decoded
input = header with length already counting the MI attribute (+24)
|| every attribute before MI
MI = HMAC-SHA1(key, input)MI is the last attribute. No FINGERPRINT attribute is used.
3.2 Message and attribute types
| Message type | Name | Direction | MI |
|---|---|---|---|
0x0003 | private allocate request | client to relay | yes |
0x0103 | allocate success | relay to client | yes |
0x0113 | allocate error | relay to client | |
0x0001 | binding request | relay to client | yes |
0x0101 | binding success | client to relay (the relay also echoed it back twice) | yes |
0x0801 | keepalive indication | client to relay | no |
0x0802 | keepalive response | relay to client | no |
0x0804 | relay ping request | client to relay (defined, never sent) | yes |
0x0805 | relay ping response | relay to client |
| Attribute | Name | Value |
|---|---|---|
0x0008 | MESSAGE-INTEGRITY | 20 bytes |
0x0009 | ERROR-CODE | RFC 5389: 2 zero bytes, class (low 3 bits), number, UTF-8 reason |
0x0016 | CONNECTION-ID | 8 bytes |
0x0020 | XOR-MAPPED-ADDRESS | RFC 5389 |
0x4000 | RELAY-TOKEN | raw token bytes |
0x4002 | RELAY-TIMESTAMP | 8 bytes (seen in allocate success; not interpreted) |
0x4003, 0x4004 | RELAY-PACKET-TYPE, RELAY-PAYLOAD | defined, unused |
0x4007 | RELAY-PING-TIMEOUT | BE16 milliseconds |
0x4024 | STREAM-SUBSCRIPTION | protobuf, 3.4 |
3.3 Private allocate request (0x0003)
Attributes in this exact order:
| Offset | Bytes | Field |
|---|---|---|
| 0 | 00 03 | type |
| 2 | BE16 | length (336 in the trace) |
| 4 | 21 12 a4 42 | magic cookie |
| 8 | 12 random bytes | transaction ID, new per attempt |
| 20 | 40 00 LL LL | RELAY-TOKEN, length = token length (193 in the trace) |
| 24 | token bytes + zero pad to 4 | |
| next | 40 24 LL LL + blob + pad | STREAM-SUBSCRIPTION (96 bytes for 9 entries in the trace). Omitted entirely if the plan is empty. |
| next | 00 16 00 08 + 8 bytes | CONNECTION-ID |
| next | 00 08 00 14 + 20 bytes | MESSAGE-INTEGRITY |
Trace example [trace]: total 356 bytes = 20 header + (4 + 196) token +
(4 + 96) subscription + (4 + 8) connection ID + (4 + 20) MI; header length
0x0150 = 336.
3.4 Stream subscription protobuf
The value is a concatenation of entries. Each entry is field 1, wire type 2
(tag byte 0x0A), whose payload is:
| Field | Number | Wire type | Written when |
|---|---|---|---|
| participant index | 1 (tag 0x08) | varint | value != 0 |
| stream index | 2 (tag 0x10) | varint | value != 0 |
| SSRC | 3 (tag 0x18) | varint (uint32) | always |
Nine entries in plan order (section 0). Example structure from the trace, SSRC varints elided:
0a 06 18 <5-byte varint> (0,0)
0a 08 10 01 18 <5-byte varint> (0,1)
0a 08 10 02 18 <5-byte varint> (0,2)
0a 08 08 01 18 <5-byte varint> (1,0)
0a 0a 08 01 10 01 18 <5-byte varint> (1,1)
...All nine SSRCs come from our own LID (the plan subscribes our slots, not the peer's) [trace].
3.5 CONNECTION-ID
If the relay block has an 8-byte conn_id, use it. Otherwise (the observed
case) derive it from the endpoint's IPv4 address and port as an XOR-mapped
address:
conn_id = 00 01 || BE16(port XOR 0x2112) || BE32(ipv4 XOR 0x2112A442)Example for 192.0.2.10:3480: 00 01 2c 8a e1 12 a6 48. The trace allocate
carried exactly this form for its relay [trace]. The port is the relay's
port from the ack, not a transport remap. The reference also accepts conn_id
text as 16 hex chars, a decimal uint64, or base64 of 8 bytes. For non-IPv4 it
falls back to 00 01 2c 84 || SHA-256("ip:port")[0:4].
A mismatch is reported by the relay as 0x0113 with ERROR-CODE 452 "Xor Relayed
Address Mismatch" [ref comment].
3.6 Relay responses
Allocate success 0x0103 [trace], 68 bytes:
01 03 00 30 21 12 a4 42 <txid of our allocate>
00 20 00 08 00 01 <xport> <xaddr> XOR-MAPPED-ADDRESS: our public address
40 02 00 08 <8 bytes> RELAY-TIMESTAMP
00 08 00 14 <20 bytes> MESSAGE-INTEGRITY (verifies with the relay key)If it carries a CONNECTION-ID, adopt it for later messages. Matching on
transaction ID is not required; any 0x0103 counts.
Allocate error 0x0113: read ERROR-CODE, close this relay, fail media over
(3.10).
Binding request 0x0001 from the relay, 44 bytes: header + MI only. Reply
immediately with binding success 0x0101: same transaction ID, MI as the
only attribute (44 bytes total). No XOR-MAPPED-ADDRESS in our reply [trace].
In the trace the relay sent one binding request about 240 ms after allocate
success and then echoed our 0x0101 back twice; incoming 0x0101 is harmless.
Keepalive response 0x0802: 20 bytes, same transaction ID as the keepalive.
3.7 Keepalive indication 0x0801
20 bytes, header only, no attributes, no MI:
08 01 00 00 21 12 a4 42 <12 random bytes>The relay answers 08 02 00 00 21 12 a4 42 <same 12 bytes> within about 20 ms
[trace]. Sent once at the moment the relay becomes ready, then every
1100 ms (CALL_RELAY_KEEPALIVE_INTERVAL_MS, minimum 250).
3.8 Relay ping 0x0804 (defined, not used)
Attributes: RELAY-PING-TIMEOUT 0x4007 (BE16 ms, default 0x01F4 = 500, padded),
CONNECTION-ID, MI. The reference builds it but never schedules it, so a real
call works without it.
3.9 Per-relay state machine
One controller per IPv4 endpoint (IPv6 endpoints are skipped by default).
creating:
on start: send allocate; repeat every 500 ms (CALL_RELAY_ALLOCATE_RETRY_MS, min 250),
no attempt limit, new transaction ID each time
on 0x0103: -> allocated -> bound -> ready (same instant)
on 0x0001: reply 0x0101, then -> bound -> ready
on 0x0101: -> bound -> ready
on 0x0113: -> closed, emit allocate_error
ready (entered once):
stop allocate retries
send keepalive now, then every 1100 ms
emit "ready" exactly once
keep answering 0x0001 with 0x0101
any state:
close() stops all timers -> closedThere is no timeout on creating and no detection of a dead relay apart from
the transport's ICE restart (4.4). In the trace the ISP relay went ready 1.06 s
after the first allocate; the two edge relays received 67 allocates each and
never answered (see 4.6).
3.10 Which relay carries media
- The relay list order from the ack is kept. Endpoint index 0 (lowest
c2r_rtt) is the primary. - Media starts on the first relay that becomes ready. If that is not the primary, media later moves to the primary as soon as the primary becomes ready.
- On
0x0113from any relay while media runs, media moves to any other relay inreadyorbound. - Media is sent to exactly one relay at a time.
4. Relay transport
Every packet (STUN, RTP, RTCP) for relay ip:port goes through one transport
per relay address. The reference uses WebRTC DataChannels by default; raw UDP is
the alternative.
4.1 Which addresses get a transport
From the relay list: every endpoint with protocol UDP (attribute absent, udp
or 0) whose relay has a valid token_id. IPv6 is disabled by default
(CALL_DISABLE_IPV6). Each IPv4 address gets one peer connection.
4.2 WebRTC DataChannel
Per relay address:
- Create a peer connection with default configuration (no ICE servers).
- Create a DataChannel: label
pre-negotiated,negotiated: true,id: 0,ordered: false,maxRetransmits: 0,priority: high, binary messages. Because it is pre-negotiated, no DCEP open message is exchanged. - Create an offer and set it as local description unchanged.
- Build the remote answer by copying the local offer SDP and editing it:
| Edit | Result |
|---|---|
a=setup:actpass | a=setup:passive (relay is the DTLS server, we are the DTLS client). a=setup:active only if enable_edgeray_dtls_active_mode, which nothing in the stanza sets. |
a=ice-ufrag: | base64 (standard alphabet, with = padding) of the endpoint's auth token bytes; if the relay has no auth token, base64 of its relay token |
a=ice-pwd: | the relay key text (24 chars, includes ==) |
a=fingerprint: | sha-256 F9:CA:0C:98:A3:CC:71:D6:42:CE:5A:E2:53:D2:15:20:D3:1B:BA:D8:57:A4:F0:AF:BE:0B:FB:F3:6B:0C:A0:68 (fixed for all relays) |
a=ice-options: lines | removed |
a=max-message-size: | 1200 |
all a=candidate: and a=end-of-candidates | removed, then append a=candidate:2 1 udp 2122262783 <relay ip> <connect port> typ host generation 0 network-cost 5 and a=end-of-candidates |
Everything else (mid, BUNDLE group, m=application ... UDP/DTLS/SCTP webrtc-datachannel,
a=sctp-port) is copied from our own offer, so both sides use the same SCTP
port (5000 in libwebrtc).
- Set that as the remote description. ICE then runs our checks against the single host candidate (standard ICE, so STUN USERNAME
<auth token b64>:<our ufrag>and integrity keyed with the relay key text, [inferred]), DTLS handshakes with us as client, SCTP associates, and the DataChannel opens.
Go/pion notes [inferred]: the ufrag is 96 characters and both ufrag and
pwd contain +, / and =; check that the ICE agent accepts them. The relay
certificate must be pinned to the fingerprint above. Our own certificate can be
any self-signed one; the relay has no way to know its fingerprint.
Port mapping
original mode (reference default) | web mode (our working test) | |
|---|---|---|
| ICE candidate port, IPv4 | the endpoint's port from the ack | always 3480 |
| Special case | IP 157.240.24.133 uses 3478 in both modes | same |
| Port reported upward for received packets | the endpoint's port | 3480 if the endpoint port was 3480, else 3478 (so the same as the ack port for the two values seen) |
Port in CONNECTION-ID and relaylatency | the endpoint's port | the endpoint's port |
The engine always addresses relays by the ack's ip:port; the transport maps
that to its connection (it tries ip:port, then ip:3480, then ip:3478).
4.3 Framing
One DataChannel message carries exactly one STUN, RTP or RTCP packet, unchanged. No length prefix, no extra header. Messages are unordered and never retransmitted, so the channel behaves like UDP. Keep packets under 1200 bytes.
Inbound demultiplexing by first bytes:
| Test | Kind |
|---|---|
| length >= 20, top 2 bits of byte 0 are 0, bytes 4..7 are the magic cookie | STUN |
byte 0 in 20..25, byte 1 0xFE, byte 2 0xFD or 0xFF | DTLS (not expected inside the channel) |
| version 2 and byte 1 in 192..223 | RTCP |
version 2 and byte1 & 0x7F < 64 or >= 96 | RTP |
4.4 Buffering, timeouts, ICE restart, RTT
- Packets sent before the channel opens are queued (cap 256 KiB, oldest dropped) and flushed in order on open. The trace shows the first three allocates queued this way, each answered by
0x0103. - A connection still not open after 20 s is marked failed and its peer objects closed.
- ICE restart: if an allocate (
0x0003) is about to be sent on an open connection that has already carried non-STUN packets and has received nothing for over 10 s, the transport tears down the peer connection, builds a fresh one the same way (reusing the first local candidate it gathered before), and sends the allocate after it opens. Skipped if no non-STUN packet was ever sent. - Every 1 s while open it reads the selected ICE candidate pair's current round trip time (falling back to total RTT / responses) and keeps it, rounded to ms, for
relaylatency.
4.5 Raw UDP alternative
Send each packet as one UDP datagram to the ack's ip:port and feed each
received datagram to the same demultiplexer. The reference documents this as
"testing only"; the transport's own comment says the relay only accepts DTLS
tunneled traffic from web clients. Not verified either way by us.
4.6 What the real call showed
With web mode, the ISP relay (port 3480, is_fna="1") opened and carried the
whole call. The two edge relays (ack port 3478, so connected on 3480 in web
mode) never answered any allocate. Whether they would work in original mode
on 3478 was not tested.
5. Media
5.1 RTP header (uplink)
| Field | Value |
|---|---|
| V, P, X, CC | 2, 0, 1, 0 (byte 0 = 0x90) |
| M | 0 on every packet [trace] |
| PT | 120 (byte 1 = 0x78) |
| Sequence number | starts at 1, +1 per packet, wraps to 0 and increments ROC |
| Timestamp | starts at a random value in 0..0x7FFF, +2880 per packet |
| Clock | 48 kHz RTP clock (2880 = 60 ms), while the codec runs at 16 kHz |
| SSRC | our slot-0 participant SSRC |
Trace example: 90 78 00 01 00 00 14 a5 <ssrc> de be 00 00 <ciphertext> <4-byte MI>,
then sequence 2 with timestamp +2880, and so on.
5.2 WARP header extension
Profile 0xDEBE, written right after the 12-byte header:
| Form | Bytes | When |
|---|---|---|
| empty | de be 00 00 | reference: every packet (piggyback disabled by default, CALL_AUDIO_PIGGYBACK=0) |
| audio piggyback | de be 00 01 30 01 00 00 (one RFC 8285 one-byte element, id 3, len 1, value 0, padded) | native client: from the 3rd packet on |
The native phone used debe0000 for its first two packets and the piggyback
form after that [trace]. The reference keeps the empty form because its
author saw the receiver stop playing with piggyback on [ref comment]. Our
uplink in the trace was 526 of 526 packets with the empty form, and the phone
played it.
5.3 Payload
One codec frame per packet: 60 ms, 16 kHz mono MLow (Meta's Opus-derived codec,
Opus TOC convention, TOC 0x50 on most frames), target 25 kbit/s. Payload sizes
in the trace ranged from about 10 to 210 bytes. The phone's frames were mostly
TOC 0x90 and 0x00, often only 1 to 5 bytes (silence). Whether plain Opus is
accepted is untested.
5.4 Protection
Encrypt the payload (everything after the extension) with AES-128-CTR using the uplink session keys and IV from section 0, then append the 4-byte WARP MI tag computed over header, extension and ciphertext plus ROC. Packet length = 12 + 4 (+4 with piggyback) + payload + 4.
5.5 Pacing
- Prebuffer 1 frame, then send one packet every 60 ms on an absolute schedule:
next += 60 ms; sleep(max(0, next - now)). This avoids drift; bursty delivery makes the phone play too fast or slow [ref comment]. - If no frame is ready at a tick, nothing is sent and the timestamp does not advance (the reference never hits this because it pre-encodes the clip).
- Uplink media starts as soon as a relay is ready, before the accept. In the trace the first RTP left 4.2 s before the accept and the phone's receiver report later showed no loss.
5.6 RTCP
All are compound-free single packets, each protected individually.
Cleartext layouts the reference sends:
| Packet | Bytes | Layout |
|---|---|---|
| SDES (PT 202) | 32 | 81 ca 00 07 <ssrc> 01 <len> <CNAME ASCII> 00 + zero pad to 4. Reference CNAME: node-load-<ssrc as 8 lowercase hex> (18 chars, len byte 0x12). Any CNAME should do. |
| TFB, transport feedback (PT 208) | 12 | 81 d0 00 02 <ssrc> BE32 rtpIndex where rtpIndex = (ROC << 16) | next sequence number (the number the next RTP will use) |
| Stream hello (PT 209) | 8 | 81 d1 00 01 <ssrc> |
| AFB, application feedback (PT 206, FMT 15) | 20 | 8f ce 00 04 <ssrc> <ssrc> 00 x 8 |
| SR (PT 200) | 28 | standard sender report; the reference never sends it on the MLow path |
Cadence, counting RTP packets sent (n = 1 for the first):
| When | Packet |
|---|---|
| immediately before RTP #1 | SDES |
| right after RTP #1 | TFB (value 2) |
| right after RTP #4 | stream hello, once |
| right after every RTP where n % 8 == 0 | TFB |
| right after every RTP where n % 25 == 0 | AFB |
Trace sequence [trace]: SDES, RTP 1, TFB(2), RTP 2..4, hello, RTP 5..8, TFB(9), ... AFB after RTP 25, 50, ...
Reference uplink SRTCP (what was on the wire in the working call):
encrypted = header[0:8] || AES-128-CTR(uplink cipher key (label 0),
IV(uplink salt (label 2), ssrc, index), bytes[8:])
trailer = BE32(0x80000000 | index) E flag set, index from 0, one counter
shared by every RTCP packet type
tag = HMAC-SHA1(uplink auth key (label 1), encrypted || trailer)[0:4]
wire = encrypted || trailer || tagSo TFB is 20 bytes on the wire, hello 16, AFB 28, SDES 40. Verified: all uplink RTCP tags in the trace recompute with the label-1 key [trace].
Native peer SRTCP (what the phone sent us) is standard RFC 3711 [trace, 4 of 4 packets verified]:
- session keys from the same 46-byte master, but PRF labels 0x03 (16-byte cipher key), 0x04 (20-byte auth key), 0x05 (14-byte salt)
- tag 10 bytes (HMAC-SHA1-80) over
header || ciphertext || E|index - E flag set, index starts at 1
- packets seen: SDES (46 bytes on the wire), TFB 208 (26), SR 200 (122, with a report block about our SSRC), AFB 206 (34)
This means the reference's uplink RTCP probably fails the phone's SRTCP authentication. Audio still worked, so RTCP from us is either ignored or only used by the relay. Implementing the native form (labels 3/4/5, 10-byte tag) is the safer choice for anything the phone must read, but it was not tested on the uplink.
5.7 Sent before media
In order: allocate(s), keepalive at ready, binding success when the relay asks, then SDES, then RTP #1. Nothing else is required before RTP.
5.8 Receive path
- Demultiplex (4.3). STUN goes to the controller whose
ip:portmatches, else to the first controller. - RTP: estimate ROC per SSRC (RFC 3711 rule: if the highest seen sequence is below
0x8000and the new one is more than0x8000above it, use ROC-1; if the highest is at least0x8000and the new one is more than0x8000below it, use ROC+1; commit when the extended index is higher). - Decrypt with the downlink keys (section 6). The reference does not verify the RTP MI tag on receive.
- Accept SSRCs in the peer's slots 0..3 (peer device-qualified LID).
- The phone's RTP uses PT 120, sets the marker bit at talk-spurt starts (byte 1
0xF8), and uses the piggyback extension after packet 2.
6. Downlink keys and keygen="2"
Finding [trace]: the downlink uses exactly the same derivation as the
uplink, with the call key we generated as IKM and the answering device's
device-qualified LID with an explicit :0 as HKDF info:
master = HKDF-SHA256(callKey, zero salt, "<peer>:0@lid", 46)
RTP : labels 0/1/2 (cipher key, MI auth key, salt)
SRTCP : labels 3/4/5, 10-byte tagEvidence:
- SRTCP: all four phone RTCP packets checked verify their 10-byte tag with the label-4 key from
<peer>:0@lid, and decrypt to valid SDES/TFB/SR content (the SR's report block names our uplink SSRC). - RTP: after reconstructing the wire ciphertext (see below) and decrypting with labels 0/2 from
<peer>:0@lid, 116 packets give a consistent TOC distribution (0x9067 times,0x0043 times). Every other candidate (bare LID, other device numbers, PN JID, swapped key halves, HBH keys fromhbh_key) gives uniformly random first bytes. - The phone's SSRC is slot 0 of
<peer>:0@lid, which you already confirmed.
Why your MI check failed: the trace never stored the downlink wire bytes.
For received RTP, the relay_packet record's hex_full is the reference's
output after it decrypted with the wrong keys and after it stripped the
4-byte MI tag. The reference derived downlink keys from the first device in its
list, the bare <peer>@lid, and its relock search never tries :0, so it
never switched. downlinkWire in testdata/private/real-call-1.json is that
cleartext (it is byte-identical to downlinkClear), so no MI check against it
can pass. To recover the true ciphertext from this trace: re-encrypt each
record with the bare-LID keys (logged in the voip_node_e2e_srtp_active
marker as downlinkCipherKeyHex/downlinkSaltHex). The MI tag itself is gone
and cannot be recovered.
What keygen="2" means [inferred, consistent with all of the above]: both
directions are keyed from the offerer's call key, each sender using its own
device-qualified LID as HKDF info; no raw_e2e is exchanged. The reference has
a second path where an <accept> with <raw_e2e> replaces the call key as IKM
(first 32 bytes, same HKDF and PRF); that path was not exercised.
Downlink RTP MI tag: not verified, because the trace lost it. The phone's
packets leave room for exactly a 4-byte trailer (25-byte packets with a 20-byte
header and 1-byte payload), so the uplink formula (label-1 key of
<peer>:0@lid, 4 bytes, ROC appended) is the expected one. Test it on a fresh
capture that logs raw inbound bytes.
Implementation rule: map a bare device JID to :0 before deriving keys or
SSRCs, and pick the downlink LID from the accepting device (from of the
<call> carrying <accept>), or match the first inbound SSRC against slots
0..3 of every candidate device LID including :0.
7. Caller timeline
Times are from the real call (t = 0 at startCall) [trace].
| t (s) | Step | Waits on |
|---|---|---|
| before 0 | resolve peer LID, fetch devices, ensure Signal sessions | session |
| 0.000 | generate call ID and key, derive uplink keys, SSRC, stream plan | |
| ~0.0 | send <offer> (2.3) | sessions |
| 0.520 | offer ack arrives with <relay>; create controllers, start allocate retries (queued in the transport), open one DataChannel per IPv4 relay | offer ack |
| 1.040 | first preaccept; send relaylatency if a relay transport is open | |
| 1.583 | primary relay 0x0103; relay ready; first keepalive | DataChannel open + allocate success |
| 1.602 | keepalive response | |
| 1.809 | media pipeline starts: SDES, RTP #1, TFB | relay ready |
| 1.824 | relay binding request, our binding success | |
| 2.0 to 6.0 | more preaccept and relaylatency from other devices; we answer each relaylatency with ours; keepalive every 1.1 s; RTP every 60 ms with TFB/hello/AFB | |
| 5.730 | first downlink RTCP, then RTP from the phone | phone answering |
| 6.033 | <accept>; lock the active device; send mute_v2 | user answers |
| 6.3 | ack for mute_v2 | |
| ... | media both ways | |
| end | send <terminate> (unless the peer ended), stop pipeline, close controllers and transports | playback done or peer terminate |
8. Minimum viable caller
Goal: the phone rings, the user answers and hears our clip.
Required:
- Peer LID, device list, Signal sessions for every device.
- Offer exactly as in 2.3, including
privacy, bothaudio,net,capability,destinationwith one<enc>per device,encopt keygen="2", anddevice-identitywhen any<enc>ispkmsg. - Parse the offer ack's
<relay>: tokens, auth tokens, key text, endpoints. - One DataChannel transport to the primary IPv4 relay (web mode as tested), allocate with token, 9-entry subscription, CONNECTION-ID and MI; retry every 500 ms until
0x0103. - Answer relay binding requests with
0x0101+ MI. - Keepalive
0x0801every 1.1 s. relaylatencyon preaccept (and in reply to the peer's), at least for the relay we use.- RTP: PT 120, seq from 1, timestamp +2880,
debe0000extension, AES-CTR payload, 4-byte MI; paced at 60 ms. terminatewhen done.
Probably required, cheap, and sent by the working reference (not proven necessary): SDES before the first RTP, TFB after RTP #1 and every 8th, stream hello after RTP #4, AFB every 25th.
Nice to have:
mute_v2 mute-state="0"after accept- downlink decryption (section 6) and SRTCP receive
- several relays, failover on
0x0113, re-targeting to the primary - ICE restart after 10 s of silence
- piggyback extension (native behavior, but see 5.2)
- native-style uplink SRTCP (labels 3/4/5, 10-byte tag)
- relay ping, SR packets, IPv6
9. Unknown or unverified
- Meaning of
net mediumvalues, thecapabilitybits, the0x02high byte oflatency,attribute_padding, and the 8-byte RELAY-TIMESTAMP. - Whether
privacymust be the peer's real tctoken. A foreign constant worked in our call; it may matter when the peer restricts who can call. - The correct
reasonfor a caller hang-up; the reference sendsacceptedand that was not checked against a native client. - The downlink RTP MI tag key (expected: label-1 key of
<peer>:0@lid), because the trace dropped the tag. - Whether the phone or relay needs our RTCP at all, and whether our label-0/1/2 SRTCP with 4-byte tags is accepted by anyone.
- Why the edge relays (port 3478) never answered in web mode, and whether
originalmode or raw UDP would reach them. - Whether plain Opus frames play on the phone instead of MLow.
- Whether media must start before the accept (the reference does; nothing tested the opposite).