# What is KayakNet?

Welcome to the official documentation for **KayakNet** - a privacy-first, decentralized peer-to-peer network.

## What is KayakNet?

KayakNet is a censorship-resistant, anonymous network that enables:

* **Private Communication** - End-to-end encrypted chat with perfect forward secrecy
* **Anonymous Marketplace** - Buy and sell with cryptocurrency escrow (Monero/Zcash)
* **Decentralized Domains** - Register `.kyk` domains on the network
* **No Central Authority** - Fully peer-to-peer, no servers to shut down

## Quick Links

* [Getting Started](/getting-started/getting-started)
* [Installation Guide](/getting-started/installation)
* [Architecture Overview](/architecture/architecture)
* [Security Model](/security/security)
* [Marketplace Guide](/features/marketplace)
* [API Reference](/api-reference/api)
* [Roadmap](/appendix/roadmap)

## Key Features

| Feature                     | Description                       |
| --------------------------- | --------------------------------- |
| Onion Routing               | 3-hop encrypted routing like Tor  |
| E2E Encryption              | All messages encrypted end-to-end |
| Traffic Analysis Resistance | Padding, mixing, dummy traffic    |
| Crypto Escrow               | Monero & Zcash support            |
| .kyk Domains                | Decentralized naming system       |
| Cross-Platform              | Windows, Linux, macOS, Android    |

## License

KayakNet is open source software released under the MIT License.


# Why KayakNet?

## The Problem

In today's digital world, privacy is increasingly under threat:

* **Surveillance** - Governments and corporations monitor online activity
* **Censorship** - Content is blocked based on geography or politics
* **Data Harvesting** - Personal information is collected and sold
* **Single Points of Failure** - Centralized services can be shut down

Traditional solutions like VPNs only shift trust to another party. Tor provides anonymity but has usability issues and doesn't include built-in services.

## The Solution

KayakNet provides a complete anonymous ecosystem:

### 1. True Decentralization

* No central servers to shut down
* Every node is equal
* Network survives even if most nodes go offline

### 2. Built-in Anonymity

* All traffic routed through 3 hops (like Tor)
* End-to-end encryption on everything
* Traffic analysis resistance included

### 3. Integrated Services

* Chat that's private by default
* Marketplace with cryptocurrency escrow
* Domain system without ICANN

### 4. Easy to Use

* Single binary to run
* Browser proxy for easy access
* No technical knowledge required

## Comparison

| Feature                     | KayakNet | Tor | I2P | VPN |
| --------------------------- | -------- | --- | --- | --- |
| Decentralized               | ✅        | ✅   | ✅   | ❌   |
| Built-in Chat               | ✅        | ❌   | ❌   | ❌   |
| Marketplace                 | ✅        | ❌   | ❌   | ❌   |
| Crypto Escrow               | ✅        | ❌   | ❌   | ❌   |
| Domain System               | ✅        | ✅   | ✅   | ❌   |
| Traffic Analysis Resistance | ✅        | ⚠️  | ✅   | ❌   |
| Easy Setup                  | ✅        | ⚠️  | ❌   | ✅   |

## Use Cases

### Privacy-Conscious Users

* Communicate without surveillance
* Browse without tracking
* Trade without financial monitoring

### Journalists & Activists

* Protect sources
* Coordinate securely
* Publish censored content

### Developers

* Build decentralized applications
* Create privacy-preserving services
* Experiment with P2P technology

### Businesses

* Secure internal communications
* Private supply chain coordination
* Confidential transactions

## What KayakNet is NOT

KayakNet is designed for legitimate privacy needs. It is **not**:

* A tool for illegal activities
* A way to evade law enforcement
* An illicit marketplace
* A money laundering service

We believe privacy is a fundamental human right, but rights come with responsibilities.


# Core Principles

KayakNet is built on these fundamental principles:

## 1. Privacy by Default

Everything in KayakNet is private by default:

* **No Opt-In Required** - You don't have to enable encryption; it's always on
* **No Metadata Leaks** - Even connection patterns are obscured
* **No Logs** - Nodes don't log user activity
* **No Tracking** - No analytics, no telemetry

## 2. Decentralization

No single point of control or failure:

* **No Central Servers** - Pure peer-to-peer architecture
* **No Company** - No organization can be pressured to compromise users
* **No Single Operator** - Anyone can run a node
* **Censorship Resistant** - No one can block content network-wide

## 3. Security in Depth

Multiple layers of protection:

```
┌─────────────────────────────────────────┐
│         Application Layer E2E          │
├─────────────────────────────────────────┤
│         Onion Routing (3 hops)          │
├─────────────────────────────────────────┤
│        Transport Encryption (TLS)        │
├─────────────────────────────────────────┤
│         Traffic Analysis Resistance      │
└─────────────────────────────────────────┘
```

## 4. Usability

Privacy shouldn't require a PhD:

* **Single Binary** - One download, run and go
* **Browser Proxy** - Use your existing browser
* **Familiar Interface** - Web-based UI
* **Cross-Platform** - Windows, Linux, macOS, Android

## 5. Open Source

Transparency builds trust:

* **Auditable Code** - Anyone can review the code
* **Community Driven** - Contributions welcome
* **No Backdoors** - Verifiable security
* **MIT License** - Use freely

## 6. Cryptocurrency Integration

Native support for private payments:

* **Monero (XMR)** - Untraceable transactions
* **Zcash (ZEC)** - Shielded addresses
* **Escrow System** - Trustless marketplace
* **No Middlemen** - Direct peer-to-peer payments

## 7. Resilience

Built to survive:

* **Sybil Resistance** - Proof-of-Work for new nodes
* **Eclipse Attack Protection** - Diverse peer connections
* **Self-Healing** - Network adapts to node failures
* **Persistent Data** - Replicated across DHT

## Design Philosophy

### Do One Thing Well

Each component has a single responsibility:

* DHT handles peer discovery
* Onion router handles anonymity
* PubSub handles messaging
* Escrow handles payments

### Fail Safely

When something goes wrong:

* Default to more privacy, not less
* Never expose user data
* Graceful degradation

### Trust No One

Every component assumes:

* The network is compromised
* Peers are malicious
* Traffic is monitored


# Overview

Welcome to KayakNet! This guide will help you get up and running in minutes.

## Overview

KayakNet is a single binary that:

1. Connects you to the P2P network
2. Runs a local proxy for your browser
3. Provides access to all KayakNet services

## Quick Start (5 Minutes)

### Step 1: Download

**Linux:**

```bash
curl -L -o kayakd.zip https://github.com/KayakNet/releases/releases/latest/download/kayakd-linux-amd64.zip
unzip kayakd.zip
chmod +x kayakd
```

**Windows (PowerShell):**

```powershell
curl.exe -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-windows-amd64.zip
Expand-Archive kayakd.zip .
```

**macOS:**

```bash
curl -L -o kayakd.zip https://github.com/KayakNet/releases/releases/latest/download/kayakd-darwin-amd64.zip
unzip kayakd.zip
chmod +x kayakd
```

### Step 2: Run

```bash
./kayakd --bootstrap 203.161.33.237:4242 --proxy --name your-node-name
```

You should see:

```
╔════════════════════════════════════════════════════════════╗
║                  KayakNet Anonymous Network                 ║
╠════════════════════════════════════════════════════════════╣
║  Node ID:  abc123...                                       ║
║  Address:  0.0.0.0:4242                                    ║
║  Name:     your-node-name                                  ║
╠════════════════════════════════════════════════════════════╣
║  [+] Onion routing + traffic analysis resistance           ║
║  [+] Browser proxy: HTTP 8118, SOCKS5 8119                 ║
║  [+] Homepage: http://home.kyk                             ║
╚════════════════════════════════════════════════════════════╝
```

### Step 3: Configure Browser

Set your browser to use the proxy:

* **HTTP Proxy:** `127.0.0.1:8118`
* **SOCKS5 Proxy:** `127.0.0.1:8119`

### Step 4: Browse

Navigate to: **<http://home.kyk>**

You're now on KayakNet! 🎉

## What's Next?

* [Configure your node](/getting-started/configuration)
* [Set up browser properly](/getting-started/browser-setup)
* [Explore the marketplace](/features/marketplace)
* [Start chatting](/features/chat)
* [Register a .kyk domain](/features/domains)

## Need Help?

* Check the [FAQ](/appendix/faq)
* Join the KayakNet chat on `home.kyk`
* Open an issue on GitHub


# Installation

## System Requirements

### Minimum

* **OS:** Windows 10+, Linux (kernel 4.x+), macOS 10.14+
* **RAM:** 512 MB
* **Storage:** 100 MB
* **Network:** Internet connection (any speed)

### Recommended

* **RAM:** 2 GB
* **Storage:** 1 GB (for data persistence)
* **Network:** Stable broadband connection

## Installation Methods

### Method 1: Pre-built Binaries (Recommended)

#### Linux (x64)

```bash
# Download
curl -L -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-linux-amd64.zip

# Extract
unzip kayakd.zip

# Make executable
chmod +x kayakd-v0.1.28-linux-amd64

# Run
./kayakd-v0.1.28-linux-amd64 --bootstrap 203.161.33.237:4242 --proxy
```

#### Windows (x64)

```powershell
# Download
curl.exe -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-windows-amd64.zip

# Extract
Expand-Archive -Force kayakd.zip .

# Run
.\kayakd-v0.1.28-windows-amd64.exe --bootstrap 203.161.33.237:4242 --proxy
```

#### macOS (x64)

```bash
# Download
curl -L -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-darwin-amd64.zip

# Extract
unzip kayakd.zip

# Make executable
chmod +x kayakd-v0.1.28-darwin-amd64

# Allow in Security preferences if blocked
# System Preferences → Security & Privacy → Allow

# Run
./kayakd-v0.1.28-darwin-amd64 --bootstrap 203.161.33.237:4242 --proxy
```

#### Android

1. Download APK from releases
2. Enable "Install from unknown sources"
3. Install and open KayakNet app
4. The app connects automatically

### Method 2: Build from Source

#### Prerequisites

* Go 1.21+
* Git

#### Steps

```bash
# Clone repository
git clone https://github.com/KayakNet/KayakNet.git
cd KayakNet

# Build
go build -o kayakd ./cmd/kayakd/

# Run
./kayakd --bootstrap 203.161.33.237:4242 --proxy
```

### Method 3: Docker

```bash
# Pull image
docker pull kayaknet/kayakd:latest

# Run
docker run -d \
  --name kayaknet \
  -p 4242:4242 \
  -p 8080:8080 \
  -p 8118:8118 \
  -p 8119:8119 \
  -v kayaknet-data:/data \
  kayaknet/kayakd:latest \
  --bootstrap 203.161.33.237:4242 --proxy
```

## Verifying Installation

After starting the node:

1. **Check the console output** - You should see the KayakNet banner
2. **Test the proxy** - `curl --proxy http://127.0.0.1:8118 http://home.kyk`
3. **Check peer count** - Should show 1+ peers after a few seconds

## Running as a Service

### Linux (systemd)

Create `/etc/systemd/system/kayaknet.service`:

```ini
[Unit]
Description=KayakNet Node
After=network.target

[Service]
Type=simple
User=kayaknet
ExecStart=/opt/kayaknet/kayakd --bootstrap 203.161.33.237:4242 --proxy --data-dir /var/lib/kayaknet
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

Enable and start:

```bash
sudo systemctl enable kayaknet
sudo systemctl start kayaknet
```

### Windows (Task Scheduler)

1. Open Task Scheduler
2. Create Basic Task → "KayakNet"
3. Trigger: At startup
4. Action: Start a program → `kayakd.exe`
5. Arguments: `--bootstrap 203.161.33.237:4242 --proxy`

## Troubleshooting

### Port Already in Use

```
Error: bind: address already in use
```

Another process is using port 4242. Either:

* Kill the other process
* Use a different port: `--listen 0.0.0.0:4243`

### Can't Connect to Bootstrap

```
Error: failed to connect to bootstrap
```

* Check your internet connection
* Verify the bootstrap address is correct
* Try a different bootstrap node

### Windows Defender Warning

Windows may flag the executable. This is a false positive for unsigned Go binaries.

* Click "More info" → "Run anyway"
* Or add an exclusion in Windows Security

### Permission Denied (Linux/macOS)

```bash
chmod +x kayakd
```


# Quick Start

Get up and running with KayakNet in under 5 minutes.

## Step 1: Download (30 seconds)

### Linux

```bash
curl -L -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-linux-amd64.zip
unzip kayakd.zip
chmod +x kayakd-v0.1.28-linux-amd64
```

### Windows (PowerShell)

```powershell
curl.exe -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-windows-amd64.zip
Expand-Archive -Force kayakd.zip .
```

### macOS

```bash
curl -L -o kayakd.zip http://203.161.33.237/kayakd-v0.1.28-darwin-amd64.zip
unzip kayakd.zip
chmod +x kayakd-v0.1.28-darwin-amd64
```

## Step 2: Run (10 seconds)

### Linux/macOS

```bash
./kayakd-v0.1.28-linux-amd64 --bootstrap 203.161.33.237:4242 --proxy --name your-name
```

### Windows

```powershell
.\kayakd-v0.1.28-windows-amd64.exe --bootstrap 203.161.33.237:4242 --proxy --name your-name
```

You should see:

```
╔════════════════════════════════════════════════════════════╗
║                  KayakNet Anonymous Network                 ║
╠════════════════════════════════════════════════════════════╣
║  Node ID:  abc123...                                       ║
║  [+] Browser proxy: HTTP 8118, SOCKS5 8119                 ║
║  [+] Homepage: http://home.kyk                             ║
╚════════════════════════════════════════════════════════════╝
```

## Step 3: Configure Browser (2 minutes)

### Firefox (Recommended)

1. Settings → Search "proxy" → Settings...
2. Select "Manual proxy configuration"
3. HTTP Proxy: `127.0.0.1` Port: `8118`
4. Check "Also use this proxy for HTTPS"
5. OK

### Chrome

1. Install "Proxy SwitchyOmega" extension
2. New Profile → HTTP `127.0.0.1:8118`
3. Apply → Select profile

## Step 4: Browse KayakNet (Instant!)

Open your browser and go to:

| URL                 | What It Is  |
| ------------------- | ----------- |
| `http://home.kyk`   | Homepage    |
| `http://chat.kyk`   | Chat        |
| `http://market.kyk` | Marketplace |

## You're Done!

### What's Next?

* **Chat**: Join `#general` on `chat.kyk`
* **Marketplace**: Browse listings on `market.kyk`
* **Domains**: Register your .kyk domain

### Quick Commands

```bash
# Run in background (Linux/macOS)
nohup ./kayakd --bootstrap 203.161.33.237:4242 --proxy &

# Check if running
curl --proxy http://127.0.0.1:8118 http://home.kyk

# Stop the node
pkill kayakd
```

### Troubleshooting

**"Address already in use"**

```bash
# Find and kill existing process
lsof -i :4242
kill <PID>
```

**"Connection refused"**

* Make sure node is running
* Check proxy port is 8118

**Can't see home.kyk**

* Verify proxy settings in browser
* Try refreshing after 30 seconds (first connection takes time)

## Video Tutorial

Coming soon!


# Configuration

## Command Line Options

```bash
kayakd [options]
```

### Core Options

| Option        | Description            | Default        |
| ------------- | ---------------------- | -------------- |
| `--listen`    | Address to listen on   | `0.0.0.0:4242` |
| `--bootstrap` | Bootstrap node address | Required       |
| `--name`      | Node display name      | `anonymous`    |
| `--data-dir`  | Data directory         | `./data`       |
| `--config`    | Config file path       | Auto-detect    |

### Proxy Options

| Option          | Description          | Default |
| --------------- | -------------------- | ------- |
| `--proxy`       | Enable browser proxy | `false` |
| `--http-proxy`  | HTTP proxy port      | `8118`  |
| `--socks-proxy` | SOCKS5 proxy port    | `8119`  |

### Network Options

| Option         | Description              | Default |
| -------------- | ------------------------ | ------- |
| `--public-api` | Expose API publicly      | `false` |
| `--api-port`   | Homepage/API port        | `8080`  |
| `--max-peers`  | Maximum peer connections | `50`    |

### Security Options

| Option             | Description                  | Default |
| ------------------ | ---------------------------- | ------- |
| `--onion-hops`     | Number of onion routing hops | `3`     |
| `--pow-difficulty` | Proof-of-work difficulty     | `20`    |

## Configuration File

Create `config.json` in your data directory:

```json
{
  "node": {
    "name": "my-node",
    "data_dir": "./data",
    "listen_address": "0.0.0.0:4242",
    "identity_file": "./data/identity.key"
  },
  "bootstrap": {
    "nodes": ["203.161.33.237:4242"]
  },
  "proxy": {
    "enabled": true,
    "http_port": 8118,
    "socks_port": 8119
  },
  "security": {
    "onion_hops": 3,
    "pow_difficulty": 20,
    "enable_traffic_analysis_resistance": true
  },
  "dht": {
    "k": 20,
    "alpha": 3,
    "record_ttl": "24h",
    "refresh_interval": "1h"
  },
  "crypto": {
    "monero": {
      "enabled": false,
      "rpc_host": "",
      "rpc_port": 18082
    },
    "zcash": {
      "enabled": false,
      "rpc_host": "",
      "rpc_port": 8232
    }
  },
  "logging": {
    "level": "info",
    "file": "./logs/kayaknet.log"
  }
}
```

## Environment Variables

| Variable             | Description                           |
| -------------------- | ------------------------------------- |
| `KAYAKNET_DATA_DIR`  | Override data directory               |
| `KAYAKNET_BOOTSTRAP` | Override bootstrap node               |
| `KAYAKNET_LOG_LEVEL` | Logging level (debug/info/warn/error) |

## Examples

### Basic Usage

```bash
./kayakd --bootstrap 203.161.33.237:4242 --proxy
```

### Custom Name and Ports

```bash
./kayakd \
  --bootstrap 203.161.33.237:4242 \
  --proxy \
  --name "my-private-node" \
  --listen 0.0.0.0:4243 \
  --http-proxy 8119 \
  --socks-proxy 8120
```

### Production Node

```bash
./kayakd \
  --config /etc/kayaknet/config.json \
  --data-dir /var/lib/kayaknet \
  --bootstrap 203.161.33.237:4242 \
  --public-api \
  --max-peers 100
```

### Bootstrap Node

```bash
./kayakd \
  --listen 0.0.0.0:4242 \
  --public-api \
  --name "bootstrap-node" \
  --data-dir /var/lib/kayaknet
```

## Data Directory Structure

```
data/
├── identity.key      # Node's cryptographic identity
├── peers.json        # Known peer addresses
├── dht/              # DHT records
├── chat/             # Chat history
├── market/           # Marketplace data
│   ├── listings.json
│   └── orders.json
├── escrow/           # Escrow records
└── names/            # .kyk domain registrations
```

## Identity Management

Your node's identity is stored in `identity.key`. This file contains:

* Ed25519 private key
* Node ID (derived from public key)

**Important:**

* Back up this file to maintain your identity
* If lost, you'll appear as a new node
* Never share this file with anyone


# Browser Setup

To access KayakNet services like `home.kyk`, you need to configure your browser to use the KayakNet proxy.

## Quick Setup

KayakNet provides two proxy types:

* **HTTP Proxy:** `127.0.0.1:8118`
* **SOCKS5 Proxy:** `127.0.0.1:8119`

## Browser-Specific Instructions

### Firefox (Recommended)

1. Open **Settings** (≡ → Settings)
2. Search for "proxy"
3. Click **Settings...** in Network Settings
4. Select **Manual proxy configuration**
5. Enter:
   * HTTP Proxy: `127.0.0.1` Port: `8118`
   * Check "Also use this proxy for HTTPS"
6. Click **OK**

**Alternative: Use SOCKS5**

* SOCKS Host: `127.0.0.1` Port: `8119`
* Select "SOCKS v5"
* Check "Proxy DNS when using SOCKS v5"

### Chrome / Edge / Brave

Chrome uses system proxy settings. You have two options:

**Option 1: System Proxy (Windows)**

1. Open Windows Settings
2. Network & Internet → Proxy
3. Manual proxy setup → On
4. Address: `127.0.0.1`
5. Port: `8118`

**Option 2: Extension (Recommended)**

1. Install "Proxy SwitchyOmega" extension
2. Create new profile "KayakNet"
3. Protocol: HTTP, Server: `127.0.0.1`, Port: `8118`
4. Apply changes
5. Click extension → Select "KayakNet"

**Option 3: Command Line**

```bash
chrome --proxy-server="http://127.0.0.1:8118"
```

### Safari (macOS)

1. System Preferences → Network
2. Select your connection → Advanced
3. Proxies tab
4. Check "Web Proxy (HTTP)"
5. Server: `127.0.0.1` Port: `8118`
6. Check "Secure Web Proxy (HTTPS)"
7. Server: `127.0.0.1` Port: `8118`
8. Click OK → Apply

### Tor Browser

Tor Browser is pre-configured for Tor. To use KayakNet instead:

1. Open `about:preferences#connection`
2. At the bottom, click "Settings..."
3. Select "Manual proxy configuration"
4. HTTP Proxy: `127.0.0.1` Port: `8118`
5. Restart browser

## Testing Your Setup

After configuring:

1. Navigate to `http://home.kyk`
2. You should see the KayakNet homepage
3. If you see an error, check:
   * KayakNet node is running
   * Proxy settings are correct
   * No other proxy is interfering

## Supported Domains

With the proxy configured, you can access:

| Domain            | Description                |
| ----------------- | -------------------------- |
| `home.kyk`        | KayakNet homepage          |
| `chat.kyk`        | Chat interface             |
| `market.kyk`      | Marketplace                |
| `marketplace.kyk` | Marketplace (alias)        |
| `domains.kyk`     | Domain registration        |
| `network.kyk`     | Network statistics         |
| `*.kyk`           | Any registered .kyk domain |

## Troubleshooting

### "Proxy Server Refused Connection"

* Ensure KayakNet node is running
* Check proxy port matches your configuration
* Try restarting the node

### "Unable to Connect"

* Verify proxy settings in browser
* Try HTTP proxy instead of SOCKS5
* Check for firewall blocking port 8118

### "Page Not Found" for .kyk domains

* The domain may not be registered
* Try `home.kyk` to verify proxy works
* Check if node is connected to network

### Slow Loading

* Wait for node to connect to peers
* First load may be slow due to onion routing
* Subsequent loads are faster due to caching

## Privacy Tips

### Do

* Use Firefox with enhanced tracking protection
* Clear cookies after sessions
* Use private/incognito mode

### Don't

* Log into personal accounts (Google, Facebook)
* Enable WebRTC (can leak real IP)
* Install untrusted extensions
* Mix KayakNet and regular browsing

### Disable WebRTC in Firefox

1. Open `about:config`
2. Search `media.peerconnection.enabled`
3. Set to `false`

## Dedicated Browser Profile

For best privacy, create a separate browser profile:

**Firefox:**

```bash
firefox -P  # Opens profile manager
# Create "KayakNet" profile
# Configure proxy only in this profile
```

**Chrome:**

```bash
chrome --user-data-dir="~/.kayaknet-chrome"
```

This keeps your KayakNet browsing completely separate from regular browsing.


# Overview

KayakNet is built as a layered system, with each layer providing specific functionality.

## High-Level Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    User Applications                         │
│            (Browser, CLI, Android App)                       │
├─────────────────────────────────────────────────────────────┤
│                      HTTP/SOCKS Proxy                        │
├──────────────┬──────────────┬──────────────┬────────────────┤
│     Chat     │  Marketplace │   Domains    │    Escrow      │
├──────────────┴──────────────┴──────────────┴────────────────┤
│                       PubSub Layer                           │
├─────────────────────────────────────────────────────────────┤
│                    Onion Routing Layer                       │
├─────────────────────────────────────────────────────────────┤
│                  DHT & Peer Discovery                        │
├─────────────────────────────────────────────────────────────┤
│                   Security Layer                             │
│        (PoW, Rate Limiting, Peer Scoring)                    │
├─────────────────────────────────────────────────────────────┤
│                   Transport Layer                            │
│              (TCP/QUIC with TLS 1.3)                         │
└─────────────────────────────────────────────────────────────┘
```

## Core Components

### 1. Transport Layer

* Encrypted connections between peers
* Support for TCP and QUIC protocols
* TLS 1.3 with certificate pinning

### 2. Security Layer

* Proof-of-Work for Sybil resistance
* Rate limiting to prevent abuse
* Peer scoring and ban lists
* Nonce tracking for replay protection

### 3. DHT (Distributed Hash Table)

* Kademlia-based peer discovery
* Decentralized data storage
* Self-healing network topology

### 4. Onion Routing

* 3-hop encrypted circuits
* Traffic analysis resistance
* Padding and timing obfuscation

### 5. PubSub Layer

* Topic-based message routing
* Efficient multicast delivery
* Message deduplication

### 6. Application Services

* **Chat:** E2E encrypted messaging
* **Marketplace:** Listings and orders
* **Domains:** .kyk naming system
* **Escrow:** Cryptocurrency payments

## Data Flow

### Sending a Message

```
1. User sends message
         ↓
2. Application encrypts (E2E)
         ↓
3. PubSub wraps message
         ↓
4. Onion router creates circuit
         ↓
5. Message sent through 3 hops
         ↓
6. Recipient's node receives
         ↓
7. Unwrap and decrypt
         ↓
8. Deliver to recipient
```

### Network Discovery

```
1. Node starts
         ↓
2. Connect to bootstrap
         ↓
3. Solve PoW challenge
         ↓
4. Join DHT network
         ↓
5. Discover peers via DHT
         ↓
6. Establish direct connections
         ↓
7. Begin routing traffic
```

## Key Design Decisions

### Why Go?

* Single binary deployment
* Cross-platform compilation
* Excellent concurrency model
* Strong standard library

### Why Not Tor?

* Full control over privacy features
* Integrated services (chat, marketplace)
* Simpler deployment
* Custom traffic analysis resistance

### Why Monero/Zcash?

* Privacy by default
* Shielded transactions
* No blockchain analysis possible
* Community trust

## Component Interaction

```
┌──────────┐     ┌──────────┐     ┌──────────┐
│  Node A  │────▶│  Node B  │────▶│  Node C  │
└──────────┘     └──────────┘     └──────────┘
     │                │                │
     └────────────────┼────────────────┘
                      │
              ┌───────▼───────┐
              │   Bootstrap   │
              │     Node      │
              └───────────────┘
```

## Persistence

All data is persisted locally:

* Identity keys (never leave device)
* Chat history (encrypted)
* Marketplace data
* Escrow records
* Domain registrations

## Scalability

* **Horizontal:** Add more nodes
* **Vertical:** Increase per-node capacity
* **DHT:** Scales logarithmically with nodes
* **PubSub:** Efficient multicast reduces load


# Network Topology

KayakNet uses a decentralized peer-to-peer topology with no central servers.

## Network Structure

```
                    ┌──────────┐
                    │Bootstrap │
                    │  Node    │
                    └────┬─────┘
                         │
         ┌───────────────┼───────────────┐
         │               │               │
    ┌────▼────┐     ┌────▼────┐     ┌────▼────┐
    │  Node A │◄───►│  Node B │◄───►│  Node C │
    └────┬────┘     └────┬────┘     └────┬────┘
         │               │               │
         │    ┌──────────┘               │
         │    │                          │
    ┌────▼────▼──┐              ┌────────▼───┐
    │   Node D   │◄────────────►│   Node E   │
    └────────────┘              └────────────┘
```

## Node Types

### Bootstrap Nodes

* Well-known entry points
* Help new nodes join
* Provide initial peer lists
* Always available

### Regular Nodes

* Run by users
* Equal participants
* Route traffic for others
* Come and go freely

### Relay Nodes (Optional)

* High-bandwidth volunteers
* Prioritized for routing
* No special privileges

## Peer Discovery

### Initial Connection

1. New node contacts bootstrap
2. Solves Proof-of-Work challenge
3. Receives initial peer list
4. Connects to peers

### DHT-Based Discovery

Once connected:

1. Node joins Kademlia DHT
2. Announces its presence
3. Discovers peers via DHT queries
4. Maintains routing table

### Peer Selection

Criteria for selecting peers:

* **Diversity** - Different subnets/geographies
* **Reliability** - Low latency, high uptime
* **Capacity** - Bandwidth availability
* **Reputation** - Peer score

## Connection Management

### Maintaining Connections

```
┌─────────────┐
│   Target:   │
│  10-50 peers│
└──────┬──────┘
       │
       ▼
┌─────────────────────────────────┐
│ If peers < min:                 │
│   - Query DHT for more          │
│   - Try cached addresses        │
│ If peers > max:                 │
│   - Disconnect lowest scored    │
└─────────────────────────────────┘
```

### Connection Limits

| Parameter       | Default | Description            |
| --------------- | ------- | ---------------------- |
| Min Peers       | 5       | Minimum connections    |
| Max Peers       | 50      | Maximum connections    |
| Bootstrap Peers | 3       | Reserved for bootstrap |

### Peer Scoring

Peers are scored based on:

* **Latency** - Lower is better
* **Uptime** - Longer is better
* **Behavior** - No spam, valid messages
* **Throughput** - Bandwidth provided

## Network Resilience

### Node Failures

When a peer disconnects:

1. Mark as offline
2. Try reconnection (3 attempts)
3. Remove from active list
4. Keep in cache for later
5. Find replacement peer

### Partition Healing

If network splits:

1. Both partitions continue independently
2. Bootstrap nodes bridge partitions
3. DHT eventually merges
4. Data reconciles

### Attack Resistance

| Attack    | Mitigation        |
| --------- | ----------------- |
| Sybil     | PoW, peer scoring |
| Eclipse   | Diverse selection |
| DDoS      | Rate limiting     |
| Partition | Bootstrap bridges |

## Data Propagation

### Message Routing

Messages propagate via:

1. **Direct** - To connected peers
2. **Gossip** - Random peer selection
3. **DHT** - Store and forward
4. **PubSub** - Topic subscription

### Latency

Typical message latency:

* Direct peer: 50-100ms
* 2-hop: 100-200ms
* 3-hop (onion): 150-300ms
* DHT lookup: 200-500ms

## Geographic Distribution

Nodes are globally distributed:

* No geographic restrictions
* Automatic peer diversity
* Regional clustering avoided

```
Americas        Europe          Asia-Pacific
   ●              ●●               ●
  ●●●            ●●●●             ●●●
   ●●             ●●               ●●
```

## Bootstrap Infrastructure

### Current Bootstrap Nodes

| Address             | Location | Status |
| ------------------- | -------- | ------ |
| 203.161.33.237:4242 | Primary  | Active |

### Running Your Own Bootstrap

```bash
./kayakd \
  --listen 0.0.0.0:4242 \
  --public-api \
  --name my-bootstrap \
  --data-dir /var/lib/kayaknet
```

Contact us to be added to default list.

## Monitoring

### Network Health

Check your node's connectivity:

```bash
curl http://127.0.0.1:8080/api/network/peers
```

Key metrics:

* Peer count (should be 5-50)
* Latency (should be <500ms)
* Message throughput

### Debug Logging

```bash
./kayakd --log-level debug
```


# Onion Routing

KayakNet uses onion routing to provide anonymity for all network traffic.

## What is Onion Routing?

Onion routing wraps messages in multiple layers of encryption, like layers of an onion. Each node in the path can only see the previous and next hop, never the full route.

## How It Works

### Circuit Building

```
┌────────┐                                              ┌────────┐
│ Sender │                                              │Receiver│
└───┬────┘                                              └────▲───┘
    │                                                        │
    │  Encrypted for Hop 3                                   │
    │  ┌─────────────────────────────────────────────────┐   │
    │  │ Encrypted for Hop 2                             │   │
    │  │ ┌─────────────────────────────────────────────┐ │   │
    │  │ │ Encrypted for Hop 1                         │ │   │
    │  │ │ ┌─────────────────────────────────────────┐ │ │   │
    │  │ │ │           Original Message              │ │ │   │
    │  │ │ └─────────────────────────────────────────┘ │ │   │
    │  │ └─────────────────────────────────────────────┘ │   │
    │  └─────────────────────────────────────────────────┘   │
    │                                                        │
    ▼                                                        │
┌───────┐          ┌───────┐          ┌───────┐              │
│ Hop 1 │─────────▶│ Hop 2 │─────────▶│ Hop 3 │──────────────┘
└───────┘          └───────┘          └───────┘
Removes one        Removes one        Removes final
layer              layer              layer
```

### Step by Step

1. **Sender** selects 3 random nodes from the network
2. **Sender** generates session keys for each hop
3. **Message** is encrypted in layers:
   * Layer 3: Encrypted with Hop 3's key
   * Layer 2: Encrypted with Hop 2's key
   * Layer 1: Encrypted with Hop 1's key
4. **Hop 1** receives, decrypts outer layer, forwards
5. **Hop 2** receives, decrypts its layer, forwards
6. **Hop 3** receives, decrypts final layer, delivers

## KayakNet Implementation

### Circuit Parameters

| Parameter        | Value             | Rationale                        |
| ---------------- | ----------------- | -------------------------------- |
| Hops             | 3                 | Balance of anonymity and latency |
| Circuit Lifetime | 10 minutes        | Prevent long-term correlation    |
| Key Algorithm    | X25519            | Fast, secure key exchange        |
| Encryption       | ChaCha20-Poly1305 | Modern AEAD cipher               |

### Circuit Selection

Nodes are selected to maximize anonymity:

```go
// Pseudocode for node selection
func selectCircuit() []Node {
    // Avoid selecting same node twice
    // Prefer nodes from different subnets
    // Exclude recently used nodes
    // Favor nodes with good reputation
}
```

### Header Format

```
┌─────────────────────────────────────────────┐
│ Version (1 byte)                            │
├─────────────────────────────────────────────┤
│ Circuit ID (16 bytes)                       │
├─────────────────────────────────────────────┤
│ Next Hop Address (encrypted)                │
├─────────────────────────────────────────────┤
│ Ephemeral Public Key (32 bytes)             │
├─────────────────────────────────────────────┤
│ Encrypted Payload                           │
└─────────────────────────────────────────────┘
```

## Traffic Analysis Resistance

Beyond basic onion routing, KayakNet implements:

### 1. Constant Packet Size

All packets are padded to 1024 bytes, preventing size correlation.

### 2. Timing Obfuscation

Random delays (0-100ms) prevent timing analysis.

### 3. Dummy Traffic

Nodes send fake traffic to obscure real patterns.

### 4. Traffic Mixing

Packets are batched and shuffled before forwarding.

## Anonymity Properties

### What Onion Routing Provides

✅ **Sender Anonymity** - Receiver doesn't know sender ✅ **Receiver Anonymity** - Sender doesn't know receiver's IP ✅ **Relationship Anonymity** - Third parties can't link sender/receiver ✅ **Forward Secrecy** - Past traffic can't be decrypted

### What It Doesn't Provide

❌ **Global Passive Adversary** - Nation-state level monitoring may correlate ❌ **Endpoint Compromise** - If sender or receiver is compromised ❌ **Traffic Confirmation** - If adversary controls first and last hop

## Compared to Tor

| Feature            | KayakNet | Tor     |
| ------------------ | -------- | ------- |
| Default Hops       | 3        | 3       |
| Circuit Rotation   | 10 min   | 10 min  |
| Traffic Padding    | Yes      | Limited |
| Timing Obfuscation | Yes      | No      |
| Dummy Traffic      | Yes      | No      |
| Directory Servers  | No (DHT) | Yes     |

## Performance Impact

Onion routing adds latency:

| Metric     | Without Onion | With Onion  |
| ---------- | ------------- | ----------- |
| Latency    | \~50ms        | \~150-300ms |
| Throughput | High          | Moderate    |
| CPU Usage  | Low           | Moderate    |

The tradeoff is acceptable for privacy-focused applications.

## Configuration

```bash
# Use 5 hops instead of 3 (not recommended)
./kayakd --onion-hops 5

# Note: More hops = more latency, diminishing returns on security
```


# DHT & Peer Discovery

KayakNet uses a Kademlia-based Distributed Hash Table (DHT) for peer discovery and decentralized data storage.

## What is a DHT?

A DHT is a decentralized key-value store distributed across all nodes:

* No central server
* Data is replicated
* Lookups are efficient (O(log n))
* Survives node failures

## Kademlia Protocol

KayakNet uses Kademlia, the same DHT protocol used by BitTorrent.

### XOR Distance

Nodes are assigned IDs, and "distance" is calculated using XOR:

```
Distance(A, B) = A XOR B
```

This creates a metric space where:

* Each node knows about nodes "close" to it
* Lookups get exponentially closer with each hop

### Routing Table

Each node maintains a routing table of k-buckets:

```
┌─────────────────────────────────┐
│ Bucket 0: Distance 2^0 - 2^1    │  ← Very close nodes
├─────────────────────────────────┤
│ Bucket 1: Distance 2^1 - 2^2    │
├─────────────────────────────────┤
│ Bucket 2: Distance 2^2 - 2^3    │
├─────────────────────────────────┤
│ ...                             │
├─────────────────────────────────┤
│ Bucket 255: Distance 2^255+     │  ← Very far nodes
└─────────────────────────────────┘
```

Each bucket holds up to K nodes (K=20 in KayakNet).

## Operations

### PING

Check if a node is alive:

```
Node A → PING → Node B
Node A ← PONG ← Node B
```

### STORE

Store a key-value pair:

```
Node A → STORE(key, value) → Closest nodes
```

### FIND\_NODE

Find nodes close to a target ID:

```
Node A → FIND_NODE(target_id) → Node B
Node A ← [list of close nodes] ← Node B
```

### FIND\_VALUE

Retrieve a stored value:

```
Node A → FIND_VALUE(key) → Node B
Node A ← value OR [closer nodes] ← Node B
```

## Peer Discovery Process

### Joining the Network

```
1. Connect to bootstrap
   │
2. Get initial peers
   │
3. Perform FIND_NODE on own ID
   │
4. Discover close neighbors
   │
5. Populate routing table
   │
6. Announce presence
```

### Iterative Lookup

To find a node or value:

```
Start with α closest known nodes
    │
For each node, send query
    │
Receive responses with closer nodes
    │
Query the newly discovered closer nodes
    │
Repeat until no closer nodes found
    │
Return result
```

Parameters:

* α (alpha) = 3 (parallel queries)
* K = 20 (nodes per bucket)

## Data Storage

### What's Stored in DHT

| Key Type        | Value                   | TTL       |
| --------------- | ----------------------- | --------- |
| `peer:<id>`     | Node address            | 1 hour    |
| `room:<name>`   | Room metadata           | 24 hours  |
| `domain:<name>` | Domain record           | Permanent |
| `listing:<id>`  | Marketplace listing     | 7 days    |
| `msg:<hash>`    | Message (store-forward) | 1 hour    |

### Replication

Data is stored on the K closest nodes:

* Provides redundancy
* Survives node failures
* Automatic re-replication

### TTL and Refresh

* Records have TTL
* Publishers refresh before expiry
* Expired records are deleted
* Popular content stays available

## Configuration

```json
{
  "dht": {
    "k": 20,              // Bucket size
    "alpha": 3,           // Parallel queries
    "record_ttl": "24h",  // Default TTL
    "refresh_interval": "1h"
  }
}
```

## Performance

### Lookup Efficiency

For N nodes in network:

* Average hops: O(log N)
* With 1M nodes: \~20 hops
* With caching: Often 1-3 hops

### Bandwidth Usage

* PING: \~100 bytes
* FIND\_NODE: \~500 bytes
* STORE: Variable (depends on value)

## Security Considerations

### Sybil Protection

Without protection, attacker could:

* Create many nodes
* Control routing
* Censor lookups

KayakNet mitigation:

* Proof-of-Work for new nodes
* Peer scoring
* Diverse peer selection

### Eclipse Protection

Without protection, attacker could:

* Surround victim node
* Control all their peers
* Censor or manipulate

KayakNet mitigation:

* Require peers from different subnets
* Maintain bootstrap connections
* Periodic peer refresh

### Data Integrity

All DHT records are signed:

```
Record = {
  key: "domain:example.kyk",
  value: { ... },
  publisher: <public_key>,
  signature: <Ed25519_sig>,
  timestamp: 1234567890
}
```

Unsigned or invalid records are rejected.

## Comparison with Other DHTs

| DHT      | Used By              | Differences             |
| -------- | -------------------- | ----------------------- |
| Kademlia | BitTorrent, KayakNet | XOR distance, k-buckets |
| Chord    | Academic             | Ring topology           |
| Pastry   | Academic             | Prefix routing          |
| Coral    | CDN                  | Hierarchical clusters   |

## Troubleshooting

### Few Peers

```bash
# Check peer count
curl http://127.0.0.1:8080/api/network/peers

# If < 5, wait or restart
```

### Slow Lookups

* Check network connectivity
* Verify bootstrap is reachable
* Increase alpha for more parallelism

### Data Not Found

* Publisher may be offline
* TTL may have expired
* Try again after network refresh


# 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


# Data Persistence

KayakNet persists all data locally to survive restarts and provide history.

## Data Directory

Default location: `./data/`

```
data/
├── identity.key          # Node identity (Ed25519 keypair)
├── peers.json            # Known peer addresses
├── config.json           # Runtime configuration
├── dht/
│   └── records.json      # DHT records
├── chat/
│   ├── rooms/
│   │   └── #general.json # Room messages
│   └── dms/
│       └── <node_id>.json # Direct messages
├── market/
│   ├── listings.json     # All listings
│   └── my_listings.json  # Your listings
├── escrow/
│   ├── orders.json       # Order records
│   └── wallets.json      # Crypto wallet data
├── names/
│   └── domains.json      # .kyk registrations
└── cache/
    └── ...               # Temporary cache
```

## Identity Persistence

### identity.key

```json
{
  "private_key": "<base64 encoded Ed25519 private key>",
  "public_key": "<base64 encoded public key>",
  "node_id": "<hex encoded node ID>",
  "created_at": "2026-01-15T10:00:00Z"
}
```

**Important:**

* Back this up!
* Losing it = new identity
* Never share with anyone

## Chat Persistence

### Room Messages

`data/chat/rooms/#general.json`:

```json
{
  "room": "#general",
  "messages": [
    {
      "id": "msg_abc123",
      "sender_id": "node_123...",
      "sender_name": "alice",
      "content": "Hello!",
      "timestamp": 1234567890,
      "signature": "..."
    }
  ],
  "last_sync": "2026-01-15T10:00:00Z"
}
```

### Direct Messages

`data/chat/dms/<recipient_id>.json`:

```json
{
  "peer_id": "node_456...",
  "peer_name": "bob",
  "messages": [
    {
      "id": "dm_xyz789",
      "from_me": true,
      "content": "Private message",
      "timestamp": 1234567890,
      "read": true
    }
  ]
}
```

## Marketplace Persistence

### Listings

`data/market/listings.json`:

```json
{
  "listings": [
    {
      "id": "listing_abc",
      "title": "Product",
      "price": 99.99,
      "seller_id": "node_123...",
      "created_at": "2026-01-15T10:00:00Z",
      "synced_at": "2026-01-15T10:05:00Z"
    }
  ]
}
```

## Escrow Persistence

### Orders

`data/escrow/orders.json`:

```json
{
  "orders": [
    {
      "id": "esc_123",
      "order_id": "ord_456",
      "listing_id": "listing_abc",
      "buyer_id": "node_buyer...",
      "seller_id": "node_seller...",
      "amount": 0.5,
      "currency": "XMR",
      "state": "funded",
      "payment_address": "...",
      "created_at": "2026-01-15T10:00:00Z"
    }
  ]
}
```

## Domain Persistence

### Registered Domains

`data/names/domains.json`:

```json
{
  "domains": [
    {
      "name": "mysite.kyk",
      "target": "node_id:abc123...",
      "owner": "<public_key>",
      "registered_at": "2026-01-15T10:00:00Z",
      "signature": "..."
    }
  ]
}
```

## Sync Mechanism

### On Startup

1. Load local data from files
2. Connect to network
3. Request updates from peers
4. Merge with local data
5. Save merged state

### During Runtime

* Changes saved immediately
* Background sync every 5 minutes
* Conflict resolution by timestamp

### Conflict Resolution

* Newer timestamp wins
* For listings: Seller's version wins
* For domains: First registration wins

## Backup & Recovery

### Creating Backup

```bash
# Backup entire data directory
tar -czf kayaknet-backup.tar.gz ./data/

# Or just identity
cp data/identity.key identity-backup.key
```

### Restoring Backup

```bash
# Full restore
tar -xzf kayaknet-backup.tar.gz

# Identity only
cp identity-backup.key data/identity.key
```

### What to Backup

| File                     | Priority | Notes               |
| ------------------------ | -------- | ------------------- |
| identity.key             | Critical | Cannot recover      |
| names/domains.json       | High     | Your domains        |
| escrow/orders.json       | High     | Transaction records |
| chat/                    | Medium   | Message history     |
| market/my\_listings.json | Medium   | Your listings       |
| peers.json               | Low      | Rebuilds quickly    |

## Storage Limits

### Default Limits

| Data Type              | Limit  |
| ---------------------- | ------ |
| Chat messages per room | 10,000 |
| DM conversations       | 1,000  |
| Listings cache         | 5,000  |
| DHT records            | 10,000 |

### Cleanup

Old data is automatically cleaned:

* Expired DHT records: Deleted on expiry
* Old messages: Keep last N
* Failed escrows: Archive after 30 days

## Custom Data Directory

```bash
./kayakd --data-dir /custom/path/data
```

Or environment variable:

```bash
export KAYAKNET_DATA_DIR=/custom/path/data
```

## Database Format

Currently using JSON files for simplicity.

Future plans:

* SQLite for large datasets
* LevelDB for DHT
* Encrypted storage option


# Security Model

KayakNet is designed with security as the primary concern. This document describes the security model and guarantees.

## Security Layers

```
┌─────────────────────────────────────────────────┐
│            Application Layer E2E                │
│         (Chat, Marketplace, etc.)               │
├─────────────────────────────────────────────────┤
│           Onion Routing (3 hops)                │
│      X25519 + ChaCha20-Poly1305                 │
├─────────────────────────────────────────────────┤
│          Transport Encryption                   │
│              TLS 1.3                            │
├─────────────────────────────────────────────────┤
│      Traffic Analysis Resistance                │
│   Padding, Mixing, Timing Obfuscation          │
├─────────────────────────────────────────────────┤
│            Anti-Sybil (PoW)                     │
│        Peer Scoring, Rate Limiting              │
└─────────────────────────────────────────────────┘
```

## Cryptographic Primitives

| Purpose              | Algorithm         | Key Size |
| -------------------- | ----------------- | -------- |
| Identity Keys        | Ed25519           | 256-bit  |
| Key Exchange         | X25519            | 256-bit  |
| Symmetric Encryption | ChaCha20-Poly1305 | 256-bit  |
| Hashing              | BLAKE2b           | 256-bit  |
| Key Derivation       | HKDF-SHA256       | -        |
| Signatures           | Ed25519           | 256-bit  |

## Security Guarantees

### Confidentiality

* All messages encrypted end-to-end
* Even if network is compromised, content is protected
* Forward secrecy: past messages can't be decrypted

### Integrity

* All messages are authenticated (AEAD)
* Tampering is detected and rejected
* Signatures verify sender identity

### Anonymity

* Onion routing hides sender/receiver relationship
* Traffic analysis resistance obscures patterns
* No logs are kept by nodes

### Availability

* Decentralized architecture resists takedowns
* DHT ensures peer discovery survives node failures
* Multiple bootstrap nodes for redundancy

## Threat Model

### What We Protect Against

| Threat            | Mitigation                      |
| ----------------- | ------------------------------- |
| Eavesdropping     | End-to-end encryption           |
| Man-in-the-Middle | Certificate pinning, signatures |
| Traffic Analysis  | Padding, mixing, dummy traffic  |
| Sybil Attacks     | Proof-of-Work for new nodes     |
| Eclipse Attacks   | Diverse peer selection          |
| Replay Attacks    | Nonce tracking                  |
| DDoS              | Rate limiting, peer scoring     |

### What We Don't Protect Against

| Threat                    | Reason                                 |
| ------------------------- | -------------------------------------- |
| Global Passive Adversary  | Traffic correlation at scale           |
| Endpoint Compromise       | If your device is hacked               |
| Rubber Hose Cryptanalysis | Physical coercion                      |
| Quantum Computers         | (Future: Post-quantum upgrade planned) |

## Attack Scenarios

### Scenario 1: ISP Monitoring

**Threat:** ISP logs all your traffic **Protection:**

* TLS hides content
* Onion routing hides destinations
* Traffic padding hides patterns

### Scenario 2: Malicious Node

**Threat:** Attacker runs KayakNet node **Protection:**

* E2E encryption (can't read content)
* Only sees adjacent hops (can't identify endpoints)
* Peer scoring isolates bad actors

### Scenario 3: Network Injection

**Threat:** Attacker injects fake messages **Protection:**

* All messages are signed
* Signatures verified before processing
* Invalid messages dropped

### Scenario 4: Sybil Attack

**Threat:** Attacker creates many fake nodes **Protection:**

* Proof-of-Work required to join
* Peer scoring deprioritizes suspicious nodes
* Eclipse attack prevention in peer selection

## Best Practices

### For Users

1. **Keep software updated** - Security patches are important
2. **Use strong device security** - Full disk encryption
3. **Don't reuse identities** - Create new node for sensitive activity
4. **Verify recipients** - Ensure you're talking to who you think

### For Node Operators

1. **Run latest version** - `--auto-update`
2. **Use dedicated machine** - Isolate from other services
3. **Monitor for anomalies** - Watch peer counts, traffic
4. **Don't log** - Disable any external logging

## Security Audits

KayakNet has not yet undergone a formal security audit. If you're a security researcher and would like to audit the code, please contact us.

## Responsible Disclosure

If you find a security vulnerability:

1. **Do not** disclose publicly
2. Email: <security@kayaknet.io> (PGP key available)
3. Include detailed reproduction steps
4. Allow 90 days for fix before disclosure

## Known Limitations

1. **Metadata** - Message timing may leak information
2. **Traffic Correlation** - Global adversary could correlate
3. **Trust in Bootstrap** - Initial connection reveals interest
4. **Mobile** - Battery and network constraints limit protections


# Encryption Layers

KayakNet uses multiple layers of encryption to protect your data.

## Overview

```
┌─────────────────────────────────────────────────┐
│  Layer 4: Application E2E Encryption            │
│  (Chat messages, delivery info, etc.)           │
├─────────────────────────────────────────────────┤
│  Layer 3: Onion Routing Encryption              │
│  (3 nested layers, one per hop)                 │
├─────────────────────────────────────────────────┤
│  Layer 2: Transport Encryption (TLS 1.3)        │
│  (Per-connection encryption)                    │
├─────────────────────────────────────────────────┤
│  Layer 1: Physical Transport                    │
│  (TCP/UDP packets)                              │
└─────────────────────────────────────────────────┘
```

## Layer 1: Transport Encryption

Every connection between nodes uses TLS 1.3:

* **Cipher Suite**: TLS\_CHACHA20\_POLY1305\_SHA256
* **Key Exchange**: X25519
* **Certificate**: Self-signed Ed25519

### What It Protects

* Content of packets between directly connected peers
* Node identity (certificate includes public key)

### What It Doesn't Protect

* Traffic patterns (timing, size)
* Metadata (who's talking to whom)

## Layer 2: Onion Routing

Messages are wrapped in 3 layers of encryption:

```
Sender encrypts:
  Layer 3 key → for Exit Node
    Layer 2 key → for Middle Node
      Layer 1 key → for Entry Node
        Message
```

### Key Exchange

Each hop gets its own ephemeral key:

1. Sender generates X25519 keypair
2. ECDH with hop's public key
3. HKDF to derive symmetric key
4. ChaCha20-Poly1305 encryption

### Header Format

```
┌──────────────────────────────────┐
│ Ephemeral Public Key (32 bytes)  │
├──────────────────────────────────┤
│ Next Hop (encrypted)             │
├──────────────────────────────────┤
│ Payload (encrypted)              │
└──────────────────────────────────┘
```

## Layer 3: Application E2E

Chat messages and sensitive data have additional encryption:

### Chat Room Keys

* Symmetric key shared by room members
* Rotated when membership changes
* ChaCha20-Poly1305

### Direct Messages

* X25519 key exchange with recipient
* Per-message key derivation (forward secrecy)
* Ed25519 signature for authentication

### Escrow Data

* Delivery info encrypted to seller's key
* Only seller can decrypt

## Cryptographic Primitives

| Purpose              | Algorithm         | Standard |
| -------------------- | ----------------- | -------- |
| Signatures           | Ed25519           | RFC 8032 |
| Key Exchange         | X25519            | RFC 7748 |
| Symmetric Encryption | ChaCha20-Poly1305 | RFC 8439 |
| Key Derivation       | HKDF-SHA256       | RFC 5869 |
| Hashing              | BLAKE2b-256       | RFC 7693 |

## Key Management

### Node Identity Key

* Ed25519 keypair
* Generated on first run
* Stored in `identity.key`
* Never transmitted

### Session Keys

* Ephemeral per-connection
* X25519 exchange
* Destroyed after use

### Room Keys

* Generated by room creator
* Encrypted to each member
* Rotated on membership change

## Forward Secrecy

KayakNet provides forward secrecy through:

1. **Ephemeral Keys** - New keys per session
2. **Key Rotation** - Regular key changes
3. **Key Destruction** - Old keys deleted

If your long-term key is compromised:

* Past messages remain encrypted
* Only future messages affected

## Quantum Resistance

Current algorithms are NOT quantum-resistant. Planned upgrades:

* **CRYSTALS-Kyber** - Post-quantum key exchange
* **CRYSTALS-Dilithium** - Post-quantum signatures
* **Hybrid Mode** - Classical + PQ for transition

## Implementation Details

### Random Number Generation

```go
// Using crypto/rand for all randomness
import "crypto/rand"

key := make([]byte, 32)
rand.Read(key)
```

### Constant-Time Operations

All cryptographic comparisons use constant-time functions:

```go
import "crypto/subtle"

if subtle.ConstantTimeCompare(a, b) == 1 {
    // Equal
}
```

### Memory Security

Sensitive data is:

* Zeroed after use
* Not logged or printed
* Stored in secure memory where possible

## Verification

You can verify encryption using packet captures:

```bash
# Capture KayakNet traffic
tcpdump -i any port 4242 -w capture.pcap

# Analyze with Wireshark
# All payloads should appear as random data
```


# Traffic Analysis Resistance

KayakNet implements multiple techniques to resist traffic analysis attacks.

## What is Traffic Analysis?

Traffic analysis examines metadata (timing, size, patterns) to learn about communications without reading content.

Even with encryption, an adversary can learn:

* When you're active
* Who you communicate with (by correlating endpoints)
* How much you communicate
* Patterns of behavior

## Protection Techniques

### 1. Constant Packet Size

All packets are padded to a fixed size (1024 bytes):

```
┌────────────────────────────────────────────────┐
│ Small message (50 bytes)                       │
│ + Padding (974 bytes) = 1024 bytes             │
└────────────────────────────────────────────────┘

┌────────────────────────────────────────────────┐
│ Large message (900 bytes)                      │
│ + Padding (124 bytes) = 1024 bytes             │
└────────────────────────────────────────────────┘
```

**Effect:** Observer cannot determine message size.

### 2. Timing Obfuscation

Random delays are added to message forwarding:

```
Received message
      │
      ▼
┌─────────────────────────┐
│ Random delay 0-100ms    │
└─────────────────────────┘
      │
      ▼
Forward message
```

**Effect:** Harder to correlate by timing.

### 3. Traffic Mixing

Multiple messages are batched and shuffled:

```
Messages A, B, C arrive
      │
      ▼
┌─────────────────────────┐
│ Collect in pool         │
│ Wait for more (50ms)    │
│ Shuffle order           │
│ Send: C, A, B           │
└─────────────────────────┘
```

**Effect:** Order doesn't reveal source-destination relationship.

### 4. Dummy Traffic

Nodes send fake messages to obscure real patterns:

```
Real traffic: ●○○●○○○●
Dummy added:  ●●●●●●●●
```

**Effect:** Activity level is constant regardless of real usage.

### 5. Circuit Rotation

Onion routing circuits are changed periodically:

| Time      | Circuit   |
| --------- | --------- |
| 0-10 min  | A → B → C |
| 10-20 min | D → E → F |
| 20-30 min | G → H → I |

**Effect:** Long-term correlation is harder.

## Configuration

```json
{
  "traffic_analysis_resistance": {
    "enabled": true,
    "packet_size": 1024,
    "max_delay_ms": 100,
    "mixing_pool_size": 10,
    "mixing_interval_ms": 50,
    "dummy_traffic_rate": 0.2,
    "circuit_rotation_minutes": 10
  }
}
```

## Performance Impact

| Technique     | Latency Impact | Bandwidth Impact |
| ------------- | -------------- | ---------------- |
| Padding       | None           | +20-50%          |
| Timing        | +50ms avg      | None             |
| Mixing        | +50ms avg      | None             |
| Dummy traffic | None           | +20%             |

Total typical impact:

* Latency: +100ms
* Bandwidth: +40%

## Threat Scenarios

### Scenario 1: ISP Monitoring

**Attack:** ISP logs packet timing/sizes

**Protection:**

* Padding hides message sizes
* Constant traffic hides activity patterns
* TLS hides content

**Result:** ISP sees uniform encrypted traffic

### Scenario 2: Timing Correlation

**Attack:** Observer at entry and exit nodes correlates timing

**Protection:**

* Random delays break correlation
* Mixing shuffles order
* Multiple circuits in use

**Result:** Probabilistic, not certain, correlation

### Scenario 3: Traffic Confirmation

**Attack:** Adversary controls entry and exit nodes

**Protection:**

* Can't be fully prevented
* Mixing reduces confidence
* Circuit rotation limits window

**Result:** Attack succeeds with lower confidence

## Limitations

### What We Can't Prevent

1. **Global adversary** - If they see everything, correlation is possible
2. **Long-term analysis** - Patterns may emerge over time
3. **Active attacks** - Adversary can inject traffic to trace

### Recommendations

For high-security needs:

* Use VPN/Tor as additional layer
* Vary usage patterns
* Use multiple identities
* Air-gapped sensitive operations

## Comparison

| Feature            | KayakNet | Tor     | I2P        |
| ------------------ | -------- | ------- | ---------- |
| Padding            | Yes      | Limited | Yes        |
| Timing obfuscation | Yes      | No      | Yes        |
| Mixing             | Yes      | No      | Yes        |
| Dummy traffic      | Yes      | No      | No         |
| Circuit rotation   | Yes      | Yes     | Continuous |

## Measuring Protection

### Test Your Setup

```bash
# Capture traffic
tcpdump -i any port 4242 -w capture.pcap

# Analyze packet sizes
tshark -r capture.pcap -T fields -e frame.len | sort | uniq -c

# Should show mostly uniform sizes
```

### Verify Timing

All packets should have:

* Similar sizes (around 1024 bytes)
* Variable inter-arrival times
* No obvious patterns


# Proof of Work

KayakNet uses Proof-of-Work (PoW) as an anti-Sybil mechanism to prevent attackers from creating many fake nodes.

## What is Proof of Work?

PoW requires nodes to solve a computational puzzle before joining the network. This makes creating many identities expensive.

## How It Works

### Challenge-Response

```
New Node                    Existing Node
    │                             │
    │──────── Connect ───────────▶│
    │                             │
    │◀─────── Challenge ──────────│
    │   (random bytes, difficulty) │
    │                             │
    │   [Compute solution]        │
    │                             │
    │──────── Solution ──────────▶│
    │                             │
    │◀─────── Accepted ───────────│
    │   (join network)            │
    │                             │
```

### The Puzzle

Find a nonce such that:

```
HASH(challenge || nonce) has D leading zero bits
```

Where:

* `challenge` = Random 32 bytes from server
* `nonce` = 64-bit number found by node
* `D` = Difficulty (number of zero bits required)
* `HASH` = BLAKE2b-256

### Example

```
Challenge: 0x1234...abcd
Difficulty: 20 (20 leading zero bits)

Node tries:
  nonce=0: HASH = 0xf1a2... (0 zeros) ✗
  nonce=1: HASH = 0x8b3c... (0 zeros) ✗
  ...
  nonce=1485721: HASH = 0x00000f... (20 zeros) ✓

Solution found!
```

## Configuration

### Default Settings

| Parameter  | Value | Description        |
| ---------- | ----- | ------------------ |
| Difficulty | 20    | Leading zero bits  |
| Timeout    | 60s   | Max time to solve  |
| Expiry     | 5min  | Challenge validity |

### Adjusting Difficulty

```bash
# Lower difficulty (faster join, less protection)
./kayakd --pow-difficulty 16

# Higher difficulty (slower join, more protection)
./kayakd --pow-difficulty 24
```

### Time to Solve

| Difficulty | Average Time | Hardware   |
| ---------- | ------------ | ---------- |
| 16         | \~100ms      | Modern CPU |
| 20         | \~500ms      | Modern CPU |
| 24         | \~10s        | Modern CPU |
| 28         | \~2min       | Modern CPU |

## Security Properties

### What PoW Prevents

1. **Sybil Attacks** - Creating many fake nodes is expensive
2. **Spam** - Sending many messages requires many nodes
3. **Eclipse Attacks** - Surrounding target needs many nodes

### Cost Analysis

To create 1000 fake nodes:

* Difficulty 20: \~500 seconds of CPU time
* Difficulty 24: \~3 hours of CPU time
* Plus electricity cost

### What PoW Doesn't Prevent

1. **Well-funded attackers** - Can afford computation
2. **Botnet operators** - Free computing power
3. **ASIC attacks** - Specialized hardware

## Implementation Details

### Hash Function

Using BLAKE2b for:

* Speed (faster than SHA-256)
* Security (256-bit output)
* ASIC resistance (memory-hard)

### Nonce Search

```go
func SolvePow(challenge []byte, difficulty int) uint64 {
    target := big.NewInt(1)
    target.Lsh(target, uint(256-difficulty))
    
    var nonce uint64
    for {
        data := append(challenge, uint64ToBytes(nonce)...)
        hash := blake2b.Sum256(data)
        
        if new(big.Int).SetBytes(hash[:]).Cmp(target) < 0 {
            return nonce
        }
        nonce++
    }
}
```

### Verification

```go
func VerifyPow(challenge []byte, nonce uint64, difficulty int) bool {
    data := append(challenge, uint64ToBytes(nonce)...)
    hash := blake2b.Sum256(data)
    
    // Check leading zeros
    leadingZeros := countLeadingZeros(hash[:])
    return leadingZeros >= difficulty
}
```

## Challenge Management

### Challenge Generation

```go
func GenerateChallenge() []byte {
    challenge := make([]byte, 32)
    rand.Read(challenge)
    return challenge
}
```

### Challenge Storage

Challenges are stored with:

* Timestamp (for expiry)
* Node public key (to prevent reuse)
* One-time use flag

### Rate Limiting

Additional protection:

* Max 5 challenges per IP per minute
* Failed attempts increase cooldown
* IP banning for excessive failures

## Alternatives Considered

### Why Not Proof of Stake?

* Requires cryptocurrency
* Complexity for users
* Chicken-egg problem

### Why Not CAPTCHA?

* Requires human interaction
* Not automatable
* Centralized verification

### Why Not Trust on First Use?

* Initial join could be Sybil
* No cost to create nodes
* Easy to abuse

## Future Improvements

### Planned

1. **Adaptive Difficulty** - Adjust based on network size
2. **Memory-Hard PoW** - Better ASIC resistance
3. **Stake + PoW** - Hybrid approach

### Research

* Proof of Space-Time
* VDF (Verifiable Delay Functions)
* Social trust graphs


# Threat Model

This document describes the threats KayakNet is designed to protect against and its limitations.

## Adversary Types

### Local Passive Adversary

**Description**: Can observe traffic on your local network (ISP, network admin)

**Capabilities**:

* See encrypted traffic to KayakNet peers
* Log connection times and durations
* Measure traffic volumes

**KayakNet Protection**:

* ✅ TLS hides packet contents
* ✅ Onion routing hides destinations
* ✅ Traffic padding obscures patterns
* ⚠️ Can see you're using KayakNet

### Network Adversary

**Description**: Controls some nodes in the network

**Capabilities**:

* Observe traffic through their nodes
* Attempt correlation attacks
* Try to manipulate routing

**KayakNet Protection**:

* ✅ E2E encryption (content protected)
* ✅ 3-hop routing (partial view only)
* ✅ Peer scoring limits malicious nodes
* ⚠️ May see timing if on circuit

### Global Passive Adversary

**Description**: Nation-state level, can observe most internet traffic

**Capabilities**:

* Monitor traffic at multiple points
* Perform traffic correlation
* Long-term analysis

**KayakNet Protection**:

* ✅ Traffic padding and mixing
* ✅ Timing obfuscation
* ⚠️ Statistical correlation possible
* ❌ Cannot fully prevent with enough observation

### Active Adversary

**Description**: Can inject, modify, or drop traffic

**Capabilities**:

* Attempt man-in-the-middle
* Block connections
* Inject fake messages

**KayakNet Protection**:

* ✅ Signatures prevent forgery
* ✅ Authentication detects tampering
* ✅ Multiple paths for redundancy
* ⚠️ Can block (but not decrypt)

## Specific Attacks

### Sybil Attack

**Attack**: Create many fake nodes to dominate the network

**Protection**:

* Proof-of-Work required for new nodes
* Peer scoring deprioritizes suspicious behavior
* Diverse peer selection limits impact

**Residual Risk**: Well-resourced attacker could still create many nodes

### Eclipse Attack

**Attack**: Surround a target with malicious nodes

**Protection**:

* Diverse peer selection (by subnet, geography)
* Minimum connections from different sources
* Bootstrap node diversity

**Residual Risk**: Possible if attacker controls network infrastructure

### Timing Attack

**Attack**: Correlate message timing to identify sender/receiver

**Protection**:

* Random delays on forwarding
* Traffic mixing
* Dummy traffic generation

**Residual Risk**: Statistical correlation with enough observations

### Traffic Analysis

**Attack**: Analyze patterns to infer activity

**Protection**:

* Constant packet size
* Traffic padding
* Mixing pools
* Dummy traffic

**Residual Risk**: Long-term patterns may emerge

### Replay Attack

**Attack**: Replay captured messages

**Protection**:

* Nonce tracking
* Timestamp validation
* Sequence numbers

**Residual Risk**: None (fully mitigated)

### Denial of Service

**Attack**: Flood network to prevent legitimate use

**Protection**:

* Rate limiting
* Proof-of-Work
* Peer scoring and banning
* Distributed architecture

**Residual Risk**: Localized disruption possible

## Trust Model

### What You Trust

| Component      | Trust Level  | Justification                |
| -------------- | ------------ | ---------------------------- |
| Your device    | Full         | If compromised, all bets off |
| KayakNet code  | Verify       | Open source, auditable       |
| Bootstrap node | Initial only | Only for discovery           |
| Peers          | None         | Assumed adversarial          |
| Network        | None         | Assumed monitored            |

### What You Don't Trust

* Any single node
* Any network path
* Any external service
* Any other user's identity (unless verified)

## Security Assumptions

1. **Cryptography is sound** - Ed25519, X25519, ChaCha20 are secure
2. **Random numbers are random** - crypto/rand is properly seeded
3. **Your device isn't compromised** - No malware, keyloggers
4. **Implementation is correct** - No critical bugs

## Known Limitations

### Cannot Protect Against

1. **Compromised endpoints** - If your device is hacked
2. **Physical coercion** - "Rubber hose" cryptanalysis
3. **User error** - Revealing identity through behavior
4. **Quantum computers** - (Future: PQ upgrade planned)
5. **Infinite resources** - Global adversary with unlimited budget

### Metadata Leaks

Even with protection, some metadata exists:

* You're using KayakNet (connection to peers)
* Approximate activity level (traffic volume)
* General online times (connection presence)

### Operational Security

KayakNet protects network traffic, not:

* What you type (screen capture)
* What you view (shoulder surfing)
* What you save (disk forensics)
* What you share (if recipient reveals)

## Recommendations

### High Security Needs

1. Use dedicated device
2. Boot from USB (Tails-like)
3. Use VPN or Tor as additional layer
4. Never reveal real identity
5. Assume everything is monitored

### Standard Use

1. Keep software updated
2. Use strong device security
3. Don't mix anonymous/real identities
4. Clear history when done
5. Use private browsing mode

## Reporting Vulnerabilities

Found a security issue?

1. **Do NOT** disclose publicly
2. Email: <security@kayaknet.io>
3. PGP key available on keyserver
4. We respond within 48 hours
5. 90-day disclosure timeline


# Best Practices

Follow these guidelines to maximize your privacy and security on KayakNet.

## For All Users

### 1. Keep Software Updated

Always run the latest version:

```bash
./kayakd --auto-update
```

Updates include security patches and improvements.

### 2. Protect Your Identity Key

Your `identity.key` is your identity. If compromised, an attacker can impersonate you.

**Do:**

* Back up to encrypted storage
* Use strong device encryption
* Delete if identity is burned

**Don't:**

* Share with anyone
* Store in cloud unencrypted
* Use same identity for sensitive and non-sensitive activity

### 3. Use Strong Device Security

KayakNet can't protect you if your device is compromised:

* Full disk encryption
* Strong passwords/biometrics
* Keep OS and apps updated
* Don't install untrusted software

### 4. Separate Identities

Use different nodes/identities for:

* Personal vs sensitive activity
* Different personas
* Testing vs production

### 5. Be Careful What You Share

Even with encryption:

* Don't share real names, photos, locations
* Assume messages may be saved by recipients
* Be vague about identifying details

## For Chat Users

### Private Rooms

For sensitive discussions:

1. Create a private room
2. Only share name with trusted participants
3. Use unique room names (not guessable)

### Verifying Contacts

Before sensitive conversation:

1. Verify Node ID through separate channel
2. Use code words or shared secrets
3. Be suspicious of identity claims

### Message Hygiene

* Enable auto-delete for sensitive chats
* Clear history when done
* Don't quote sensitive messages

## For Marketplace Users

### For Buyers

1. **Check seller reputation** - Read reviews
2. **Start small** - Test with small orders first
3. **Use escrow** - Never pay outside escrow
4. **Verify addresses** - Double-check crypto addresses
5. **Document everything** - Save order details

### For Sellers

1. **Secure crypto wallets** - Hardware wallet recommended
2. **Accurate listings** - Prevent disputes
3. **Ship securely** - Don't reveal return address
4. **Good communication** - Respond to buyers
5. **Separate business wallet** - Don't mix with personal

### Escrow Safety

* Never release funds before confirming receipt
* Open disputes promptly if issues arise
* Provide evidence in disputes
* Don't accept payment outside system

## For High-Security Users

### Additional Layers

Consider adding:

* VPN (before KayakNet)
* Tor (as transport)
* Dedicated hardware
* Air-gapped devices

### Operational Security

* Use public WiFi (carefully)
* Vary your patterns
* Assume you're being watched
* Have plausible deniability

### Compartmentalization

* Different devices for different activities
* Don't cross-contaminate identities
* Separate digital footprints

## For Node Operators

### Secure Your Server

If running a public node:

* Minimal installed software
* Regular security updates
* Firewall configuration
* No unnecessary services

### Logging Policy

* Disable all logging
* Don't retain connection metadata
* Secure any necessary logs

### Physical Security

* Encrypted drives
* Secure facility
* Protection from seizure

## Common Mistakes

### Don't

❌ Use same identity across networks ❌ Connect to KayakNet without encryption ❌ Trust unverified contacts ❌ Store sensitive data unencrypted ❌ Use weak passwords ❌ Ignore software updates ❌ Share personal information ❌ Use KayakNet on compromised devices

### Do

✅ Keep software updated ✅ Use strong device security ✅ Verify contacts ✅ Separate identities ✅ Back up keys securely ✅ Use private rooms for sensitive chats ✅ Always use escrow ✅ Report security issues responsibly

## If Compromised

### Signs of Compromise

* Unexpected messages from your identity
* Account settings changed
* Unknown transactions
* Peers report strange behavior

### Recovery Steps

1. **Stop using compromised identity**
2. **Generate new identity** (delete `identity.key`)
3. **Notify trusted contacts** through other channels
4. **Review device security**
5. **Consider hardware replacement**

## Reporting Security Issues

Found a vulnerability?

1. **Don't disclose publicly**
2. Email: <security@kayaknet.io>
3. Include detailed reproduction steps
4. Allow 90 days for fix
5. Coordinate disclosure

We appreciate responsible disclosure!


# Chat System

KayakNet Chat provides end-to-end encrypted messaging with full privacy protection.

## Overview

* **End-to-End Encrypted** - Messages only readable by participants
* **Room-Based** - Public and private chat rooms
* **Direct Messages** - Private 1-on-1 conversations
* **Media Support** - Share images and files
* **Persistent History** - Messages saved locally
* **Real-Time** - Instant message delivery via PubSub

## Accessing Chat

1. Start your KayakNet node with `--proxy`
2. Configure browser proxy
3. Navigate to `http://chat.kyk`

Or access via `http://home.kyk` → Chat tab

## Features

### Public Rooms

Join rooms to chat with multiple people:

```
┌─────────────────────────────────────────┐
│  #general                          [3]  │
├─────────────────────────────────────────┤
│  alice: Hello everyone!                 │
│  bob: Hey alice, welcome!               │
│  you: Thanks for having me              │
├─────────────────────────────────────────┤
│  [Type a message...]           [Send]   │
└─────────────────────────────────────────┘
```

**Creating a Room:**

1. Click "NEW ROOM"
2. Enter room name
3. Optionally set as private
4. Share the room name with others

**Joining a Room:**

1. Enter room name in search
2. Click "JOIN"
3. Start chatting

### Direct Messages (DMs)

Private conversations between two users:

1. Click on a user's name
2. Select "Send Direct Message"
3. Or enter their Node ID manually
4. Messages are E2E encrypted

### Media Sharing

Share images in chat:

1. Click the image icon 📷
2. Select file from device
3. Image is encrypted and sent
4. Recipients see inline preview

### User Presence

See who's online:

* 🟢 Online - Active in last 5 minutes
* 🟡 Away - Inactive
* ⚫ Offline - Not connected

### Message Status

* ✓ Sent - Message left your node
* ✓✓ Delivered - Reached recipient's node
* 👁 Read - Recipient opened message

## Encryption

### Room Messages

Room messages use:

1. **Room Key** - Symmetric key shared by members
2. **ChaCha20-Poly1305** - AEAD encryption
3. **Gossip Protocol** - Distributed delivery

### Direct Messages

DMs use:

1. **X25519** - Key exchange with recipient
2. **ChaCha20-Poly1305** - Encrypt message
3. **Ed25519** - Sign for authenticity

### Key Rotation

Keys are rotated:

* Room keys: When members change
* DM keys: Per message (perfect forward secrecy)

## Commands

| Command       | Description         |
| ------------- | ------------------- |
| `/join #room` | Join a room         |
| `/leave`      | Leave current room  |
| `/nick name`  | Set display name    |
| `/dm user`    | Start DM with user  |
| `/members`    | List room members   |
| `/clear`      | Clear local history |
| `/help`       | Show all commands   |

## Privacy Features

### What's Protected

✅ Message content - E2E encrypted ✅ Sender identity - Pseudonymous ✅ Recipient identity - Hidden by onion routing ✅ Message timing - Obfuscated ✅ Chat history - Stored locally only

### What's Visible

⚠️ Room names - Public rooms are discoverable ⚠️ Online status - Can be disabled ⚠️ Message metadata - Size (padded), timestamp (fuzzy)

## Settings

Access settings via gear icon:

| Setting               | Description                  |
| --------------------- | ---------------------------- |
| Display Name          | Your visible name            |
| Show Online Status    | Toggle presence visibility   |
| Read Receipts         | Send read confirmations      |
| Message Notifications | Desktop notifications        |
| Auto-Delete           | Delete messages after X days |

## Technical Details

### Message Format

```json
{
  "id": "abc123...",
  "type": "room" | "dm",
  "room": "#general",
  "sender": "node_id",
  "sender_name": "alice",
  "content": "<encrypted>",
  "timestamp": 1234567890,
  "signature": "ed25519_sig"
}
```

### Delivery

Messages are delivered via:

1. **Direct** - If recipient is a peer
2. **DHT** - Store and forward
3. **Gossip** - Flood to room members

### Storage

Chat history is stored in:

```
./data/chat/
├── rooms/
│   └── #general.json
└── dms/
    └── <recipient_id>.json
```

## Troubleshooting

### Messages Not Sending

* Check node is connected (peer count > 0)
* Verify recipient is online or using DHT fallback
* Try restarting node

### Can't Join Room

* Room name is case-sensitive
* Room may be private
* Network connectivity issue

### History Not Loading

* Check data directory permissions
* May be syncing from network
* Try clearing cache

## Best Practices

1. **Use unique names** - Avoid impersonation
2. **Verify contacts** - Check Node IDs match
3. **Clear history** - When done with sensitive chats
4. **Private rooms** - For confidential discussions
5. **No personal info** - Keep anonymity intact


# Marketplace

The KayakNet Marketplace is a decentralized, anonymous platform for buying and selling goods and services using cryptocurrency.

## Overview

* **Fully Decentralized** - No central server, listings stored across DHT
* **Anonymous** - Sellers and buyers use pseudonyms
* **Crypto Payments** - Monero (XMR) and Zcash (ZEC) only
* **Escrow System** - Trustless transactions with dispute resolution

## Accessing the Marketplace

1. Start your KayakNet node with `--proxy`
2. Configure browser proxy
3. Navigate to `http://market.kyk` or `http://marketplace.kyk`

## For Buyers

### Browsing Listings

The marketplace shows all active listings from the network. You can:

* **Search** by keyword
* **Filter** by category
* **Sort** by price, date, or rating

### Making a Purchase

1. **Find a listing** - Browse or search
2. **Click "BUY"** - Opens purchase modal
3. **Choose currency** - XMR or ZEC
4. **Enter delivery info** - Encrypted for seller only
5. **Create order** - Generates escrow address
6. **Send payment** - To the escrow address shown
7. **Wait for confirmation** - Payment verified
8. **Seller ships** - You'll see tracking info
9. **Confirm receipt** - Releases funds to seller

### Order States

| State     | Description                     | Your Action           |
| --------- | ------------------------------- | --------------------- |
| CREATED   | Order created, awaiting payment | Send crypto           |
| FUNDED    | Payment received                | Wait for shipping     |
| SHIPPED   | Item shipped                    | Confirm when received |
| COMPLETED | You confirmed receipt           | None                  |
| DISPUTED  | Dispute opened                  | Provide evidence      |

### Disputes

If something goes wrong:

1. Click **"OPEN DISPUTE"** on your order
2. Explain the issue
3. Provide any evidence (screenshots, tracking info)
4. Moderators will review
5. Funds released to appropriate party

## For Sellers

### Creating a Listing

1. Go to Marketplace
2. Click **"CREATE LISTING"**
3. Fill in details:
   * **Title** - Clear, descriptive name
   * **Description** - Detailed product info
   * **Category** - Select appropriate category
   * **Price** - In USD equivalent
   * **Currency** - Accept XMR, ZEC, or both
   * **Images** - Upload product photos
   * **Stock** - Available quantity
   * **Ships From** - General location
   * **Ships To** - Regions you ship to
   * **Delivery Time** - Estimated days
4. **Enter your wallet addresses:**
   * Monero address (if accepting XMR)
   * Zcash address (if accepting ZEC)
5. Click **"PUBLISH"**

### Managing Sales

1. Go to **"MY LISTINGS"** tab
2. View your active listings
3. Check **"SALES"** tab for orders

### Fulfilling Orders

When you receive an order:

1. Order appears in **"SALES"** with state "FUNDED"
2. Prepare and ship the item
3. Click **"MARK AS SHIPPED"**
4. Enter tracking information (optional)
5. Wait for buyer to confirm receipt
6. Funds released to your wallet

### Seller Tips

* **Respond quickly** - Buyers expect fast communication
* **Accurate descriptions** - Avoid disputes
* **Good photos** - Multiple angles, clear quality
* **Competitive pricing** - Check similar listings
* **Build reputation** - Good reviews attract more buyers

## Escrow System

All transactions go through escrow:

```
┌──────────┐     ┌──────────┐     ┌──────────┐
│  Buyer   │────▶│  Escrow  │────▶│  Seller  │
│          │     │  Wallet  │     │          │
└──────────┘     └──────────┘     └──────────┘
   Sends            Holds           Receives
  Payment        Until Confirm       Payment
```

### Escrow Timeline

1. **Order Created** - Buyer has 24 hours to pay
2. **Payment Received** - Funds held in escrow
3. **Shipped** - Seller marks as shipped
4. **14-Day Window** - Buyer has 14 days to confirm or dispute
5. **Auto-Release** - If buyer doesn't respond, funds release after 14 days

### Fees

| Fee Type     | Amount                    |
| ------------ | ------------------------- |
| Platform Fee | 2.5%                      |
| Network Fee  | Variable (crypto network) |

## Categories

Available categories:

* Digital Goods
* Physical Goods
* Services
* Art & Collectibles
* Electronics
* Books & Media
* Other

## Best Practices

### For Buyers

* Check seller ratings and history
* Read descriptions carefully
* Use messaging to ask questions
* Confirm receipt promptly
* Leave honest reviews

### For Sellers

* Use strong pseudonyms
* Never reveal real identity
* Ship discreetly
* Keep records locally
* Use verified crypto addresses

## Prohibited Items

KayakNet does not allow:

* Weapons
* Illegal drugs
* Stolen goods
* Child exploitation material
* Human trafficking
* Terrorism-related items

Violations result in permanent bans and potential law enforcement reporting.

## Privacy Considerations

* Listings are public to all KayakNet users
* Buyer/seller identities are pseudonymous
* Delivery addresses are E2E encrypted
* Payment addresses are generated fresh per order
* Transaction history is not publicly linked


# Escrow System

The KayakNet Escrow System provides trustless cryptocurrency transactions for the marketplace.

## How It Works

```
┌─────────┐         ┌─────────┐         ┌─────────┐
│  Buyer  │         │ Escrow  │         │ Seller  │
└────┬────┘         └────┬────┘         └────┬────┘
     │                   │                   │
     │  1. Create Order  │                   │
     │──────────────────▶│                   │
     │                   │                   │
     │  2. Pay to Escrow │                   │
     │──────────────────▶│                   │
     │                   │                   │
     │                   │  3. Notify Seller │
     │                   │──────────────────▶│
     │                   │                   │
     │                   │  4. Ship Item     │
     │                   │◀──────────────────│
     │                   │                   │
     │  5. Receive Item  │                   │
     │◀ ─ ─ ─ ─ ─ ─ ─ ─ ─│                   │
     │                   │                   │
     │  6. Confirm       │                   │
     │──────────────────▶│                   │
     │                   │                   │
     │                   │  7. Release Funds │
     │                   │──────────────────▶│
     │                   │                   │
```

## Supported Cryptocurrencies

| Currency | Symbol | Privacy Level             |
| -------- | ------ | ------------------------- |
| Monero   | XMR    | Maximum (default private) |
| Zcash    | ZEC    | High (shielded addresses) |

### Why These Currencies?

* **Bitcoin** - Not supported (transparent blockchain)
* **Monero** - Ring signatures, stealth addresses
* **Zcash** - Zero-knowledge proofs

## Order States

| State       | Description                       | Duration       |
| ----------- | --------------------------------- | -------------- |
| `created`   | Order initiated, awaiting payment | 24 hours       |
| `funded`    | Payment received, held in escrow  | Until shipped  |
| `shipped`   | Seller marked as shipped          | 14 days        |
| `completed` | Buyer confirmed receipt           | Final          |
| `disputed`  | Dispute opened                    | Until resolved |
| `refunded`  | Funds returned to buyer           | Final          |
| `expired`   | Order timed out                   | Final          |

## Creating an Escrow

### For Buyers

1. **Click "BUY"** on a listing
2. **Select currency** (XMR or ZEC)
3. **Enter delivery info** (encrypted)
4. **Review order details**
5. **Click "CREATE ORDER"**

You'll receive:

* **Escrow Address** - Where to send payment
* **Amount** - Exact crypto amount
* **Expiry** - Time limit for payment

### Payment

Send the **exact** amount to the escrow address:

```
Amount: 0.00123456 XMR
Address: 44zFk33yjuwLLWSkj1i2JMiiNX9HifKinA8v...
Fee: 2.5% (included)
Expires: 24 hours
```

**Important:**

* Send the EXACT amount shown
* Include enough for network fees
* Use correct currency network

### Confirmation

After payment:

1. Transaction broadcasts to network
2. KayakNet monitors for confirmations
3. Required confirmations: 10 (XMR), 6 (ZEC)
4. State changes to "funded"
5. Seller notified automatically

## For Sellers

### When Order is Funded

1. Check **SALES** tab in marketplace
2. Order shows "FUNDED" state
3. Delivery info is decrypted

### Fulfilling Order

1. Ship the item
2. Click **"MARK AS SHIPPED"**
3. Enter tracking info (optional)
4. State changes to "shipped"

### Receiving Payment

* Buyer confirms → Funds released instantly
* 14 days pass → Funds auto-release
* Dispute → Wait for resolution

## Disputes

### Opening a Dispute

As a buyer, if something's wrong:

1. Go to order details
2. Click **"OPEN DISPUTE"**
3. Select reason:
   * Item not received
   * Item not as described
   * Wrong item
   * Damaged item
   * Other
4. Describe the issue
5. Upload evidence (photos, screenshots)

### Dispute Resolution

1. **Seller Response** - 48 hours to respond
2. **Evidence Review** - Both parties submit proof
3. **Mediation** - Network mediators review
4. **Decision** - Funds released or refunded

### Auto-Resolution

If no response:

* Buyer dispute → Refunded after 7 days
* Seller dispute → Released after 7 days

## Fees

| Fee Type     | Amount   | When                |
| ------------ | -------- | ------------------- |
| Platform Fee | 2.5%     | On completion       |
| Network Fee  | Variable | On each transaction |
| Dispute Fee  | 1%       | If dispute filed    |

Platform fees fund network operations and development.

## Security

### Key Protection

* Escrow wallets on bootstrap node
* Multi-signature for large amounts (coming)
* Cold storage for reserves

### Address Generation

Each order gets a unique address:

```
Order: #1234
├── XMR subaddress: unique per order
└── ZEC z-address: unique per order
```

### No Custodial Risk

* Funds held minimum time
* Released immediately on confirmation
* No pooling of buyer funds

## Manual Confirmation

If automatic payment detection fails:

1. Go to order details
2. Click **"MANUAL CONFIRM"**
3. Enter transaction ID (TXID)
4. Submit

This is useful when:

* Wallet sync is behind
* Network congestion
* Unusual transaction

## API Reference

### Create Escrow

```
POST /api/escrow/create
{
  "listing_id": "abc123",
  "currency": "XMR",
  "buyer_address": "44zFk...",
  "delivery_info": "encrypted..."
}
```

### Check Status

```
GET /api/escrow/status?id=abc123
```

### Mark Shipped

```
POST /api/escrow/ship
{
  "escrow_id": "abc123",
  "tracking_info": "optional"
}
```

### Confirm Receipt

```
POST /api/escrow/release
{
  "escrow_id": "abc123"
}
```

## Best Practices

### For Buyers

* Verify seller reputation first
* Pay exact amount shown
* Check address carefully
* Confirm receipt promptly
* Keep transaction records

### For Sellers

* Ship promptly when funded
* Provide tracking when possible
* Communicate with buyers
* Keep shipping receipts
* Respond to disputes quickly

## Troubleshooting

### Payment Not Detected

1. Verify you sent correct amount
2. Check transaction confirmed
3. Use manual confirmation
4. Wait for wallet sync

### Funds Not Released

1. Check if buyer confirmed
2. Wait for auto-release (14 days)
3. Contact support if stuck

### Order Expired

* Payment wasn't received in time
* Create new order
* Use faster confirmation next time


# Domain System (.kyk)

The KayakNet Naming System (KNS) provides decentralized domain registration for `.kyk` domains.

## Overview

* **Decentralized** - No ICANN, no central authority
* **Anonymous** - Register without identity
* **Permanent** - No annual renewal fees
* **Cryptographic** - Ownership proven by keys

## How It Works

```
┌─────────────┐     ┌─────────┐     ┌─────────────┐
│   Browser   │────▶│ KayakNet│────▶│   .kyk      │
│             │     │  Proxy  │     │  Resolver   │
└─────────────┘     └─────────┘     └─────────────┘
   home.kyk            DNS              Content
                     Lookup             Delivery
```

1. User enters `example.kyk`
2. KayakNet proxy intercepts request
3. Looks up domain in DHT
4. Routes to registered content
5. Displays in browser

## Registering a Domain

### Via Web Interface

1. Go to `http://domains.kyk`
2. Search for available domain
3. Click **"REGISTER"**
4. Set resolution target:
   * Node ID (serves from your node)
   * IP address (external server)
   * Content hash (static content)
5. Sign with your node key
6. Domain is yours!

### Via API

```bash
curl -X POST http://127.0.0.1:8080/api/domains/register \
  -d "domain=mysite.kyk" \
  -d "target=node_id:abc123..."
```

## Resolution Types

### 1. Node-Based

Domain resolves to your KayakNet node:

```
mysite.kyk → Your Node ID
```

* Serves content from your node
* Must keep node running
* Good for dynamic content

### 2. IP-Based

Domain resolves to an IP address:

```
mysite.kyk → 192.168.1.100:8080
```

* External server hosts content
* Works even if node offline
* Less anonymous

### 3. Content-Addressed

Domain resolves to content hash:

```
mysite.kyk → hash:abc123...
```

* Static content stored in DHT
* Always available
* Immutable

## Reserved Domains

These domains are reserved by the network:

| Domain            | Purpose             |
| ----------------- | ------------------- |
| `home.kyk`        | Homepage            |
| `chat.kyk`        | Chat interface      |
| `market.kyk`      | Marketplace         |
| `marketplace.kyk` | Marketplace (alias) |
| `domains.kyk`     | Domain registration |
| `network.kyk`     | Network stats       |

## Domain Rules

### Naming Rules

* Length: 3-63 characters
* Characters: `a-z`, `0-9`, `-`
* Cannot start/end with `-`
* Case insensitive (`MyDomain` = `mydomain`)

### Ownership

* First come, first served
* No expiration (permanent)
* Transferable via key exchange
* Cannot be revoked by network

### Updates

Update resolution at any time:

```bash
curl -X POST http://127.0.0.1:8080/api/domains/update \
  -d "domain=mysite.kyk" \
  -d "target=new_target"
```

Signed with your node key.

## Hosting Content

### Static Website

1. Create HTML files
2. Upload to your node
3. Register domain pointing to your node
4. Access via `yoursite.kyk`

### Dynamic Service

1. Run service on your node
2. Expose via internal port
3. Register domain
4. KayakNet routes requests to your service

## DNS vs KNS

| Feature      | Traditional DNS | KayakNet KNS  |
| ------------ | --------------- | ------------- |
| Authority    | ICANN           | None          |
| Registration | Requires ID     | Anonymous     |
| Cost         | Annual fee      | Free          |
| Takedown     | Possible        | Impossible    |
| Censorship   | Vulnerable      | Resistant     |
| Resolution   | Global          | KayakNet only |

## Technical Details

### Registration Record

```json
{
  "domain": "example.kyk",
  "owner": "node_public_key",
  "target": {
    "type": "node",
    "value": "node_id"
  },
  "registered_at": 1234567890,
  "signature": "ed25519_sig"
}
```

### Storage

Domain records stored in DHT:

* Key: `kns:example.kyk`
* Value: Registration record
* TTL: Permanent (refreshed by lookups)

### Resolution

1. Lookup `kns:example.kyk` in DHT
2. Verify signature matches owner
3. Extract target
4. Route request to target

## Subdomain Support

Subdomains work automatically:

```
blog.mysite.kyk → mysite.kyk handles routing
```

Your node can route subdomains however you want.

## Security

### Ownership Proof

* Only private key holder can update
* Signatures prevent forgery
* DHT replication prevents tampering

### Squatting Protection

None currently - first come, first served.

### Dispute Resolution

None - no authority to arbitrate.

## API Reference

### Register Domain

```
POST /api/domains/register
{
  "domain": "example.kyk",
  "target": "node_id:abc123"
}
```

### Lookup Domain

```
GET /api/domains/lookup?domain=example.kyk
```

### Update Domain

```
POST /api/domains/update
{
  "domain": "example.kyk",
  "target": "new_target"
}
```

### Transfer Domain

```
POST /api/domains/transfer
{
  "domain": "example.kyk",
  "new_owner": "new_public_key"
}
```

### List My Domains

```
GET /api/domains/mine
```

## Best Practices

1. **Secure your keys** - Losing keys = losing domains
2. **Use descriptive names** - Easy to remember
3. **Consider subdomains** - `shop.brand.kyk`, `blog.brand.kyk`
4. **Keep node running** - For node-based resolution
5. **Backup registrations** - Store proof of ownership

## Future Enhancements

* **Decentralized Marketplace** - Trade domains
* **Renewal Mechanism** - Optional periodic renewal
* **Multi-Signature** - Shared domain ownership
* **DNS Compatibility** - Bridge to traditional DNS


# File Sharing

KayakNet supports sharing files through the chat system and marketplace.

## Current Capabilities

### Images in Chat

Share images directly in chat:

1. Click the image icon in chat
2. Select file from device
3. Image is encrypted and sent
4. Recipient sees inline preview

**Supported formats:**

* JPEG/JPG
* PNG
* GIF
* WebP

**Size limit:** 5MB per image

### Marketplace Images

Listings can include product images:

* Main image (required)
* Up to 5 additional images
* Compressed for network efficiency

## How It Works

### Image Encoding

```
1. User selects image
   │
2. Image resized (max 1920x1080)
   │
3. Compressed to JPEG (quality 85%)
   │
4. Base64 encoded
   │
5. Encrypted with room/recipient key
   │
6. Sent via standard message
```

### Delivery

* Small images (<100KB): Inline in message
* Large images: Chunked delivery
* DHT: Store-and-forward for offline

## Planned Features

### Full File Sharing (Coming Soon)

Share any file type:

* Documents (PDF, TXT, etc.)
* Archives (ZIP, TAR)
* Media (video, audio)
* Any binary file

### Distributed Storage

Large files will be:

1. Split into chunks
2. Encrypted per-chunk
3. Distributed across DHT
4. Retrieved on demand

### BitTorrent Integration

For large files:

* Create KayakNet torrents
* Share magnet links in chat
* Download via P2P within network

## Security

### Encryption

All files are encrypted:

* Room files: Room symmetric key
* DM files: Recipient's public key
* Marketplace: Public (for listings)

### Metadata

File metadata is also protected:

* Filename (optional to share)
* Size (padded)
* Type (not leaked)

## Best Practices

1. **Don't share sensitive files** - Unless absolutely necessary
2. **Verify recipients** - Ensure intended audience
3. **Delete after use** - Clear from local storage
4. **Check file sizes** - Large files may be slow

## Limitations

### Current Limitations

| Limitation             | Value       |
| ---------------------- | ----------- |
| Max image size         | 5MB         |
| Max images per listing | 6           |
| File types             | Images only |

### Network Constraints

* Large files strain onion routing
* Slow on mobile connections
* DHT storage is temporary

## API

### Upload Image (Chat)

```
POST /api/chat/upload
Content-Type: multipart/form-data

file: <image data>
room: #general
```

### Get Image

```
GET /api/chat/file?id=file_abc123
```

### Marketplace Image

```
POST /api/market/create
{
  "images": ["data:image/jpeg;base64,..."]
}
```


# Overview

KayakNet exposes a REST API on port 8080 for programmatic access to all features.

## Base URL

```
http://127.0.0.1:8080
```

For remote access (if `--public-api` enabled):

```
http://<node-ip>:8080
```

## Authentication

Most endpoints don't require authentication - they operate on behalf of the local node.

For multi-user setups, API keys can be configured (see Configuration).

## Response Format

All responses are JSON:

```json
{
  "success": true,
  "data": { ... }
}
```

Error responses:

```json
{
  "error": "Error message"
}
```

## Endpoints Overview

| Category    | Prefix          | Description         |
| ----------- | --------------- | ------------------- |
| Network     | `/api/network/` | Node and peer info  |
| Chat        | `/api/chat/`    | Messaging           |
| Marketplace | `/api/market/`  | Listings and orders |
| Escrow      | `/api/escrow/`  | Payment management  |
| Domains     | `/api/domains/` | .kyk registration   |

## Network API

### Get Node Info

```
GET /api/network/info
```

Response:

```json
{
  "node_id": "abc123...",
  "name": "my-node",
  "version": "v0.1.28",
  "uptime": 3600,
  "peer_count": 12
}
```

### List Peers

```
GET /api/network/peers
```

Response:

```json
{
  "peers": [
    {
      "id": "peer1...",
      "name": "peer-name",
      "address": "1.2.3.4:4242",
      "latency_ms": 45,
      "connected_at": "2026-01-15T10:00:00Z"
    }
  ]
}
```

### Get Statistics

```
GET /api/network/stats
```

Response:

```json
{
  "messages_sent": 1234,
  "messages_received": 5678,
  "bytes_sent": 1048576,
  "bytes_received": 2097152,
  "circuits_created": 42,
  "dht_records": 256
}
```

## Chat API

### List Rooms

```
GET /api/chat/rooms
```

### Join Room

```
POST /api/chat/join
{
  "room": "#general"
}
```

### Send Message (Room)

```
POST /api/chat/send
{
  "room": "#general",
  "content": "Hello world!"
}
```

### Send Direct Message

```
POST /api/chat/dm
{
  "recipient": "node_id",
  "content": "Private message"
}
```

### Get History

```
GET /api/chat/history?room=#general&limit=50
```

## Marketplace API

### List Listings

```
GET /api/market/listings?category=all&sort=newest&page=1
```

### Get Listing

```
GET /api/market/listing?id=abc123
```

### Create Listing

```
POST /api/market/create
{
  "title": "Product Name",
  "description": "Product description",
  "category": "digital",
  "price": 99.99,
  "currency": "XMR",
  "seller_xmr_address": "44zFk...",
  "stock": 10,
  "ships_from": "US",
  "ships_to": ["US", "EU"],
  "images": ["data:image/png;base64,..."]
}
```

### Update Listing

```
POST /api/market/update
{
  "id": "abc123",
  "price": 89.99,
  "stock": 5
}
```

### Delete Listing

```
POST /api/market/delete
{
  "id": "abc123"
}
```

### Search

```
GET /api/market/search?q=keyword&category=digital&min_price=10&max_price=100
```

## Escrow API

### Create Escrow

```
POST /api/escrow/create
{
  "listing_id": "abc123",
  "currency": "XMR",
  "buyer_address": "44zFk...",
  "delivery_info": "encrypted delivery details"
}
```

Response:

```json
{
  "success": true,
  "escrow_id": "esc123",
  "order_id": "ord456",
  "payment_address": "escrow_address...",
  "amount": 0.5,
  "currency": "XMR",
  "expires_at": "2026-01-16T10:00:00Z"
}
```

### Get Status

```
GET /api/escrow/status?id=esc123
```

### Mark Shipped

```
POST /api/escrow/ship
{
  "escrow_id": "esc123",
  "tracking_info": "TRACK123"
}
```

### Confirm Receipt

```
POST /api/escrow/release
{
  "escrow_id": "esc123"
}
```

### Open Dispute

```
POST /api/escrow/dispute
{
  "escrow_id": "esc123",
  "reason": "Item not received",
  "description": "Details..."
}
```

### My Orders

```
GET /api/escrow/my?type=buying
GET /api/escrow/my?type=selling
```

## Domain API

### Register

```
POST /api/domains/register
{
  "domain": "mysite.kyk",
  "target": "node_id:abc123"
}
```

### Lookup

```
GET /api/domains/lookup?domain=mysite.kyk
```

### Update

```
POST /api/domains/update
{
  "domain": "mysite.kyk",
  "target": "new_target"
}
```

### My Domains

```
GET /api/domains/mine
```

## Error Codes

| Code | Meaning                          |
| ---- | -------------------------------- |
| 200  | Success                          |
| 400  | Bad Request (invalid parameters) |
| 401  | Unauthorized                     |
| 403  | Forbidden                        |
| 404  | Not Found                        |
| 429  | Rate Limited                     |
| 500  | Internal Server Error            |
| 503  | Service Unavailable              |

## Rate Limits

| Endpoint        | Limit       |
| --------------- | ----------- |
| General         | 100 req/min |
| Chat Send       | 30 req/min  |
| Escrow Create   | 10 req/min  |
| Domain Register | 5 req/min   |

## WebSocket API

Real-time updates via WebSocket:

```javascript
const ws = new WebSocket('ws://127.0.0.1:8080/ws');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data.type, data.payload);
};
```

### Event Types

| Type                | Description         |
| ------------------- | ------------------- |
| `chat.message`      | New chat message    |
| `chat.dm`           | New direct message  |
| `market.listing`    | New/updated listing |
| `escrow.update`     | Escrow state change |
| `peer.connected`    | New peer connected  |
| `peer.disconnected` | Peer disconnected   |

## SDK Examples

### Python

```python
import requests

class KayakNet:
    def __init__(self, base_url='http://127.0.0.1:8080'):
        self.base = base_url
    
    def get_info(self):
        return requests.get(f'{self.base}/api/network/info').json()
    
    def send_message(self, room, content):
        return requests.post(f'{self.base}/api/chat/send', 
            data={'room': room, 'content': content}).json()

kn = KayakNet()
print(kn.get_info())
```

### JavaScript

```javascript
class KayakNet {
  constructor(baseUrl = 'http://127.0.0.1:8080') {
    this.base = baseUrl;
  }

  async getInfo() {
    const res = await fetch(`${this.base}/api/network/info`);
    return res.json();
  }

  async sendMessage(room, content) {
    const res = await fetch(`${this.base}/api/chat/send`, {
      method: 'POST',
      body: new URLSearchParams({ room, content })
    });
    return res.json();
  }
}
```


# Network API


# Chat API


# Marketplace API


# Escrow API


# Domain API


# Building from Source

This guide explains how to build KayakNet from source code.

## Prerequisites

### Required

* **Go 1.21+** - [Download Go](https://go.dev/dl/)
* **Git** - [Download Git](https://git-scm.com/)

### Optional

* **Make** - For build automation
* **Docker** - For containerized builds

## Clone Repository

```bash
git clone https://github.com/KayakNet/KayakNet.git
cd KayakNet
```

## Build

### Simple Build

```bash
go build -o kayakd ./cmd/kayakd/
```

### Optimized Build

```bash
go build -ldflags="-s -w" -o kayakd ./cmd/kayakd/
```

Flags:

* `-s` - Strip symbol table
* `-w` - Strip DWARF debugging info

Result: \~40% smaller binary

### Cross-Compilation

**Windows (from Linux/macOS):**

```bash
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o kayakd.exe ./cmd/kayakd/
```

**Linux (from Windows/macOS):**

```bash
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o kayakd ./cmd/kayakd/
```

**macOS (from Linux/Windows):**

```bash
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o kayakd ./cmd/kayakd/
```

**ARM (Raspberry Pi):**

```bash
GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o kayakd-arm64 ./cmd/kayakd/
```

## Build All Platforms

```bash
# Build script
#!/bin/bash
VERSION="v0.1.28"

# Linux
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o kayakd-${VERSION}-linux-amd64 ./cmd/kayakd/

# Windows  
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o kayakd-${VERSION}-windows-amd64.exe ./cmd/kayakd/

# macOS
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o kayakd-${VERSION}-darwin-amd64 ./cmd/kayakd/

# Create archives
zip kayakd-${VERSION}-linux-amd64.zip kayakd-${VERSION}-linux-amd64
zip kayakd-${VERSION}-windows-amd64.zip kayakd-${VERSION}-windows-amd64.exe
zip kayakd-${VERSION}-darwin-amd64.zip kayakd-${VERSION}-darwin-amd64
```

## Project Structure

```
KayakNet/
├── cmd/
│   └── kayakd/           # Main binary entry point
│       └── main.go
├── internal/
│   ├── chat/             # Chat system
│   ├── config/           # Configuration
│   ├── crypto/           # Cryptographic operations
│   ├── dht/              # Distributed hash table
│   ├── e2e/              # End-to-end encryption
│   ├── escrow/           # Escrow system
│   ├── identity/         # Node identity
│   ├── market/           # Marketplace
│   ├── names/            # .kyk domain system
│   ├── network/          # Core networking
│   ├── onion/            # Onion routing
│   ├── pow/              # Proof of work
│   └── pubsub/           # Publish-subscribe
├── pkg/
│   └── protocol/         # Wire protocol
├── android/              # Android app source
├── go.mod
├── go.sum
└── README.md
```

## Dependencies

View dependencies:

```bash
go mod graph
```

Update dependencies:

```bash
go get -u ./...
go mod tidy
```

## Testing

### Run Tests

```bash
go test ./...
```

### Run with Coverage

```bash
go test -cover ./...
```

### Run Specific Package

```bash
go test ./internal/chat/...
```

### Verbose Output

```bash
go test -v ./...
```

## Linting

### Install golangci-lint

```bash
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
```

### Run Linter

```bash
golangci-lint run
```

## Docker Build

### Dockerfile

```dockerfile
FROM golang:1.21-alpine AS builder

WORKDIR /app
COPY . .
RUN go build -ldflags="-s -w" -o kayakd ./cmd/kayakd/

FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/kayakd /usr/local/bin/
ENTRYPOINT ["kayakd"]
```

### Build Image

```bash
docker build -t kayaknet/kayakd:latest .
```

### Run Container

```bash
docker run -d \
  --name kayaknet \
  -p 4242:4242 \
  -p 8080:8080 \
  -p 8118:8118 \
  -v kayaknet-data:/data \
  kayaknet/kayakd:latest \
  --bootstrap 203.161.33.237:4242 --proxy
```

## Build Flags

| Flag                     | Description                    |
| ------------------------ | ------------------------------ |
| `-s`                     | Strip symbol table             |
| `-w`                     | Strip DWARF info               |
| `-X main.Version=v1.0.0` | Set version variable           |
| `-race`                  | Enable race detector (testing) |

### Set Version at Build

```bash
go build -ldflags="-s -w -X main.Version=v1.0.0" -o kayakd ./cmd/kayakd/
```

## Troubleshooting

### "go: command not found"

Install Go and add to PATH:

```bash
export PATH=$PATH:/usr/local/go/bin
```

### "cannot find package"

Download dependencies:

```bash
go mod download
```

### CGO Issues

Disable CGO for static builds:

```bash
CGO_ENABLED=0 go build ...
```

### Large Binary Size

Use ldflags and UPX:

```bash
go build -ldflags="-s -w" -o kayakd ./cmd/kayakd/
upx --best kayakd
```


# Contributing

Thank you for your interest in contributing to KayakNet! This guide will help you get started.

## Ways to Contribute

### Code

* Fix bugs
* Implement features
* Improve performance
* Write tests

### Documentation

* Fix typos and errors
* Add examples
* Improve clarity
* Translate to other languages

### Testing

* Run beta releases
* Report bugs
* Test edge cases
* Verify fixes

### Community

* Help users in chat
* Answer questions
* Share KayakNet
* Write tutorials

## Getting Started

### 1. Fork the Repository

```bash
# Fork on GitHub, then:
git clone https://github.com/YOUR_USERNAME/KayakNet.git
cd KayakNet
```

### 2. Set Up Development Environment

```bash
# Install Go 1.21+
go version

# Download dependencies
go mod download

# Build
go build ./cmd/kayakd/
```

### 3. Create a Branch

```bash
git checkout -b feature/your-feature-name
```

## Code Style

### Go Code

Follow standard Go conventions:

* `gofmt` for formatting
* `golint` for style
* Clear variable names
* Comments for exported functions

```go
// Good
func ProcessMessage(msg *Message) error {
    if msg == nil {
        return errors.New("message is nil")
    }
    // Process...
    return nil
}

// Bad
func pm(m *Message) error {
    // ...
}
```

### Commit Messages

Use clear, descriptive commit messages:

```
feat: add support for Zcash escrow

- Implement Zcash wallet integration
- Add z-address generation
- Update escrow API for ZEC

Closes #123
```

Prefixes:

* `feat:` - New feature
* `fix:` - Bug fix
* `docs:` - Documentation
* `test:` - Tests
* `refactor:` - Code refactoring
* `perf:` - Performance improvement
* `chore:` - Maintenance

## Pull Request Process

### 1. Before Submitting

* [ ] Code compiles without errors
* [ ] Tests pass (`go test ./...`)
* [ ] Linter passes (`golangci-lint run`)
* [ ] Documentation updated if needed
* [ ] Commit messages are clear

### 2. Submit PR

1. Push your branch
2. Open PR on GitHub
3. Fill out the template
4. Wait for review

### 3. Review Process

* Maintainers will review
* Address feedback
* Make requested changes
* PR will be merged when approved

## Testing

### Running Tests

```bash
# All tests
go test ./...

# With coverage
go test -cover ./...

# Specific package
go test ./internal/chat/...

# Verbose
go test -v ./...
```

### Writing Tests

```go
func TestProcessMessage(t *testing.T) {
    tests := []struct {
        name    string
        input   *Message
        wantErr bool
    }{
        {"valid message", &Message{...}, false},
        {"nil message", nil, true},
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            err := ProcessMessage(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("got error %v, wantErr %v", err, tt.wantErr)
            }
        })
    }
}
```

## Security Contributions

### Responsible Disclosure

If you find a security vulnerability:

1. **DO NOT** open a public issue
2. Email: <security@kayaknet.io>
3. Include detailed reproduction steps
4. Wait for acknowledgment

### Security-Related PRs

* Mark PR as security-related
* Request private review
* Don't discuss details publicly until fixed

## Documentation

### Where to Document

| Type         | Location            |
| ------------ | ------------------- |
| API docs     | `api/*.md`          |
| Features     | `features/*.md`     |
| Architecture | `architecture/*.md` |
| Security     | `security/*.md`     |

### Documentation Style

* Clear and concise
* Include examples
* Use code blocks for commands
* Keep up to date with code

## Community Guidelines

### Be Respectful

* Treat everyone with respect
* No harassment or discrimination
* Constructive criticism only

### Be Collaborative

* Help others learn
* Share knowledge
* Welcome newcomers

### Be Professional

* Stay on topic
* No spam or self-promotion
* Respect privacy

## Questions?

* Join `#dev` on `chat.kyk`
* Open a GitHub discussion
* Check existing issues

Thank you for contributing to KayakNet!


# Android App

This guide covers building and contributing to the KayakNet Android app.

## Overview

The Android app provides:

* Full KayakNet connectivity
* Chat (rooms and DMs)
* Marketplace browsing
* Domain lookup
* Native Android experience

## Tech Stack

* **Language:** Kotlin
* **UI:** Jetpack Compose
* **Architecture:** MVVM
* **Networking:** Ktor HTTP client
* **Build:** Gradle

## Project Structure

```
android/
├── app/
│   ├── src/main/
│   │   ├── java/com/kayaknet/
│   │   │   ├── MainActivity.kt
│   │   │   ├── KayakNetApp.kt
│   │   │   ├── ui/
│   │   │   │   ├── screens/
│   │   │   │   │   ├── HomeScreen.kt
│   │   │   │   │   ├── ChatScreen.kt
│   │   │   │   │   ├── MarketScreen.kt
│   │   │   │   │   └── DomainsScreen.kt
│   │   │   │   └── theme/
│   │   │   │       └── Theme.kt
│   │   │   └── network/
│   │   │       └── KayakNetClient.kt
│   │   ├── res/
│   │   │   ├── drawable/
│   │   │   └── values/
│   │   └── AndroidManifest.xml
│   └── build.gradle.kts
├── build.gradle.kts
└── settings.gradle.kts
```

## Building

### Prerequisites

* Android Studio Hedgehog (2023.1.1) or later
* JDK 17
* Android SDK (API 34)

### Build Steps

```bash
# Clone repository
git clone https://github.com/KayakNet/KayakNet.git
cd KayakNet/android

# Build debug APK
./gradlew assembleDebug

# Output: app/build/outputs/apk/debug/app-debug.apk
```

### Build Release APK

```bash
# Create signing key (first time only)
keytool -genkey -v -keystore kayaknet.keystore \
  -alias kayaknet -keyalg RSA -keysize 2048 -validity 10000

# Build release
./gradlew assembleRelease

# Output: app/build/outputs/apk/release/app-release.apk
```

## GitHub Actions

Automated builds via GitHub Actions:

```yaml
# .github/workflows/android.yml
name: Build Android APK

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
      - name: Build APK
        run: |
          cd android
          chmod +x gradlew
          ./gradlew assembleDebug
      - name: Upload APK
        uses: actions/upload-artifact@v4
        with:
          name: kayaknet-debug
          path: android/app/build/outputs/apk/debug/app-debug.apk
```

## Architecture

### Network Communication

The app communicates with the KayakNet backend via HTTP:

```kotlin
class KayakNetClient(private val baseUrl: String) {
    private val client = HttpClient(CIO) {
        install(ContentNegotiation) {
            json()
        }
    }
    
    suspend fun getChatRooms(): List<ChatRoom> {
        return client.get("$baseUrl/api/chat/rooms").body()
    }
    
    suspend fun sendMessage(room: String, content: String) {
        client.post("$baseUrl/api/chat/send") {
            setBody(FormDataContent(Parameters.build {
                append("room", room)
                append("content", content)
            }))
        }
    }
}
```

### Bootstrap Connection

```kotlin
val bootstrapUrl = "http://203.161.33.237:8080"
val client = KayakNetClient(bootstrapUrl)
```

### UI with Jetpack Compose

```kotlin
@Composable
fun ChatScreen(viewModel: ChatViewModel) {
    val messages by viewModel.messages.collectAsState()
    
    Column {
        LazyColumn(modifier = Modifier.weight(1f)) {
            items(messages) { msg ->
                MessageItem(msg)
            }
        }
        MessageInput(onSend = { viewModel.sendMessage(it) })
    }
}
```

## Features Implementation

### Chat

* Rooms list from `/api/chat/rooms`
* Messages from `/api/chat/history`
* Send via POST `/api/chat/send`
* Polling for updates (1s interval)

### Marketplace

* Listings from `/api/market/listings`
* Details from `/api/market/listing?id=X`
* Categories and search supported

### Domains

* Lookup via `/api/domains/lookup?domain=X`
* My domains from `/api/domains/mine`

## Testing

### Unit Tests

```bash
./gradlew test
```

### Instrumented Tests

```bash
./gradlew connectedAndroidTest
```

### Manual Testing

1. Install APK on device/emulator
2. Ensure KayakNet node is running
3. App should connect automatically

## Known Issues

### No Local Node

The Android app connects to the bootstrap node, not a local node. This means:

* Relies on bootstrap availability
* No local proxy mode
* Limited offline capability

### Future: Embedded Node

Planned: Embed Go node using gomobile:

```bash
gomobile bind -target=android ./pkg/mobile
```

## Contributing

### Code Style

* Kotlin conventions
* Compose best practices
* Clear naming
* Comments for complex logic

### Pull Requests

1. Fork repository
2. Create feature branch
3. Test on multiple devices
4. Submit PR with description

## Troubleshooting

### Build Fails

```bash
# Clean and rebuild
./gradlew clean
./gradlew assembleDebug
```

### Connection Issues

* Verify bootstrap is running
* Check internet connectivity
* Try with VPN if needed

### UI Issues

* Check Compose version compatibility
* Verify Material3 components
* Test on different screen sizes


# Testing

This guide covers testing KayakNet during development and for quality assurance.

## Test Types

### Unit Tests

Test individual functions and components:

```bash
# Run all unit tests
go test ./...

# With verbose output
go test -v ./...

# Specific package
go test ./internal/chat/...

# With coverage
go test -cover ./...
```

### Integration Tests

Test component interactions:

```bash
# Run integration tests
go test -tags=integration ./...
```

### End-to-End Tests

Test complete user flows (manual):

1. Start bootstrap node
2. Start test nodes
3. Perform actions
4. Verify results

## Running Tests

### Quick Test

```bash
go test ./...
```

### Full Test Suite

```bash
# With race detection
go test -race ./...

# With coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
```

### Specific Tests

```bash
# Single test function
go test -run TestChatSendMessage ./internal/chat/...

# Test pattern
go test -run "TestChat.*" ./internal/chat/...
```

## Test Coverage

### Generate Report

```bash
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
open coverage.html
```

### Coverage Goals

| Package | Target |
| ------- | ------ |
| crypto  | 90%+   |
| e2e     | 85%+   |
| chat    | 80%+   |
| market  | 80%+   |
| escrow  | 85%+   |

## Writing Tests

### Test Structure

```go
func TestFunctionName(t *testing.T) {
    // Arrange
    input := setupTestData()
    
    // Act
    result, err := FunctionUnderTest(input)
    
    // Assert
    if err != nil {
        t.Errorf("unexpected error: %v", err)
    }
    if result != expected {
        t.Errorf("got %v, want %v", result, expected)
    }
}
```

### Table-Driven Tests

```go
func TestEncrypt(t *testing.T) {
    tests := []struct {
        name      string
        plaintext string
        key       []byte
        wantErr   bool
    }{
        {"valid input", "hello", validKey, false},
        {"empty input", "", validKey, false},
        {"nil key", "hello", nil, true},
        {"short key", "hello", shortKey, true},
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            _, err := Encrypt([]byte(tt.plaintext), tt.key)
            if (err != nil) != tt.wantErr {
                t.Errorf("Encrypt() error = %v, wantErr %v", err, tt.wantErr)
            }
        })
    }
}
```

### Mocking

```go
type MockPeerStore struct {
    peers map[string]*Peer
}

func (m *MockPeerStore) GetPeer(id string) *Peer {
    return m.peers[id]
}

func TestWithMock(t *testing.T) {
    mock := &MockPeerStore{
        peers: map[string]*Peer{
            "peer1": {ID: "peer1", Name: "Test"},
        },
    }
    
    // Use mock in tests...
}
```

## Manual Testing

### Local Network Setup

```bash
# Terminal 1: Bootstrap
./kayakd --listen 0.0.0.0:4242 --name bootstrap

# Terminal 2: Node A
./kayakd --bootstrap 127.0.0.1:4242 --proxy --name nodeA --listen 0.0.0.0:4243

# Terminal 3: Node B  
./kayakd --bootstrap 127.0.0.1:4242 --name nodeB --listen 0.0.0.0:4244
```

### Test Scenarios

#### Chat Test

1. Node A joins room `#test`
2. Node B joins room `#test`
3. Node A sends message
4. Verify Node B receives message

#### Marketplace Test

1. Node A creates listing
2. Node B searches for listing
3. Verify listing appears
4. Node B creates order
5. Verify escrow created

#### Domain Test

1. Node A registers `test.kyk`
2. Node B looks up `test.kyk`
3. Verify resolution

## Browser Testing

### Setup

1. Start node with `--proxy`
2. Configure browser proxy to `127.0.0.1:8118`
3. Navigate to `http://home.kyk`

### Test Cases

| Feature     | Test                  |
| ----------- | --------------------- |
| Homepage    | Loads correctly       |
| Chat        | Send/receive messages |
| Marketplace | Browse listings       |
| Domains     | Search works          |
| Escrow      | Create order          |

## Performance Testing

### Load Test

```bash
# Using hey (install: go install github.com/rakyll/hey@latest)
hey -n 1000 -c 50 http://127.0.0.1:8080/api/network/info
```

### Benchmark Tests

```go
func BenchmarkEncrypt(b *testing.B) {
    key := generateKey()
    data := make([]byte, 1024)
    
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        Encrypt(data, key)
    }
}
```

Run benchmarks:

```bash
go test -bench=. ./internal/crypto/...
```

## CI/CD Integration

### GitHub Actions

```yaml
name: Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.21'
      - run: go test -race -coverprofile=coverage.out ./...
      - uses: codecov/codecov-action@v4
        with:
          files: coverage.out
```

## Debugging Tests

### Verbose Output

```bash
go test -v ./...
```

### With Logging

```go
func TestWithLogging(t *testing.T) {
    t.Log("Starting test")
    // ...
    t.Logf("Result: %v", result)
}
```

### Debugging Failures

```bash
# Run specific failing test
go test -v -run TestFailingFunction ./path/to/package

# With debug output
KAYAKNET_DEBUG=1 go test -v ./...
```


# Roadmap

This document outlines the development roadmap for KayakNet.

## Current Status (v0.1.x)

### Completed Features

✅ **Core Network**

* P2P connectivity
* Bootstrap node support
* DHT-based peer discovery
* Proof-of-Work anti-Sybil
* Peer scoring and rate limiting

✅ **Security**

* 3-hop onion routing
* End-to-end encryption
* Traffic analysis resistance
* TLS 1.3 transport

✅ **Chat**

* Public rooms
* Direct messages
* E2E encryption
* Media sharing
* Persistent history

✅ **Marketplace**

* Create/browse listings
* Categories and search
* Seller profiles
* Order management

✅ **Escrow**

* Monero support
* Zcash support
* Order state management
* Manual confirmation

✅ **Domains**

* .kyk registration
* Node-based resolution
* Persistent storage

✅ **Clients**

* Windows binary
* Linux binary
* macOS binary
* Android app

***

## Phase 2: Enhanced Security (Q2 2026)

### Multi-Signature Escrow

* 2-of-3 multisig for large transactions
* Reduced single-point-of-failure risk
* Arbitrator key for disputes

### Post-Quantum Cryptography

* CRYSTALS-Kyber for key exchange
* CRYSTALS-Dilithium for signatures
* Hybrid mode for backward compatibility

### Hardware Key Support

* YubiKey integration
* Ledger wallet support
* TPM-backed keys

### Improved Traffic Analysis Resistance

* Adaptive dummy traffic
* Variable circuit lifetimes
* Path diversity requirements

***

## Phase 3: Scalability (Q3 2026)

### Network Optimization

* Multiple bootstrap nodes
* Geographic peer selection
* Connection pooling
* Message batching

### DHT Improvements

* Faster lookups
* Better replication
* Reduced bandwidth

### Mobile Optimization

* Battery-efficient routing
* Partial sync mode
* Push notifications (privacy-preserving)

***

## Phase 4: Ecosystem (Q4 2026)

### $KNT Token

* Native cryptocurrency
* Governance voting
* Staking rewards
* Transaction fee payments

### Decentralized Governance

* Protocol upgrade voting
* Feature proposals
* Community treasury

### Developer Tools

* SDK for Python, JavaScript, Go
* Plugin system
* Service templates

### Additional Features

* File sharing (torrents over KayakNet)
* Voice/video calls (E2E encrypted)
* Decentralized storage
* Smart contracts (simple scripting)

***

## Phase 5: Maturity (2027)

### Security Audit

* Professional code audit
* Bug bounty program
* Formal verification (critical paths)

### Performance

* Sub-second message delivery
* 10K+ concurrent users per node
* Global distribution

### Compliance Tools

* Optional identity verification
* Merchant tools
* Tax reporting (opt-in)

### Documentation

* Comprehensive technical docs
* Video tutorials
* Localization (multiple languages)

***

## Long-Term Vision

### Federation

* Bridge to other anonymous networks
* Tor/I2P transport option
* Inter-network messaging

### Mainstream Adoption

* Browser extension
* Desktop app (Electron)
* iOS app
* Integration with existing platforms

### Research

* Zero-knowledge marketplace
* Reputation without identity
* Quantum-resistant DHT

***

## Community Input

We welcome suggestions! Please:

1. Open an issue on GitHub
2. Join the discussion on `chat.kyk`
3. Submit pull requests

***

## Version History

| Version | Date     | Highlights               |
| ------- | -------- | ------------------------ |
| v0.1.0  | Jan 2026 | Initial release          |
| v0.1.10 | Jan 2026 | Auto-update, persistence |
| v0.1.20 | Jan 2026 | Escrow improvements      |
| v0.1.28 | Jan 2026 | Buyer/seller role fixes  |

***

## How to Contribute

### Code

* Fork repository
* Create feature branch
* Submit pull request
* Follow code style

### Testing

* Run beta releases
* Report bugs
* Suggest improvements

### Documentation

* Fix typos
* Add examples
* Translate

### Community

* Help new users
* Moderate chat
* Share KayakNet

***

## Disclaimer

This roadmap is aspirational and subject to change based on:

* Community feedback
* Technical challenges
* Resource availability
* Security considerations

No timeline is guaranteed. Security always takes priority over features.


# FAQ

## General

### What is KayakNet?

KayakNet is a privacy-first, decentralized peer-to-peer network that provides anonymous communication, a cryptocurrency marketplace, and decentralized domain names.

### Is KayakNet legal?

KayakNet itself is legal software. Like any tool, it can be used for legal or illegal purposes. We do not condone illegal activity.

### Is KayakNet like Tor?

Similar concept, different implementation. Both use onion routing for anonymity. KayakNet also includes built-in chat, marketplace, and domain system.

### Who created KayakNet?

KayakNet is developed by an anonymous team committed to privacy rights.

### Is KayakNet open source?

Yes, KayakNet is released under the MIT License.

***

## Installation

### What operating systems are supported?

* Windows 10+
* Linux (kernel 4.x+)
* macOS 10.14+
* Android 8+

### Do I need to install anything else?

No, KayakNet is a single binary with no dependencies.

### Why does Windows Defender flag it?

Unsigned Go binaries often trigger false positives. You can safely allow it or build from source.

### Can I run multiple nodes?

Yes, use different ports: `--listen 0.0.0.0:4243`

***

## Network

### How do I connect to KayakNet?

Run the binary with `--bootstrap 203.161.33.237:4242`

### How many peers should I have?

At least 3-5 peers for good connectivity. More is better.

### Why is my connection slow?

Onion routing adds latency (\~150-300ms). This is the cost of privacy.

### Can I run a bootstrap node?

Yes! Contact us to be added to the default list.

### How much bandwidth does it use?

Varies by activity. Typical: 100MB-1GB per day.

***

## Privacy & Security

### Is KayakNet anonymous?

Yes, to the extent cryptographically possible. Your IP is hidden via onion routing.

### Can my ISP see I'm using KayakNet?

They can see encrypted traffic to KayakNet peers, but not content or destinations.

### Is traffic analysis possible?

KayakNet has traffic analysis resistance, but a global adversary could still correlate.

### Are my messages encrypted?

Yes, all messages are end-to-end encrypted.

### Can KayakNet staff read my messages?

No. There is no "staff" and no backdoors. Only recipients can read messages.

### What if I lose my identity key?

You'll appear as a new user. There's no recovery. Back up your keys!

***

## Chat

### How do I join a chat room?

Go to `chat.kyk` and enter the room name, or use `/join #roomname`.

### Are chat rooms public?

Public rooms are visible to all. Create private rooms for confidential chats.

### How long are messages stored?

Messages are stored locally on your device. Set auto-delete for sensitive chats.

### Can I send images?

Yes, images are encrypted and shared via the chat interface.

***

## Marketplace

### How do I buy something?

1. Find listing
2. Click Buy
3. Pay to escrow address
4. Wait for delivery
5. Confirm receipt

### What cryptocurrencies are accepted?

Monero (XMR) and Zcash (ZEC) only. Bitcoin is not supported due to lack of privacy.

### What are the fees?

2.5% platform fee on completed transactions.

### How long do I have to pay?

24 hours after creating an order.

### What if I don't receive my item?

Open a dispute within 14 days. Funds will be held pending resolution.

### How do sellers get paid?

After buyer confirms receipt, or 14 days after shipping (auto-release).

***

## Escrow

### How does escrow work?

Buyer pays to a holding address. Funds are released to seller after buyer confirms receipt.

### What if payment isn't detected?

Use "Manual Confirm" and provide the transaction ID.

### Can I cancel an order?

Before payment: yes. After payment: only via dispute.

### What happens in a dispute?

Both parties provide evidence. Mediators decide who gets the funds.

***

## Domains

### What are .kyk domains?

Decentralized domain names that work within KayakNet.

### How much do domains cost?

Free to register (first come, first served).

### Do domains expire?

No, domains are permanent once registered.

### Can someone take my domain?

Not if you have the private key. No authority can reassign domains.

### Do .kyk domains work outside KayakNet?

No, they only resolve through the KayakNet proxy.

***

## Technical

### What language is KayakNet written in?

Go (Golang).

### What cryptography does it use?

* Ed25519 (signatures)
* X25519 (key exchange)
* ChaCha20-Poly1305 (encryption)
* BLAKE2b (hashing)

### How does peer discovery work?

Kademlia-based DHT, similar to BitTorrent.

### What is the message size limit?

1MB for regular messages, larger files via chunking.

### Can I use KayakNet programmatically?

Yes, there's a REST API on port 8080.

***

## Troubleshooting

### Node won't start

* Check if port 4242 is in use
* Try a different port with `--listen`
* Check firewall settings

### Can't connect to peers

* Verify bootstrap address
* Check internet connection
* Wait a few minutes for discovery

### Browser shows "Proxy Error"

* Ensure node is running
* Check proxy settings (127.0.0.1:8118)
* Try restarting the node

### Messages not sending

* Check peer count (need at least 1)
* Verify recipient is online or DHT is working
* Check for error messages in console

### Escrow payment not detected

* Wait for confirmations (10 XMR, 6 ZEC)
* Use manual confirmation with TXID
* Verify you sent exact amount

***

## Contributing

### How can I help?

* Report bugs
* Submit code
* Improve documentation
* Help other users
* Run a node

### Where do I report bugs?

Open an issue on GitHub or report in `chat.kyk`.

### Is there a bounty program?

Coming soon. Security vulnerabilities should be reported privately.

***

## Contact

### How do I get support?

* Join `#help` on `chat.kyk`
* Open GitHub issue
* Check this FAQ

### How do I stay updated?

* Watch GitHub repository
* Join `#announcements` on `chat.kyk`
* Follow development roadmap


# Glossary

## A

### AEAD

**Authenticated Encryption with Associated Data** - Encryption that provides both confidentiality and integrity. KayakNet uses ChaCha20-Poly1305.

### Anti-Sybil

Protection mechanisms against Sybil attacks where an attacker creates many fake identities.

## B

### Bootstrap Node

A well-known node that helps new nodes join the network and discover peers.

### BLAKE2b

A fast cryptographic hash function used in KayakNet for various operations.

## C

### ChaCha20-Poly1305

A modern symmetric encryption algorithm providing both encryption and authentication.

### Circuit

A path through multiple nodes used for onion routing. KayakNet uses 3-hop circuits.

## D

### DHT

**Distributed Hash Table** - A decentralized key-value store used for peer discovery and data storage. KayakNet uses a Kademlia-based DHT.

### DM

**Direct Message** - A private message between two users.

## E

### E2E

**End-to-End Encryption** - Encryption where only the communicating parties can read the messages.

### Ed25519

A digital signature algorithm used for identity and message signing.

### Escrow

A financial arrangement where a third party holds funds until conditions are met.

## F

### Forward Secrecy

A property ensuring that past communications cannot be decrypted even if long-term keys are compromised.

## G

### Gossip Protocol

A communication protocol where nodes share information with random peers, eventually reaching all nodes.

## H

### HKDF

**HMAC-based Key Derivation Function** - Used to derive encryption keys from shared secrets.

### Hop

One node in an onion routing circuit. KayakNet uses 3 hops by default.

## I

### Identity Key

The Ed25519 key pair that identifies a node. The public key derives the Node ID.

## K

### Kademlia

A DHT protocol that provides efficient peer lookup using XOR distance metric.

### KNS

**KayakNet Naming System** - The decentralized domain system for .kyk domains.

### KNT

**KayakNet Token** - The planned native cryptocurrency for KayakNet (not yet implemented).

## M

### Monero (XMR)

A privacy-focused cryptocurrency supported for marketplace payments.

### Mixing

The process of combining messages from multiple sources to obscure their origins.

## N

### Node

A computer running KayakNet software, participating in the network.

### Node ID

A unique identifier derived from the node's public key, used for routing and identification.

## O

### Onion Routing

A technique for anonymous communication where messages are encrypted in layers, like an onion.

## P

### Padding

Adding random data to messages to make them uniform size, preventing size-based traffic analysis.

### Peer

Another node that your node is directly connected to.

### PubSub

**Publish-Subscribe** - A messaging pattern where messages are published to topics and delivered to subscribers.

### PoW

**Proof-of-Work** - A computational challenge that must be solved to perform certain actions, used for anti-Sybil protection.

## R

### Ring Signature

A signature that could have been created by any member of a group, providing anonymity. Used in Monero.

## S

### Shielded Address

A Zcash address that hides sender, receiver, and amount using zero-knowledge proofs.

### SOCKS5

A proxy protocol supported by KayakNet for browser connections.

### Sybil Attack

An attack where a malicious actor creates many fake identities to gain disproportionate influence.

## T

### TLS 1.3

**Transport Layer Security** - The protocol used to encrypt connections between nodes.

### Traffic Analysis

Techniques to learn about communications by analyzing metadata like timing, size, and patterns.

## W

### Wallet

Software or hardware that manages cryptocurrency keys and transactions.

## X

### X25519

An elliptic curve Diffie-Hellman key exchange algorithm used for establishing shared secrets.

### XMR

The ticker symbol for Monero cryptocurrency.

## Z

### ZEC

The ticker symbol for Zcash cryptocurrency.

### Zero-Knowledge Proof

A cryptographic method to prove knowledge of something without revealing it. Used in Zcash.

### .kyk

The domain extension for KayakNet's naming system (e.g., `example.kyk`).


# Changelog

All notable changes to KayakNet are documented here.

## \[v0.1.28] - 2026-01-15

### Fixed

* Escrow buyer/seller role detection
* "Mark as Shipped" now only visible to sellers
* "Confirm Received" now only visible to buyers
* Added `is_buyer` and `is_seller` flags to escrow status API

### Added

* `/api/escrow/all` endpoint for viewing all escrows

***

## \[v0.1.27] - 2026-01-15

### Added

* Manual payment confirmation for escrow
* "MANUAL CONFIRM" button in order details
* Sellers can confirm payment with transaction ID

***

## \[v0.1.26] - 2026-01-14

### Fixed

* Seller cryptocurrency address storage in listings
* Escrow creation includes seller payout addresses
* Version string updated to prevent auto-update issues

### Added

* `SellerXMRAddress` and `SellerZECAddress` fields to listings

***

## \[v0.1.25] - 2026-01-14

### Fixed

* Escrow forwarding to bootstrap node
* Local nodes now properly forward escrow requests
* Crypto wallet configuration detection

***

## \[v0.1.20] - 2026-01-14

### Fixed

* Listing sync across network
* Order persistence

### Added

* `/api/sync-listing` endpoint

***

## \[v0.1.19] - 2026-01-14

### Added

* Listing synchronization from bootstrap

### Fixed

* Cached listing data issues

***

## \[v0.1.18] - 2026-01-14

### Fixed

* Android app sync issues
* Logo display on all pages
* Production-grade Android features

***

## \[v0.1.17] - 2026-01-13

### Added

* Android production-grade app
* Full sync with desktop/web

***

## \[v0.1.14] - 2026-01-12

### Added

* Domain registration UI
* `/api/domains/register` endpoint

***

## \[v0.1.13] - 2026-01-12

### Added

* Persistence across all features
* Chat, market, domains, escrow all persist

***

## \[v0.1.12] - 2026-01-12

### Added

* Auto-update mechanism
* Checks GitHub releases on startup
* Downloads and applies updates automatically

***

## \[v0.1.11] - 2026-01-12

### Added

* Chat persistence
* Messages saved to disk

***

## \[v0.1.10] - 2026-01-11

### Added

* DM routing through bootstrap
* Better direct message delivery

***

## \[v0.1.9] - 2026-01-11

### Fixed

* E2E encryption for general chat
* Message propagation issues

***

## \[v0.1.8] - 2026-01-11

### Fixed

* `e2e.UnmarshalEnvelope` bug
* Cross-node message visibility

***

## \[v0.1.6] - 2026-01-10

### Fixed

* JavaScript syntax errors in chat UI
* Clarified mic access requires HTTPS

***

## \[v0.1.5] - 2026-01-10

### Added

* Domain mappings: `chat.kyk`, `market.kyk`, etc.
* Multiple domain aliases

***

## \[v0.1.4] - 2026-01-10

### Enhanced

* Chat frontend improvements
* Better UI/UX

***

## \[v0.1.3] - 2026-01-09

### Added

* Real Monero integration
* Real Zcash integration
* Bootstrap crypto processing

***

## \[v0.1.2] - 2026-01-08

### Added

* Escrow system
* Monero/Zcash simulated support

***

## \[v0.1.1] - 2026-01-07

### Added

* Bootstrap escrow support
* Centralized crypto processing

***

## \[v0.1.0] - 2026-01-05

### Initial Release

* Core P2P network
* Onion routing (3 hops)
* End-to-end encryption
* Chat rooms and DMs
* Marketplace with listings
* .kyk domain system
* Browser proxy (HTTP/SOCKS5)
* Traffic analysis resistance
* Proof-of-Work anti-Sybil
* Windows, Linux, macOS binaries
* Android app

***

## Versioning

KayakNet follows [Semantic Versioning](https://semver.org/):

* **MAJOR**: Incompatible API changes
* **MINOR**: New features, backward compatible
* **PATCH**: Bug fixes, backward compatible

Current: `v0.1.x` (Beta)


