Module 2: Routing & HTLCs

🤔 The Network Effect Problem

You now understand payment channels between two parties. But here's the problem: you can't open a channel with everyone you might want to pay. That would require millions of on-chain transactions and locked capital.

The Question: How can Alice pay Dave if they don't have a direct channel?

Alice ←channel→ Bob ←channel→ Carol ←channel→ Dave

Alice wants to pay Dave 0.1 BTC
But Alice only has a channel with Bob!

Key Insight: What if Alice could route the payment through Bob and Carol to reach Dave, without trusting them? What if the payment could only complete if Dave receives it, or automatically refund if something goes wrong?

This is exactly what Hash Time-Locked Contracts (HTLCs) enable.

Hash Time-Locked Contracts (HTLCs)

An HTLC is a conditional payment that uses cryptographic hashes and timelocks to create trustless multi-hop payments.

The Two Conditions

An HTLC can be spent in two ways:

  1. Hash Condition: Reveal the preimage of a hash (the secret) before the timeout expires → Payment succeeds
  2. Timelock Condition: After the timeout expires, refund to the sender → Payment fails, money returned

HTLC Script Structure

OP_IF
    # Payment path (reveal preimage)
    OP_HASH160 <payment_hash> OP_EQUALVERIFY
    <receiver_pubkey>
OP_ELSE
    # Refund path (after timeout)
    <timeout_blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
    <sender_pubkey>
OP_ENDIF
OP_CHECKSIG

This script says: "Pay to receiver if they know the preimage, or refund to sender after timeout."

Multi-Hop Payment Flow

Let's walk through how Alice pays Dave through Bob and Carol:

Step 1: Invoice & Secret Generation

Dave generates a random secret (preimage) and hashes it to create payment_hash. He sends Alice an invoice containing the payment_hash and the amount (0.1 BTC).

Dave: preimage = random()
      payment_hash = SHA256(preimage)

Invoice: "Pay 0.1 BTC to payment_hash abc123..."

Step 2: Alice Sets Up HTLCs

Alice constructs a payment route: Alice → Bob → Carol → Dave

She sets up HTLCs with decreasing timeouts:

Alice → Bob:   HTLC for 0.101 BTC, timeout 100 blocks
Bob → Carol:   HTLC for 0.1005 BTC, timeout 90 blocks
Carol → Dave:  HTLC for 0.1 BTC, timeout 80 blocks

(Each hop takes a small fee and reduces timeout)

Step 3: Dave Reveals the Secret

Dave sees the HTLC from Carol. To claim it, he reveals the preimage to Carol.

The Magic Moment

When Dave reveals the preimage to claim the payment from Carol, Carol now knows the secret! She can use it to claim the payment from Bob. Bob can use it to claim from Alice.

The secret propagates backwards along the route, settling all HTLCs.

Step 4: HTLCs Settle Backwards

Dave reveals preimage to Carol  → Carol claims 0.1 BTC
Carol uses preimage with Bob     → Bob claims 0.1005 BTC
Bob uses preimage with Alice     → Alice pays 0.101 BTC

Result:
- Dave received 0.1 BTC
- Carol earned 0.0005 BTC (routing fee)
- Bob earned 0.0005 BTC (routing fee)
- Alice paid 0.101 BTC total

What if Something Goes Wrong?

If any hop fails to forward the payment, the HTLCs automatically time out and refund in reverse order:

  • Carol's HTLC to Dave times out at block 80 → Carol gets refund
  • Bob's HTLC to Carol times out at block 90 → Bob gets refund
  • Alice's HTLC to Bob times out at block 100 → Alice gets full refund

No one can steal funds. The payment is atomic: either it completes entirely or refunds entirely.

Onion Routing: Privacy by Design

Lightning uses onion routing (inspired by Tor) to protect payment privacy. Each hop only knows the previous and next hop—not the full route.

How Onion Routing Works

Alice encrypts the payment instructions in layers, like an onion:

Layer 3 (innermost): [Dave: Final destination, 0.1 BTC]
Layer 2:             [Carol → Dave, 0.1 BTC]
Layer 1 (outermost): [Bob → Carol, 0.1005 BTC]

Alice sends the onion to Bob.
Bob decrypts layer 1 → sees "forward to Carol"
Carol decrypts layer 2 → sees "forward to Dave"
Dave decrypts layer 3 → sees "I'm the final recipient"

Each node only knows:

  • Bob knows: Alice sent something, forward to Carol (doesn't know final destination)
  • Carol knows: Bob forwarded something, forward to Dave (doesn't know if Bob is sender)
  • Dave knows: He's the final recipient (doesn't know if Carol is sender or forwarder)

Result: Payment privacy without a central coordinator. No one knows the full route except Alice (the sender).

Path Finding: Discovering Routes

How does Alice know to route through Bob and Carol? The Lightning Network uses source routing— the sender constructs the entire path.

Network Gossip

Nodes broadcast information about their channels:

  • Channel existence and capacity
  • Routing fees and policies
  • Channel updates (enabled/disabled)

This creates a network graph that each node uses to find routes.

Route Selection Criteria

When finding a route, nodes consider:

  • Liquidity: Does each channel have enough balance?
  • Fees: What's the total routing cost?
  • Reliability: Has this route succeeded before?
  • Privacy: Shorter routes leak less information but may have higher fees

The Liquidity Problem

Channel capacity is public (on-chain), but channel balance distribution is private. This is good for privacy but makes routing tricky—you might try a route that doesn't have enough liquidity on one side.

Modern Lightning nodes use probabilistic routing and learn from failures to improve route selection over time.

Interactive Route Simulator

Simulate multi-hop payments, watch HTLCs propagate, and see how failures result in refunds.

Launch Lightning Routing Simulator →

Try creating a route with insufficient liquidity to see how payment failures work!

Advanced Routing Concepts

Multi-Path Payments (MPP)

Instead of sending 1 BTC through a single route, you can split it across multiple routes:

Alice wants to pay Dave 1 BTC:
Route 1: Alice → Bob → Dave (0.6 BTC)
Route 2: Alice → Carol → Dave (0.4 BTC)

Total: 1 BTC delivered via 2 separate HTLCs

Benefits: Better success rates, improved privacy, better liquidity utilization

Just-In-Time (JIT) Routing

Some routing nodes open new channels on-the-fly to facilitate payments, reducing the need for pre-existing channel connectivity.

Trampoline Routing

Mobile wallets can delegate route computation to trusted nodes (trampolines) to save bandwidth and computation, while still maintaining payment security.

Think About It

Question: Why do HTLC timeouts need to decrease along the route (100 → 90 → 80 blocks)?

Answer: To ensure that if a downstream hop times out, the upstream hops have time to also refund. If Alice's timeout was 80 blocks and Dave's was 100 blocks, Dave could claim the payment at block 99, but Alice's HTLC would have already timed out—Alice wouldn't get the preimage and would lose money! Decreasing timeouts ensure safety.

Key Takeaways

  • HTLCs enable trustless multi-hop payments across channels
  • Payments are atomic: they either complete fully or refund fully
  • The secret (preimage) propagates backwards, settling all HTLCs
  • Onion routing provides payment privacy—hops don't know the full route
  • Timeouts must decrease along the route to ensure safety
  • Path finding uses network gossip to build a routing graph
  • Multi-path payments split large payments across multiple routes
  • No intermediary can steal funds—cryptography enforces atomicity

✓ Knowledge Check

Test your understanding of Lightning routing and HTLCs with these practical questions.

1. What are the two conditions under which an HTLC can be spent?

2. Why do HTLC timeouts need to DECREASE along a payment route?

3. What information does each routing node know about a payment?

4. When Dave reveals the preimage to claim payment from Carol, what happens next?

5. What is Multi-Path Payments (MPP)?