Glossary

Onion Routing

A layered encryption technique where each routing node can only decrypt its own instructions, preserving sender and receiver privacy.

Key Takeaways

  • Onion routing wraps payment instructions in layers of encryption: each node along the route can only decrypt its own layer, learning the previous hop and next hop but never the full path from sender to receiver.
  • The Lightning Network uses Sphinx packets for onion routing, enabling fixed-size encrypted payloads that prevent intermediate nodes from determining their position in the route or the total number of hops.
  • Privacy is not absolute: timing analysis, probing attacks, and traffic correlation can partially deanonymize payments. Blinded paths and trampoline payments offer additional defenses.

What Is Onion Routing?

Onion routing is a privacy technique that encrypts a message in multiple layers, like the layers of an onion. Each node that processes the message peels off one layer of encryption, revealing only the instructions for that node: where the message came from and where to send it next. No single node ever sees the complete route.

The concept originated in the 1990s at the U.S. Naval Research Laboratory and became widely known through the Tor network, which uses onion routing for anonymous internet browsing. The Lightning Network adopted a similar approach for payment routing, using a construction called Sphinx to protect the privacy of both senders and receivers in Bitcoin payment channels.

Without onion routing, every node forwarding a payment would know the sender, the receiver, and the amount. With it, forwarding nodes learn only what they need to perform their role: accept a payment from one channel and push it out another.

How It Works

When a sender initiates a Lightning payment, their node first calculates the full route to the destination. The sender then constructs a Sphinx onion packet that encodes instructions for every hop along the path. The construction process works from the inside out:

  1. The sender computes a shared secret with each node on the route using Elliptic Curve Diffie-Hellman (ECDH) key exchange against each node's public key
  2. Starting from the final hop, the sender encrypts that hop's routing instructions using the shared secret for that node
  3. The sender wraps each preceding layer around the previous result, encrypting with the corresponding node's shared secret
  4. The fully constructed onion packet is sent to the first hop along with the HTLC

Each forwarding node receives the onion, derives the shared secret using its private key, and decrypts its layer. This reveals per-hop instructions: the next node to forward to, the amount and timelock to use, and the remaining (still encrypted) onion to pass along.

The Sphinx Packet Format

Lightning uses the Sphinx packet construction defined in BOLT #4. A Sphinx packet has three components:

  • Version byte: identifies the packet format (currently version 0)
  • Ephemeral public key (33 bytes): used by each hop to derive the shared secret via ECDH. This key is deterministically blinded at each hop so that only the intended recipient can compute the correct shared secret.
  • Encrypted payload (1300 bytes): contains all per-hop data in a fixed-size block. The fixed size is critical: it prevents nodes from inferring the route length based on payload size.

The encrypted payload uses a stream cipher (ChaCha20) keyed with the shared secret. After decrypting, the node reads its own per-hop data from the beginning of the payload, then shifts the remaining bytes left and pads with pseudorandom filler bytes. This shift-and-pad process ensures the payload is always exactly 1300 bytes regardless of position in the route.

Sphinx Packet Structure:
┌──────────┬────────────────────┬───────────────────────┐
│ Version  │ Ephemeral Pub Key  │ Encrypted Payload     │
│ (1 byte) │ (33 bytes)         │ (1300 bytes)          │
└──────────┴────────────────────┴───────────────────────┘

Per-Hop Payload (after decryption):
┌─────────────┬──────────────────────────────────────────┐
│ This node's │ Remaining encrypted data for next hops   │
│ instructions│ (shifted left, padded with filler)        │
└─────────────┴──────────────────────────────────────────┘

Per-Hop Payload Contents

Each hop's decrypted payload contains a Type-Length-Value (TLV) encoded set of fields:

  • Short channel ID: identifies which channel to forward the payment through
  • Amount to forward: the number of millisatoshis to send to the next hop (which may differ from the incoming amount, accounting for routing fees)
  • Outgoing CLTV value: the timelock to set on the outgoing HTLC
  • Padding and optional TLV records: additional data such as payment metadata or blinded path instructions

The final hop's payload differs: instead of forwarding instructions, it contains the payment secret (used to prove the payment was intended for this receiver), the total amount, and any additional application-level data. For recipients with private channels, the sender includes route hints in the onion construction to reach nodes not visible in the public graph.

What Each Node Can and Cannot See

A forwarding node learns only:

  • The previous hop (who sent it the HTLC)
  • The next hop (where to forward the HTLC)
  • The forwarding amount and timelock delta
  • The fee it earns (difference between incoming and outgoing amounts)

A forwarding node cannot determine:

  • The original sender of the payment
  • The final destination of the payment
  • The total payment amount
  • How many hops came before or will come after
  • The total route length

This asymmetry is the core privacy property. Even if an adversary controls one or two nodes in the path, they cannot reconstruct the full payment route from their local view alone.

The 20-Hop Limit

The fixed 1300-byte payload limits Lightning routes to a maximum of 20 hops. Each hop consumes approximately 65 bytes of payload space (with the modern TLV format), and the total must fit within the fixed allocation.

This limit exists for two reasons:

  • Fixed payload size: the 1300-byte payload cannot grow, so more hops would require either larger packets (breaking the constant-size property) or smaller per-hop payloads (reducing flexibility)
  • Practical routing constraints: longer routes accumulate more routing fees, require larger timelock deltas, and have higher failure rates. In practice, most Lightning payments complete in 3 to 5 hops.

The 20-hop ceiling is generous for real-world use. The network's small-world topology means almost any two nodes are reachable within a handful of hops.

Comparison to Tor Onion Routing

Both Lightning and Tor use layered encryption, but the designs differ significantly:

PropertyLightning (Sphinx)Tor
Packet sizeFixed (1366 bytes total)Fixed (512-byte cells)
Circuit typeSource-routed, single-use per paymentIncrementally built, long-lived circuits
Route selectionSender computes the full pathClient selects relays from a directory
PayloadPayment instructions (amounts, timelocks)Arbitrary TCP streams
Reply pathError replies use shared secrets for backtrackingBidirectional over the same circuit
Hop countUp to 20 (typically 3 to 5)Typically 3 (guard, middle, exit)

A critical difference: Tor circuits are long-lived and carry many packets, making them vulnerable to traffic analysis over time. Lightning onion packets are single-use: each payment creates a fresh packet with new ephemeral keys. This limits the window for correlation attacks but does not eliminate them entirely.

Use Cases

Private Payments

The primary use case is payment privacy. When Alice pays Bob through intermediate nodes Carol and Dave, Carol knows Alice sent something through her but does not know the destination. Dave knows he is forwarding to Bob but does not know the origin. Neither Carol nor Dave learns the full picture.

This privacy is essential for Bitcoin layer-2 networks where financial transactions should not be visible to every participant in the routing infrastructure.

Multi-Hop Routing with Fees

Onion routing enables a decentralized fee market. Each node sets its own routing fees, and the sender embeds the correct fee amounts in each hop's encrypted payload. Nodes cannot see what other nodes are charging, preventing collusion on fee extraction.

Atomic Multi-Path Payments

Atomic multi-path payments (AMP) split a payment across multiple routes. Each partial payment carries its own onion packet with independent layered encryption. This means no single routing node sees the total payment amount, and the partial payments cannot be correlated by intermediaries.

Blinded Paths and Receiver Privacy

Standard onion routing protects the sender well: forwarding nodes cannot identify the origin. But the sender must know the receiver's node ID to construct the route. This leaks receiver identity to the sender.

Blinded paths extend onion routing so the receiver provides a pre-encrypted route suffix. The sender constructs their portion of the onion and appends the blinded segment without knowing the final destination node. This achieves mutual privacy: the sender does not learn the receiver's identity, and forwarding nodes learn nothing about either endpoint.

Risks and Considerations

Timing Attacks

Onion encryption hides the contents of a payment, but it does not hide when payments occur. An adversary that controls two nodes on the same route can correlate an incoming HTLC at one node with an outgoing HTLC at the other by matching amounts, timing, and hash values. Since all hops in a payment share the same payment hash, a node appearing twice on the path can link both positions.

PTLCs (Point Time-Locked Contracts) are a proposed upgrade that would replace the shared payment hash with per-hop randomized points, leveraging Taproot and Schnorr signatures. This would eliminate hash-based correlation while preserving atomicity.

Probing and Network Analysis

Channel probing allows an attacker to send fake payments that deliberately fail in order to infer channel balances across the network. Combined with knowledge of the network graph, an adversary can narrow down the set of possible senders for a given payment by analyzing which channels had sufficient balance to route it.

While onion routing prevents direct observation of the route, it does not prevent inference-based deanonymization. Network-level adversaries who can observe many nodes simultaneously pose the greatest threat to payment privacy.

Route Length Inference

The fixed-size Sphinx packet prevents exact route-length determination, but timing can leak information. Payments routed through more hops experience slightly higher latency. A sophisticated adversary measuring HTLC settlement times at their node could make statistical guesses about whether they are near the beginning or end of a route.

Some implementations add small random delays to HTLC forwarding to mitigate this, though this introduces a tradeoff between privacy and payment speed.

Sender Knowledge Requirement

Source routing requires the sender to know the full network topology and compute the route themselves. This means the sender must have a reasonably current view of the channel graph, which can be resource-intensive for mobile or constrained devices. Trampoline payments address this by delegating route computation to intermediate nodes, though this introduces a partial trust assumption: the trampoline node learns that a payment was requested, even if it does not learn the final destination.

Error Reporting and Privacy Leaks

When a payment fails mid-route, the failing node generates an error that propagates back to the sender. These error messages are encrypted using the shared secrets from the original onion, so only the sender can read them. However, the error structure can sometimes reveal which node failed, leaking partial route information to any node that observes the error timing.

The Lightning specification has evolved to address this with attributable errors, which allow the sender to cryptographically verify which node produced the error without leaking this information to intermediate nodes.

This article is for educational purposes only and does not constitute financial or technical advice. Privacy properties depend on implementation details and network conditions that change over time.