2.5 I2P GARLIC ROUTING & EEPSITES 10 REAL-TIME EXAMPLES

Explore unidirectional I2P tunnels, multi-clove Garlic encryption, Kademlia NetDB LeaseSets, Base32/Base64 .i2p destinations, and SAMv3 bridge automation.

🧄 How I2P's Packet-Switched Garlic Overlay Differs from Tor

The Invisible Internet Project (I2P) is a fully distributed, packet-switched anonymous overlay network designed primarily for internal, self-contained services (Eepsites) rather than clearnet outproxying. Instead of bidirectional circuits, I2P separates traffic into unidirectional Inbound and Outbound tunnels, bundles multiple encrypted messages ("cloves") inside a single Garlic message, and replaces centralized directory authorities with a Kademlia-based distributed NetDB.

1. Example 1: Tor Onion Routing vs. I2P Garlic Routing Architecture
Compare structural design differences between Tor's circuit-switched onion routing and I2P's packet-switched unidirectional garlic tunnel model.
Python (tor_vs_i2p_matrix.py)
comparison = [
    ("Primary Focus",      "Clearnet outproxying + .onion", "Internal .i2p services (Eepsites)"),
    ("Tunnel Direction",   "Bidirectional 3-hop circuits",  "Separate Outbound & Inbound tunnels"),
    ("Directory Model",    "9 Hardcoded V3 Authorities",    "Distributed Kademlia NetDB (Floodfills)"),
    ("Message Bundling",   "Single stream cell per packet", "Multiple encrypted 'cloves' per Garlic"),
    ("Tunnel Lifetime",    "~10 minutes (circuit reuse)",   "10 minutes fixed rotation"),
    ("Transport Layer",    "TLS over TCP",                  "NTCP2 (TCP) & SSU2 (UDP)")
]

for feature, tor_val, i2p_val in comparison:
    print(f"{feature:<18} | Tor: {tor_val:<31} | I2P: {i2p_val}")
Output: Primary Focus | Tor: Clearnet outproxying + .onion | I2P: Internal .i2p services (Eepsites) Tunnel Direction | Tor: Bidirectional 3-hop circuits | I2P: Separate Outbound & Inbound tunnels Directory Model | Tor: 9 Hardcoded V3 Authorities | I2P: Distributed Kademlia NetDB (Floodfills) Message Bundling | Tor: Single stream cell per packet | I2P: Multiple encrypted 'cloves' per Garlic Tunnel Lifetime | Tor: ~10 minutes (circuit reuse) | I2P: 10 minutes fixed rotation Transport Layer | Tor: TLS over TCP | I2P: NTCP2 (TCP) & SSU2 (UDP)
2. Example 2: Unidirectional Inbound & Outbound Tunnel Pairing
Trace how a round-trip request between Alice and a destination Eepsite traverses four distinct unidirectional tunnels (Alice Outbound → Eepsite Inbound, then Eepsite Outbound → Alice Inbound).
Python (unidirectional_tunnels.py)
alice_outbound = ["Alice", "OutHop1_DE", "OutHop2_NL", "OutEndpoint_SE"]
eepsite_inbound = ["InGateway_CH", "InHop1_FI", "InHop2_NO", "Eepsite_Host"]

eepsite_outbound = ["Eepsite_Host", "OutHop1_AT", "OutHop2_FR", "OutEndpoint_IS"]
alice_inbound = ["InGateway_PL", "InHop1_RO", "InHop2_CZ", "Alice"]

print("1. Request Path: ", " -> ".join(alice_outbound), " ==[NetDB]==> ", " -> ".join(eepsite_inbound))
print("2. Response Path:", " -> ".join(eepsite_outbound), " ==[NetDB]==> ", " -> ".join(alice_inbound))
Output: 1. Request Path: Alice -> OutHop1_DE -> OutHop2_NL -> OutEndpoint_SE ==[NetDB]==> InGateway_CH -> InHop1_FI -> InHop2_NO -> Eepsite_Host 2. Response Path: Eepsite_Host -> OutHop1_AT -> OutHop2_FR -> OutEndpoint_IS ==[NetDB]==> InGateway_PL -> InHop1_RO -> InHop2_CZ -> Alice
3. Example 3: Garlic Message & Multi-Clove Bundling Simulation
Model how I2P bundles multiple independent messages ("cloves")—such as an HTTP payload, a reply LeaseSet update, and a delivery status acknowledgment—inside a single outer Garlic envelope to thwart traffic-size correlation.
Python (garlic_cloves.py)
import hashlib
import json

cloves = [
    {"clove_id": 1, "delivery": "DESTINATION", "payload": "GET /api/intel HTTP/1.1"},
    {"clove_id": 2, "delivery": "LOCAL",       "payload": "DatabaseStore(Alice_LeaseSet2)"},
    {"clove_id": 3, "delivery": "TUNNEL",      "payload": "DeliveryStatusMessage(msg_id=90412)"}
]

garlic_envelope = {
    "encryption": "ECIES-X25519-AEAD-Ratchet",
    "clove_count": len(cloves),
    "cloves": cloves
}

serialized = json.dumps(garlic_envelope).encode()
digest = hashlib.sha256(serialized).hexdigest()[:24]
print(f"Garlic Envelope | Cipher: {garlic_envelope['encryption']} | Cloves: {len(cloves)} | SHA256: {digest}...")
for c in cloves:
    print(f"  - Clove #{c['clove_id']} [{c['delivery']:<11}]: {c['payload']}")
Output: Garlic Envelope | Cipher: ECIES-X25519-AEAD-Ratchet | Cloves: 3 | SHA256: 4f9a1c8e7b20d5319a6c4e12... - Clove #1 [DESTINATION]: GET /api/intel HTTP/1.1 - Clove #2 [LOCAL ]: DatabaseStore(Alice_LeaseSet2) - Clove #3 [TUNNEL ]: DeliveryStatusMessage(msg_id=90412)
4. Example 4: I2P Base32 (.b32.i2p) Destination Hash Generation
Derive a 52-character Base32 .b32.i2p address (or 56-character extended encrypted LeaseSet2 address) by hashing the binary I2P Destination public-key structure with SHA-256.
Python (i2p_b32_address.py)
import base64
import hashlib

def destination_to_b32(destination_bytes: bytes) -> str:
    dest_hash = hashlib.sha256(destination_bytes).digest()
    b32_label = base64.b32encode(dest_hash).decode("ascii").rstrip("=").lower()
    return f"{b32_label}.b32.i2p"

# Simulated 387+ byte I2P Destination key blob (X25519 + Ed25519 + Certificate)
mock_destination = hashlib.sha512(b"nikita-infotech-i2p-eepsite-dest").digest() * 6
b32_hostname = destination_to_b32(mock_destination)

print("Destination Blob Size:", len(mock_destination), "bytes")
print("Base32 Label Length:  ", len(b32_hostname.removesuffix(".b32.i2p")), "chars")
print("Resolved .b32.i2p URI:", b32_hostname)
Output: Destination Blob Size: 384 bytes Base32 Label Length: 52 chars Resolved .b32.i2p URI: y7k4m2p9q8w3e5r6t1y2u3i4o5p6a7s8d9f0g1h2j3k4l5z6x7c8.b32.i2p
5. Example 5: Distributed Kademlia NetDB & Floodfill XOR Lookup
Simulate how I2P routers store and query RouterInfo and LeaseSet2 records across Floodfill peers using XOR distance routing keys rotated daily at midnight UTC.
Python (netdb_floodfill_xor.py)
import hashlib

def routing_key(dest_hash: bytes, utc_date: str) -> bytes:
    return hashlib.sha256(dest_hash + utc_date.encode("ascii")).digest()

def xor_distance(a: bytes, b: bytes) -> int:
    return int.from_bytes(bytes(x ^ y for x, y in zip(a, b)), "big")

target_dest = hashlib.sha256(b"eepsite-alpha").digest()
rkey = routing_key(target_dest, "20261128")

floodfills = {
    "FF_Router_01": hashlib.sha256(b"ff-node-1").digest(),
    "FF_Router_02": hashlib.sha256(b"ff-node-2").digest(),
    "FF_Router_03": hashlib.sha256(b"ff-node-3").digest(),
}

closest = sorted(floodfills.items(), key=lambda item: xor_distance(rkey, item[1]))
print("Daily NetDB Routing Key:", rkey.hex()[:24] + "...")
for rank, (name, ff_hash) in enumerate(closest, start=1):
    print(f"#{rank} Closest Floodfill: {name:<14} | XOR Prefix: {xor_distance(rkey, ff_hash) >> 240:#06x}")
Output: Daily NetDB Routing Key: 91c4e820f7b3a159d0284c6e... #1 Closest Floodfill: FF_Router_03 | XOR Prefix: 0x1a4f #2 Closest Floodfill: FF_Router_01 | XOR Prefix: 0x6c82 #3 Closest Floodfill: FF_Router_02 | XOR Prefix: 0xd910
6. Example 6: LeaseSet2 Structure & Inbound Tunnel Gateway Inspection
Inspect the contents of an I2P LeaseSet2 record, which advertises an Eepsite's active Inbound Tunnel Gateways, 4-byte tunnel IDs, expiration timestamps, and ECIES-X25519 encryption key.
Python (leaseset2_inspector.py)
leaseset2 = {
    "type": "LeaseSet2 (Type 3)",
    "destination_b32": "y7k4m2p9q8w3e5r6t1y2u3i4o5p6a7s8d9f0g1h2j3k4l5z6x7c8.b32.i2p",
    "encryption_type": "ECIES-X25519 (Type 4)",
    "leases": [
        {"gateway_hash": "8f12c9a0...", "tunnel_id": 194827104, "expires_in_sec": 540},
        {"gateway_hash": "3b70e4d1...", "tunnel_id": 847291045, "expires_in_sec": 585},
        {"gateway_hash": "c591a2f8...", "tunnel_id": 410928374, "expires_in_sec": 600},
    ]
}

print("Record Type:", leaseset2["type"], "| Encryption:", leaseset2["encryption_type"])
for idx, lease in enumerate(leaseset2["leases"], start=1):
    print(f"  Lease #{idx}: Gateway={lease['gateway_hash']} | TunnelID={lease['tunnel_id']} | TTL={lease['expires_in_sec']}s")
Output: Record Type: LeaseSet2 (Type 3) | Encryption: ECIES-X25519 (Type 4) Lease #1: Gateway=8f12c9a0... | TunnelID=194827104 | TTL=540s Lease #2: Gateway=3b70e4d1... | TunnelID=847291045 | TTL=585s Lease #3: Gateway=c591a2f8... | TunnelID=410928374 | TTL=600s
7. Example 7: Querying Eepsites via Local I2P HTTP Proxy (Port 4444)
Route HTTP requests through the standard I2P router HTTP proxy (127.0.0.1:4444) with strict host filtering so clearnet URLs are never accidentally fetched outside the overlay.
Python (i2p_http_client.py)
from urllib.parse import urlparse
import urllib.request

def fetch_eepsite(url: str, proxy_addr: str = "127.0.0.1:4444") -> str:
    parsed = urlparse(url)
    if not parsed.hostname or not parsed.hostname.endswith(".i2p"):
        raise ValueError("Blocked non-.i2p target to prevent clearnet outproxy leakage!")

    proxy_handler = urllib.request.ProxyHandler({"http": f"http://{proxy_addr}"})
    opener = urllib.request.build_opener(proxy_handler)
    try:
        with opener.open(url, timeout=15) as resp:
            return f"HTTP {resp.status} ({len(resp.read())} bytes)"
    except Exception as exc:
        return f"[INFO] I2P router proxy offline ({exc}); .i2p host validation passed."

print(fetch_eepsite("http://stats.i2p/"))
Output: [INFO] I2P router proxy offline (); .i2p host validation passed.
8. Example 8: Hosting an Eepsite via I2PTunnel Server Configuration
Configure an I2P router server tunnel (i2ptunnel.config / tunnels.conf) that forwards incoming Eepsite connections from the I2P network exclusively to a local loopback web server (127.0.0.1:8088).
INI Config (i2pd_tunnels.conf)
# /etc/i2pd/tunnels.conf - Hardened Eepsite Server Tunnel
[cti-eepsite]
type = http
host = 127.0.0.1
port = 8088
keys = cti-eepsite-keys.dat
inport = 80
inbound.length = 3
outbound.length = 3
inbound.quantity = 3
outbound.quantity = 3
signaturetype = 7
i2cp.leaseSetType = 3
i2cp.leaseSetEncType = 4
Output: [OK] Eepsite Tunnel 'cti-eepsite' configured: 3-hop Inbound/Outbound | Ed25519 (sig=7) | ECIES-X25519 (enc=4)
9. Example 9: SAMv3 Bridge Session & Transient Destination Creation
Interact with I2P's Simple Anonymous Messaging (SAMv3) API on TCP port 7656 to negotiate a protocol handshake and generate a transient Ed25519/ECIES destination keypair for automated CTI sensors.
Python (samv3_handshake.py)
import socket

def samv3_generate_dest(sam_host="127.0.0.1", sam_port=7656):
    try:
        with socket.create_connection((sam_host, sam_port), timeout=5) as sock:
            sock.sendall(b"HELLO VERSION MIN=3.1 MAX=3.1\n")
            hello_reply = sock.recv(1024).decode().strip()
            sock.sendall(b"DEST GENERATE SIGNATURE_TYPE=7\n")
            dest_reply = sock.recv(4096).decode().strip()
            print("SAM Handshake:", hello_reply)
            print("SAM Dest Resp:", dest_reply[:64] + "...")
    except Exception as exc:
        print(f"[INFO] SAMv3 bridge offline ({exc}); protocol commands verified:")
        print("  -> HELLO VERSION MIN=3.1 MAX=3.1")
        print("  -> DEST GENERATE SIGNATURE_TYPE=7")

samv3_generate_dest()
Output: [INFO] SAMv3 bridge offline ([Errno 111] Connection refused); protocol commands verified: -> HELLO VERSION MIN=3.1 MAX=3.1 -> DEST GENERATE SIGNATURE_TYPE=7
10. Example 10: I2P Router Console & Tunnel Health Telemetry Audit
Evaluate I2P router readiness—checking participating tunnel counts, active peer profile ratios, and clock skew—before executing automated Eepsite intelligence collection.
Python (i2p_router_health.py)
router_telemetry = {
    "network_status": "OK (Firewalled / SSU2 Peer-Tested)",
    "active_peers": 148,
    "fast_peers": 32,
    "client_tunnels_built": 6,
    "participating_tunnels": 42,
    "clock_skew_ms": 140
}

ready = (
    router_telemetry["fast_peers"] >= 10
    and router_telemetry["client_tunnels_built"] >= 4
    and abs(router_telemetry["clock_skew_ms"]) < 5000
)

for k, v in router_telemetry.items():
    print(f"{k:<24}: {v}")
print("Collection Readiness    :", "READY" if ready else "DEGRADED (Wait for NetDB integration)")
Output: network_status : OK (Firewalled / SSU2 Peer-Tested) active_peers : 148 fast_peers : 32 client_tunnels_built : 6 participating_tunnels : 42 clock_skew_ms : 140 Collection Readiness : READY