Lightning for Builders The network
Onion routing
How each node on a route learns only its neighbours: build and peel a toy onion in Python, then compare it with the real Sphinx format.
45 minIntermediate10 / 17
Draft: this lesson is still waiting for review.
What you'll learn
- Explain what each hop can and can't see in an onion-routed payment
- Build a layered encryption and peel it hop by hop
- Name what real Lightning onions add: fixed size, shared secrets, HMACs
Key terms
- onion routing (upitishaji wa kitunguu)
- Wrapping payment instructions in layers of encryption so each node only learns the next hop.
- node (nodi)
- A computer running Bitcoin or Lightning software that checks every rule for itself.
When Alice pays Dina through Bob and Chan, Bob needs to know where to send the payment next, but not that it's going to Dina. onion routing gives each node exactly what it needs and nothing more.
Layers, like an onion
Alice knows the whole route. She builds a message in layers, innermost first:
- The Dina layer: "you are the final hop; the amount is 21,000."
- Wrapped in the Chan layer: "forward 21,000 to Dina."
- Wrapped in the Bob layer: "forward 21,001 to Chan."
Each layer is encrypted with a key only that hop can work out. Bob peels his layer, reads "forward to Chan", and passes on the rest, which to him is random-looking bytes. Chan peels the next one. Only Dina's layer says "it's for you".
Build a toy onion
The real thing uses elliptic-curve shared secrets and ChaCha20; ours uses a SHA-256 stream. The layering is the same idea. Fill in wrap and peel:
Build a toy onion
These exercises need a laptop with the lab running. You can read the lesson on your phone.
The check runs your functions with random keys and messages, and makes sure the message only appears after the last layer.
What real onions add (Sphinx)
- Fixed size. Every onion is 1,366 bytes, padded with filler, so a hop can't count the remaining hops.
- Per-hop shared secrets. Alice uses a fresh ephemeral key per payment; each hop derives its secret with ECDH, and the key is blinded at every step so hops can't link the onion they received with the one they send on.
- HMACs. Each layer carries an integrity tag. A tampered onion is rejected, and the error travels back encrypted, layer by layer, to Alice.
Reflect
Write your answer down, or talk it over with a friend or your chama.
- Chan forwards the payment to Dina. Can Chan tell whether Dina is the final recipient?
- Why must every onion be the same size, however long the route?
Check yourself
Further reading
Adapted from Mastering the Lightning Network. Andreas M. Antonopoulos, Olaoluwa Osuntokun and René Pickhardt. Licence: CC BY-SA 4.0.