bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

View File

@@ -9,11 +9,11 @@ This directory contains Docker-based testing infrastructure for simulating cross
│ p2p-test-network │
│ (172.28.0.0/16) │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
│ │172.28.1.│ │ :8081 │ │ :8082 │ │
│ │ :8080 │ └─────────┘ └─────────┘ │
│ └─────────┘ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
│ │172.28.1.│ │ :8081 │ │ :8082 │ │
│ │ :8080 │ └─────────┘ └─────────┘ │
│ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
```

View File

@@ -0,0 +1,64 @@
# Dockerfile for MWP NAT Traversal Testing
#
# Build context should be the project root (zig-p2p/)
# Run: docker build -f docker-tests/nat/Dockerfile -t mwp-peer .
FROM debian:bookworm-slim AS builder
# Install dependencies
RUN apt-get update && apt-get install -y \
curl \
xz-utils \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Install Zig
ARG ZIG_VERSION=0.15.2
ARG TARGETARCH
RUN set -ex; \
case "${TARGETARCH}" in \
amd64) ZIG_ARCH="x86_64" ;; \
arm64) ZIG_ARCH="aarch64" ;; \
*) echo "Unsupported architecture: ${TARGETARCH}"; exit 1 ;; \
esac; \
curl -fsSL "https://ziglang.org/download/${ZIG_VERSION}/zig-${ZIG_ARCH}-linux-${ZIG_VERSION}.tar.xz" -o /tmp/zig.tar.xz && \
tar -xJf /tmp/zig.tar.xz -C /opt && \
mv /opt/zig-${ZIG_ARCH}-linux-${ZIG_VERSION} /opt/zig && \
rm /tmp/zig.tar.xz
ENV PATH="/opt/zig:${PATH}"
# Copy source and build
WORKDIR /build
COPY src ./src
COPY build.zig ./build.zig
COPY examples ./examples
COPY docker-tests ./docker-tests
COPY tests ./tests
# Build all targets (needed for install step)
RUN zig build && \
cp zig-out/bin/mwp-demo /build/mwp-demo && \
ls -la /build/mwp-demo
# =============================================================================
# Runtime Stage
# =============================================================================
FROM debian:bookworm-slim AS runtime
RUN apt-get update && apt-get install -y \
ca-certificates \
iproute2 \
iputils-ping \
net-tools \
tcpdump \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /build/mwp-demo /usr/local/bin/mwp-demo
RUN chmod +x /usr/local/bin/mwp-demo
WORKDIR /app
# Default command shows help
CMD ["mwp-demo", "--help"]

113
docker-tests/nat/README.md Normal file
View File

@@ -0,0 +1,113 @@
# NAT Traversal Testing for MWP
This directory contains a Docker-based NAT simulation environment for testing the Mutual Witness Protocol (MWP) NAT traversal capabilities.
## Network Topology
```
┌─────────────────── public (10.200.0.0/24) ───────────────────┐
│ │
│ bootstrap (10.200.0.10) - Rendezvous/DHT node │
│ │ │
│ ┌────┴────┐ ┌─────────┐ │
│ │ nat1 │ 10.200.0.2 │ nat2 │ 10.200.0.3 │
│ │ gateway │ │ gateway │ │
│ └────┬────┘ └────┬────┘ │
└───────┼────────────────────────────────────┼─────────────────┘
│ │
│ NAT (MASQUERADE) │ NAT (MASQUERADE)
│ │
┌───────┴───────┐ ┌───────┴───────┐
│ private_alice │ │ private_bob │
│ (10.201.0.0) │ │ (10.202.0.0) │
│ │ │ │
│ alice │ │ bob │
│ 10.201.0.10 │ │ 10.202.0.10 │
└───────────────┘ └───────────────┘
```
## Quick Start
```bash
# Run the full NAT traversal test
./run-nat-test.sh
```
## Manual Testing
```bash
# Build the image
docker-compose build
# Start NAT gateways
docker-compose up -d nat1 nat2
# Start bootstrap node
docker-compose up -d bootstrap
# Get bootstrap DHT ID
docker-compose logs bootstrap | grep "DHT Node ID"
# Start peers with the DHT ID
export BOOTSTRAP_DHT_ID=<id-from-above>
docker-compose up alice bob
# View logs
docker-compose logs -f alice bob
```
## What This Tests
1. **DHT Discovery**: Can Alice and Bob find each other's publications through the DHT when they're behind different NATs?
2. **IP Reflection**: Does the bootstrap node correctly report the NAT's public IP:port to each peer?
3. **Hole Punching**: Can Alice and Bob establish a direct UDP connection through both NATs?
## Expected Results
### DHT Discovery: Should PASS
Both peers should be able to publish and find each other's MWP publications via the DHT through the bootstrap node.
### Hole Punching: May FAIL
Docker's iptables-based NAT typically implements **symmetric NAT** or **port-restricted cone NAT**, which makes UDP hole punching difficult or impossible without:
- A relay server (TURN)
- Protocol extensions for symmetric NAT traversal
This is expected behavior and matches real-world scenarios where some NAT types require relay fallback.
## NAT Types
| NAT Type | Hole Punch Success Rate |
|----------|------------------------|
| Full Cone | ~100% |
| Restricted Cone | ~90% |
| Port-Restricted Cone | ~60% |
| Symmetric | ~10% (needs prediction) |
Docker's NAT is typically port-restricted cone or symmetric.
## Troubleshooting
### "Cannot connect to bootstrap"
- Check that nat1/nat2 gateways are running and healthy
- Verify routing tables in alice/bob containers:
```bash
docker-compose exec alice ip route
```
### "DHT FIND_VALUE not found"
- Ensure bootstrap node has the publications stored
- Check that both peers are using the correct bootstrap DHT ID
- Verify `p2p.update()` is being called (see CLAUDE.md)
### "Hole punch timeout"
- This is expected for symmetric NAT
- The DHT discovery should still work
- Future: implement relay fallback
## Files
- `Dockerfile` - Builds the mwp-demo binary
- `docker-compose.yml` - Defines the network topology
- `run-nat-test.sh` - Automated test script

View File

@@ -0,0 +1,287 @@
# NAT Traversal Test Environment for MWP
#
# Network Topology:
#
# ┌─────────────────── public (10.200.0.0/24) ──────────────────┐
# │ │
# │ bootstrap (10.200.0.10) │
# │ │ │
# │ ┌────┴────┐ ┌─────────┐ │
# │ │ nat1 │ 10.200.0.2 │ nat2 │ 10.200.0.3│
# │ │ gateway │ │ gateway │ │
# │ └────┬────┘ └────┬────┘ │
# └───────┼────────────────────────────────────┼────────────────┘
# │ │
# ┌───────┴───────┐ ┌────────┴──────┐
# │ private_alice │ │ private_bob │
# │ (10.201.0.0) │ │ (10.202.0.0) │
# │ │ │ │
# │ alice │ │ bob │
# │ 10.201.0.10 │ │ 10.202.0.10 │
# └───────────────┘ └───────────────┘
#
# Usage:
# docker-compose up --build
# docker-compose logs -f alice bob
networks:
public:
driver: bridge
ipam:
config:
- subnet: 10.200.0.0/24
private_alice:
driver: bridge
internal: false
ipam:
config:
- subnet: 10.201.0.0/24
private_bob:
driver: bridge
internal: false
ipam:
config:
- subnet: 10.202.0.0/24
services:
# ==========================================================================
# NAT Gateway 1 (for Alice)
# ==========================================================================
nat1:
image: alpine:latest
container_name: nat1
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
public:
ipv4_address: 10.200.0.2
private_alice:
ipv4_address: 10.201.0.2
command:
- sh
- -c
- |
echo 'Installing iptables...'
apk add --no-cache iptables
echo 'Setting up NAT gateway 1...'
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush existing rules
iptables -t nat -F
iptables -F FORWARD
# NAT: Masquerade traffic from private network going to public
iptables -t nat -A POSTROUTING -s 10.201.0.0/24 -o eth0 -j MASQUERADE
# Allow forwarding
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
echo 'NAT1 gateway ready'
iptables -t nat -L -n -v
# Keep container running
sleep infinity
healthcheck:
test: ["CMD", "sh", "-c", "iptables -t nat -L >/dev/null 2>&1"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# NAT Gateway 2 (for Bob)
# ==========================================================================
nat2:
image: alpine:latest
container_name: nat2
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
public:
ipv4_address: 10.200.0.3
private_bob:
ipv4_address: 10.202.0.2
command:
- sh
- -c
- |
echo 'Installing iptables...'
apk add --no-cache iptables
echo 'Setting up NAT gateway 2...'
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush existing rules
iptables -t nat -F
iptables -F FORWARD
# NAT: Masquerade traffic from private network going to public
iptables -t nat -A POSTROUTING -s 10.202.0.0/24 -o eth0 -j MASQUERADE
# Allow forwarding
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
echo 'NAT2 gateway ready'
iptables -t nat -L -n -v
# Keep container running
sleep infinity
healthcheck:
test: ["CMD", "sh", "-c", "iptables -t nat -L >/dev/null 2>&1"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# Bootstrap Node (on public network - acts as rendezvous point)
# This node just runs MWP and serves DHT requests - it doesn't connect to anyone
# ==========================================================================
bootstrap:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: bootstrap
networks:
public:
ipv4_address: 10.200.0.10
command:
- sh
- -c
- |
echo '=========================================='
echo 'Starting bootstrap node on public network'
echo 'IP: 10.200.0.10, Port: 18100'
echo '=========================================='
mwp-demo --name bootstrap --port 18100 --deterministic
healthcheck:
test: ["CMD", "sh", "-c", "netstat -tuln | grep 18100"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# Alice (behind NAT1)
# ==========================================================================
alice:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: alice
cap_add:
- NET_ADMIN
depends_on:
nat1:
condition: service_healthy
bootstrap:
condition: service_healthy
networks:
private_alice:
ipv4_address: 10.201.0.20
environment:
- BOOTSTRAP_DHT_ID=${BOOTSTRAP_DHT_ID:-}
command:
- sh
- -c
- |
echo '=========================================='
echo 'Configuring Alice network'
echo '=========================================='
# Set default route through NAT gateway
ip route del default 2>/dev/null || true
ip route add default via 10.201.0.2
echo 'Alice routing table:'
ip route
echo 'Testing connectivity to bootstrap...'
ping -c 2 10.200.0.10 || echo 'Ping failed (may be blocked)'
echo 'Waiting for bootstrap node...'
sleep 5
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
echo 'ERROR: BOOTSTRAP_DHT_ID not set!'
exit 1
fi
echo '=========================================='
echo 'Starting Alice'
echo 'Bootstrap: 10.200.0.10:18100'
echo "DHT ID: $BOOTSTRAP_DHT_ID"
echo '=========================================='
mwp-demo --name alice --port 18100 --deterministic --connect-to bob \
--bootstrap 10.200.0.10:18100 \
--dht-id "$BOOTSTRAP_DHT_ID"
# ==========================================================================
# Bob (behind NAT2)
# ==========================================================================
bob:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: bob
cap_add:
- NET_ADMIN
depends_on:
nat2:
condition: service_healthy
bootstrap:
condition: service_healthy
networks:
private_bob:
ipv4_address: 10.202.0.20
environment:
- BOOTSTRAP_DHT_ID=${BOOTSTRAP_DHT_ID:-}
command:
- sh
- -c
- |
echo '=========================================='
echo 'Configuring Bob network'
echo '=========================================='
# Set default route through NAT gateway
ip route del default 2>/dev/null || true
ip route add default via 10.202.0.2
echo 'Bob routing table:'
ip route
echo 'Testing connectivity to bootstrap...'
ping -c 2 10.200.0.10 || echo 'Ping failed (may be blocked)'
echo 'Waiting for network setup...'
sleep 8
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
echo 'ERROR: BOOTSTRAP_DHT_ID not set!'
exit 1
fi
echo '=========================================='
echo 'Starting Bob'
echo 'Bootstrap: 10.200.0.10:18100'
echo "DHT ID: $BOOTSTRAP_DHT_ID"
echo '=========================================='
mwp-demo --name bob --port 18100 --deterministic --connect-to alice \
--bootstrap 10.200.0.10:18100 \
--dht-id "$BOOTSTRAP_DHT_ID"

186
docker-tests/nat/run-nat-test.sh Executable file
View File

@@ -0,0 +1,186 @@
#!/bin/bash
#
# NAT Traversal Test Script for MWP
#
# This script sets up a simulated NAT environment using Docker and tests
# whether two peers (Alice and Bob) behind different NATs can discover
# each other and establish a connection.
#
# Network topology:
# - Bootstrap node on public network (172.20.0.10)
# - Alice behind NAT1 (172.18.0.10 -> 172.20.0.2)
# - Bob behind NAT2 (172.19.0.10 -> 172.20.0.3)
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
cleanup() {
log_info "Cleaning up..."
cd "$SCRIPT_DIR"
docker compose down --volumes --remove-orphans 2>/dev/null || true
}
trap cleanup EXIT
# =============================================================================
# Main
# =============================================================================
log_info "=========================================="
log_info "MWP NAT Traversal Test"
log_info "=========================================="
cd "$SCRIPT_DIR"
# Step 1: Build the Docker image
log_info "Building MWP Docker image..."
docker compose build --quiet
# Step 2: Start NAT gateways first
log_info "Starting NAT gateways..."
docker compose up -d nat1 nat2
sleep 2
# Step 3: Start bootstrap node
log_info "Starting bootstrap node..."
docker compose up -d bootstrap
sleep 3
# Step 4: Get bootstrap node's DHT ID
log_info "Getting bootstrap node DHT ID..."
BOOTSTRAP_DHT_ID=""
for i in {1..10}; do
BOOTSTRAP_DHT_ID=$(docker compose logs bootstrap 2>/dev/null | grep -o "DHT Node ID: [a-f0-9]*" | head -1 | cut -d' ' -f4)
if [ -n "$BOOTSTRAP_DHT_ID" ]; then
break
fi
log_info "Waiting for bootstrap DHT ID... (attempt $i/10)"
sleep 2
done
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
log_error "Failed to get bootstrap DHT ID"
docker compose logs bootstrap
exit 1
fi
log_success "Bootstrap DHT ID: $BOOTSTRAP_DHT_ID"
# Step 5: Export DHT ID and start Alice and Bob
export BOOTSTRAP_DHT_ID
log_info "Starting Alice and Bob with bootstrap DHT ID..."
# Start Alice and Bob
docker compose up -d alice bob
# Step 6: Monitor for results (60 second timeout)
log_info "Monitoring for NAT traversal results..."
log_info "(Timeout: 60 seconds)"
TIMEOUT=60
START_TIME=$(date +%s)
ALICE_FOUND=false
BOB_FOUND=false
HOLE_PUNCH_SUCCESS=false
while true; do
CURRENT_TIME=$(date +%s)
ELAPSED=$((CURRENT_TIME - START_TIME))
if [ $ELAPSED -ge $TIMEOUT ]; then
log_warn "Timeout reached after ${TIMEOUT}s"
break
fi
# Check Alice's logs
if ! $ALICE_FOUND; then
if docker compose logs alice 2>/dev/null | grep -q "FOUND PEER PUBLICATION"; then
log_success "Alice found Bob's publication!"
ALICE_FOUND=true
fi
fi
# Check Bob's logs
if ! $BOB_FOUND; then
if docker compose logs bob 2>/dev/null | grep -q "FIND_VALUE.*found=true"; then
log_success "Bob found Alice's publication via DHT!"
BOB_FOUND=true
fi
fi
# Check for hole punch success
if docker compose logs alice bob 2>/dev/null | grep -q "Hole punch.*success\|Connection established"; then
log_success "Hole punch succeeded!"
HOLE_PUNCH_SUCCESS=true
break
fi
# Check for hole punch failure (expected in some NAT types)
if docker compose logs bob 2>/dev/null | grep -q "Hole punch failed"; then
log_warn "Hole punch failed (may be expected for symmetric NAT)"
break
fi
sleep 2
done
# Step 7: Print results
echo ""
log_info "=========================================="
log_info "Test Results"
log_info "=========================================="
echo ""
if $ALICE_FOUND && $BOB_FOUND; then
log_success "DHT Discovery: PASSED"
echo " - Alice found Bob's publication"
echo " - Bob found Alice's publication"
else
log_error "DHT Discovery: FAILED"
if ! $ALICE_FOUND; then echo " - Alice did NOT find Bob"; fi
if ! $BOB_FOUND; then echo " - Bob did NOT find Alice"; fi
fi
echo ""
if $HOLE_PUNCH_SUCCESS; then
log_success "Hole Punch: PASSED"
else
log_warn "Hole Punch: FAILED (expected for symmetric NAT)"
echo " - Docker's iptables NAT is typically symmetric/port-restricted"
echo " - This makes hole punching difficult without relay"
fi
echo ""
log_info "=========================================="
# Step 8: Show detailed logs on failure
if ! $ALICE_FOUND || ! $BOB_FOUND; then
echo ""
log_info "Alice logs (last 30 lines):"
docker compose logs --tail=30 alice
echo ""
log_info "Bob logs (last 30 lines):"
docker compose logs --tail=30 bob
fi
# Exit with appropriate code
if $ALICE_FOUND && $BOB_FOUND; then
exit 0
else
exit 1
fi