# Message Protocol

KayakNet uses a custom binary protocol for efficient P2P communication.

## Message Format

```
┌────────────────────────────────────────────────┐
│ Magic Number (4 bytes): 0x4B594B4E ("KYKN")    │
├────────────────────────────────────────────────┤
│ Version (1 byte)                               │
├────────────────────────────────────────────────┤
│ Message Type (1 byte)                          │
├────────────────────────────────────────────────┤
│ Flags (2 bytes)                                │
├────────────────────────────────────────────────┤
│ Sequence Number (4 bytes)                      │
├────────────────────────────────────────────────┤
│ Payload Length (4 bytes)                       │
├────────────────────────────────────────────────┤
│ Payload (variable)                             │
├────────────────────────────────────────────────┤
│ MAC (16 bytes) - Poly1305                      │
└────────────────────────────────────────────────┘
```

## Message Types

| Type              | Value | Description         |
| ----------------- | ----- | ------------------- |
| PING              | 0x01  | Keepalive           |
| PONG              | 0x02  | Ping response       |
| HANDSHAKE         | 0x10  | Initial connection  |
| DHT\_FIND\_NODE   | 0x20  | DHT query           |
| DHT\_FIND\_VALUE  | 0x21  | DHT value lookup    |
| DHT\_STORE        | 0x22  | DHT store           |
| PUBSUB\_SUBSCRIBE | 0x30  | Subscribe to topic  |
| PUBSUB\_PUBLISH   | 0x31  | Publish message     |
| CHAT\_MESSAGE     | 0x40  | Chat room message   |
| CHAT\_DM          | 0x41  | Direct message      |
| MARKET\_LISTING   | 0x50  | Marketplace listing |
| ESCROW\_CREATE    | 0x60  | Create escrow       |
| DOMAIN\_REGISTER  | 0x70  | Register domain     |
| ONION\_DATA       | 0x80  | Onion-routed data   |

## Handshake Protocol

```
Client                          Server
   │                               │
   │─────── HANDSHAKE_INIT ───────▶│
   │   (version, public_key)       │
   │                               │
   │◀────── HANDSHAKE_RESP ────────│
   │   (version, public_key,       │
   │    pow_challenge)             │
   │                               │
   │─────── HANDSHAKE_POW ────────▶│
   │   (pow_solution)              │
   │                               │
   │◀────── HANDSHAKE_OK ──────────│
   │   (session established)       │
   │                               │
```

## Flags

| Bit  | Name       | Description            |
| ---- | ---------- | ---------------------- |
| 0    | ENCRYPTED  | Payload is encrypted   |
| 1    | COMPRESSED | Payload is compressed  |
| 2    | URGENT     | High priority          |
| 3    | FRAGMENT   | Part of larger message |
| 4-15 | Reserved   | For future use         |

## Encoding

### Numbers

* Big-endian byte order
* Unsigned integers

### Strings

* UTF-8 encoded
* Length-prefixed (2 bytes)

### Binary Data

* Length-prefixed (4 bytes)
* Raw bytes

### Lists

* Count-prefixed (2 bytes)
* Elements follow

## Payload Structures

### PING/PONG

```
Timestamp (8 bytes, Unix milliseconds)
```

### DHT\_FIND\_NODE

```
Target ID (32 bytes)
```

### DHT\_FIND\_NODE Response

```
Node Count (2 bytes)
For each node:
  Node ID (32 bytes)
  Address Length (2 bytes)
  Address (variable)
```

### CHAT\_MESSAGE

```
Room Name Length (2 bytes)
Room Name (variable)
Sender ID (32 bytes)
Sender Name Length (2 bytes)
Sender Name (variable)
Content Length (4 bytes)
Content (variable, encrypted)
Timestamp (8 bytes)
Signature (64 bytes)
```

## Compression

Large payloads (>1KB) may be compressed:

* Algorithm: LZ4
* Flag bit 1 set
* Decompress after decryption

## Fragmentation

Messages >64KB are fragmented:

* Flag bit 3 set
* Fragment header:

  ```
  Message ID (16 bytes)
  Fragment Index (2 bytes)
  Total Fragments (2 bytes)
  ```

## Error Handling

### Error Response

```
┌────────────────────────────────────────────────┐
│ Type: ERROR (0xFF)                             │
├────────────────────────────────────────────────┤
│ Error Code (2 bytes)                           │
├────────────────────────────────────────────────┤
│ Message Length (2 bytes)                       │
├────────────────────────────────────────────────┤
│ Message (variable)                             │
└────────────────────────────────────────────────┘
```

### Error Codes

| Code   | Description           |
| ------ | --------------------- |
| 0x0001 | Unknown message type  |
| 0x0002 | Invalid format        |
| 0x0003 | Authentication failed |
| 0x0004 | Rate limited          |
| 0x0005 | Not found             |
| 0x0006 | Timeout               |

## Security

### Authentication

* Every message has MAC
* Computed with session key
* Invalid MAC = drop message

### Replay Protection

* Sequence numbers are tracked
* Duplicates rejected
* Window of 1000 messages

### Nonce Management

* ChaCha20 uses 12-byte nonce
* Counter + random component
* Never reused per key
