Getting Started with Bitcoin Lightning Network

Mabel Oza
Coinmonks
13 min readMay 17, 2023

--

The Lightning Network is the layer-2 scaling solution for Bitcoin that was created to facilitate cheaper and faster transactions.

Bitcoin Lightning is similar to a bar tab…

The lightning network acts as the tab running at a bar. The tab is a payment channel between you and the bar. When ordering the first drink, you provide a credit card, similar to initiating a payment channel. Then as the night proceeds, and you're having too much fun, you will order multiple drinks 🍻; these multiple drink orders are recorded transactions 📜. While going through these drinks, you haven't technically spent any money on these drinks. It's only until the end of the night when you pay for the drinks by closing out your tab.

With the lightning network, 2 transactions happen on the Bitcoin network, opening a payment channel (starting the tab) and closing a payment channel (closing out the tab).

Topics Covered:

What is Bitcoin Lightning?

🤺Different Lightning Implementations

🌐Payment Channel Lifecycle

🤔Analyzing a Lightning Payment Channel

👬Connecting to a Lightning Node via Docker

📚Resources

⛈ What is Bitcoin Lightning Network?

The lightning network is built to facilitate cheaper transaction fees and faster transactions on the Bitcoin network.

A Layer 2 Solution…

It's a layer 2 solution, which means it's a child network to a major blockchain network. There are different variations to layer 2 networks, but the overall theme is that they are smaller versions of the network that write into the layer 1 network. Examples of other layer-2 solutions are Polygon for Ethereum, Loopring for Ethereum, and Lightning for Bitcoin.

Ingredients in the Lightning Network

The Lightning Network consists of three key components: lightning nodes, payment channels, and routing nodes. Lightning nodes are the machines and software that allow organizations or people to participate. Payment channels are established between two nodes to allow for off-chain transactions with fast and low-cost settlements. Routing nodes are crucial in finding and forwarding payments across the network, ensuring that transactions can reach their intended destinations efficiently. These components create a scalable and efficient network for conducting fast and secure off-chain transactions.

Lightning Nodes — The Building Blocks

Lightning nodes are machines or instances that have lightning software installed. These nodes have a full Bitcoin node, a lightning client (see the Lightning Implementation section below), and a node wallet.

A Lightning node is a piece of software that connects to the Lightning Network and allows users to transact with other nodes on the network. Anyone can run lightning nodes to send and receive payments and route payments for other users.

Lightning nodes can be set up using a machine like raspberry pi (for experimental and learning purposes), on the cloud, or bought ready-made. Below is a guide on setting up a node:

Below is a link on whether you should buy or DIY a Bitcoin lightning node:

Payment Channels — Connecting Nodes

The lightning network is made up of a collection of payment channels. A payment channel is a connection between two nodes that allows them to transact with each other off-chain without broadcasting their transactions to the main blockchain.

A payment channel is a connection between two nodes that allows them to transact with each other off-chain without broadcasting their transactions to the main blockchain. This is the fundamental building block of the Lightning Network.

Think of it like a Thanksgiving dining table. Bob is next to Carol, and Carol is next to Alice. Alice, Carol, and Bob will all be nodes in the lightning network. Alice and Carol have a payment channel, and Carol and Bob have a payment channel.

Alice and Carol can have all the side conversations they want without sharing them with the group. There's no reason why Alice has to tell the group everything she wants to tell Carol and vice versa (unless she's roasting her). But if someone asks what they are talking about or Alice and Carol decide to bring in the group, they can summarize their conversation with the group. In this scenario, Alice and Carol have a payment channel.

With payment channels, nodes can transact with each other back and forth without ever sharing it with the larger Bitcoin network (all the nodes). The pieces they share are that they started a payment channel with each other and closed their channel with their final balances.

Routing Nodes — Connecting Payment Channels

The lightning network comprises multiple payment channels, mostly connected like a web. One party can connect with another party because the payment channels are all connected to each other.

Routing nodes act as intermediaries and use their own payment channels to route transactions and relay payments to the final destination. Routing nodes are responsible for discovering and maintaining routes through the network and ensuring that transactions are processed quickly and efficiently.

Going back to our Thanksgiving dinner… Even though Bob isn't sitting next to Alice, he can transact (give a slice of turkey 🦃) with Alice efficiently because he can go through Carol. Carol can agree to pass the turkey to Alice in exchange for payment. In this scenario, Carol would be called a routing node.

Over time as the network expands, all channels will be connected based on the theory of six degrees of separation.

Onion Routing

The technique used to route is onion routing, developed in 1998 by DARPA (Defense Advanced Research Projects Agency) and has been commonly used in Tor Networks.

Onion routing applies anonymity to a network messages by wrapping each message in distinct layers of protection to hide the routing of the messages between a client device and a destination device.

The messages are encapsulated in layers of encryption, just like layers of an onion.

In onion routing, each layer is encrypted with the public key of the next node in the route, including the final destination. The routing node receiving the onion packet only knows the address of the next node in the route, which is encrypted in the outer layer of the onion.

The routing node uses its routing table to determine the address of the next node to route the transaction and then decrypts the outer layer of the onion to reveal the address of the next node. It then encrypts the packet with the public key of the next node and sends it along to the next routing node. This process repeats until the packet reaches its final destination.

🤺Different Lightning Implementations

People and organizations use lightning implementations to interact with a lightning node and do all the necessary functions. All lightning network implementations must follow the specifications defined by B.O.L.T. (Basis of Lightning Technology).

A few popular lightning networks that vary by language are C-Lightning, Eclair, LND, Rust LDK, and Electrum. C-Lightning is written in C, Eclair is written in Scala, LND is written in Go, Rust LDK is written in Rust, and Electrum is written in Python.

🤔Analyzing a Lightning Payment Channel

To truly understand a lightning network, it's crucial to analyze it in an explorer (i.e., mempool.space, 1ml.com, or amboss.space).

Below is a snapshot taken from "mempool.space" on channel 805523109340971008, which is used by "zero fee routing | CLN" and "BitcoinLightning.Network".

This image was captured from https://mempool.space/lightning/channel/805523109340971008.

Key highlights about this network:

🌐Payment Channel Lifecycle

1. Create a Payment Channel

We need to be part of a payment channel to do anything on the lightning network. To create a payment channel, we'll have Alice and Bob go through the following steps:

Terms are Negotiated

  1. Alice and Bob agree on the terms of the payment channel, including the amount of Bitcoin to be committed to the channel and the fees they will pay each other for routing payments.

Multi-Signature Wallet is Created

  1. Alice creates a multi-signature wallet that requires both her and Bob's signatures to spend funds

Funding Transactions are Created & Signed

  1. Alice generates a funding transaction that allocates the agreed-upon amount of BTC from her wallet to the multi-sig wallet address. This transaction is not broadcast to the Bitcoin network yet.
  2. Alice shares the funding transaction details with Bob, who verifies the details and adds his own input to the transaction.
  3. Bob generates a signature for the funding transaction and shares it with Alice.
  4. Alice adds her own signature to the funding transaction and broadcasts it to the Bitcoin network, making the funds available in the multi-sig wallet.
  5. Bob creates his own funding transaction using the same multi-sig wallet address, allocates the agreed-upon amount of BTC from his wallet, and shares the funding transaction details with Alice.
  6. Alice verifies the details and adds her own input to the transaction.
  7. Alice generates a signature for the funding transaction and shares it with Bob.
  8. Bob adds his own signature to the funding transaction and broadcasts it to the Bitcoin network, making the funds available in the multi-sig wallet.

Announcement Transactions

  1. Alice creates a new transaction that spends from the funding transaction and sends the channel's capacity to a new public key (the channel ID).
  2. Bob does the same and creates a new transaction with the same inputs and outputs but with his own public key as the channel ID.
  3. Alice and Bob exchange their unsigned announcement transactions.
  4. Alice signs Bob's announcement transaction with her private key and sends the signed transaction to Bob.
  5. Bob signs Alice's announcement transaction with his private key and sends the signed transaction back to Alice.
  6. Once both parties have fully signed announcement transactions, they can broadcast them to the Bitcoin network to publicly announce the existence of the new payment channel.

2. Exchange Funds in the Payment Channel

  1. The recipient (Bob) generates an invoice that includes the payment amount and a payment hash.
  2. The sender (Alice) uses her Lightning wallet to scan the invoice's QR code or copy the invoice details.
  3. Alice's wallet decodes the invoice and verifies that it's valid.
  4. Alice's wallet constructs a Sphinx packet that includes the payment hash and encrypts it with Bob's public key.
  5. Alice's wallet adds the Sphinx packet to a payment message that includes the payment amount and routes it through the Lightning network toward Bob's node.
  6. The payment message is forwarded through intermediary nodes until it reaches Bob's node.
  7. Bob's node decrypts the Sphinx packet with his private key to reveal the payment hash.
  8. Bob's node looks up the preimage corresponding to the payment hash and includes it in a Sphinx packet that is encrypted with the previous hop's public key.
  9. Bob's node sends the Sphinx packet back through the network toward Alice's node.
  10. The Sphinx packet is forwarded through intermediary nodes until it reaches Alice's node.
  11. Alice's node decrypts the Sphinx packet with her private key to reveal the preimage.
  12. Alice's node sends the preimage to Bob's node to prove the payment has been completed.
  13. Bob's node verifies the preimage, and the payment is complete.

The Invoice

All payments start with an invoice (unless it's keysend). The payee must put together an invoice. This tells the payer what network they want the payment in and the amount.

A Lightning invoice is a payment request that includes a payment hash and a preimage, which the payer must provide to settle the invoice.

Lightning invoices are generated by the payee and are used to receive payments through the Lightning Network.

Dive deeper into specifics around an invoice at the blog below:

3. Close the Payment Channel

There are 3 ways to close a channel, a collaborative close, a force close, and a dispute close.

Below are the steps at a high level:

  1. Either party initiates the closing process by sending a close transaction to the Bitcoin network.
  2. The closing transaction spends the latest channel state, which includes the balance of each party.
  3. The closing transaction is broadcast to the Bitcoin network and included in a block.
  4. Once the closing transaction is confirmed, both parties can claim their respective channel balances on the Bitcoin network.

If one party does not agree with the channel state used in the closing transaction, they can broadcast a penalty transaction to the Bitcoin network. This penalty transaction claims all the funds in the channel for the non-compliant party.

If the penalty transaction is broadcast, it will invalidate the previous closing transaction and force the compliant party to wait until the penalty transaction confirms before claiming their funds.

Check out the write-up below for a deeper dive into closing channels:

👬Connecting to a Lightning Node via Docker

Getting Started with the Lightning Network with Docker

  1. Find your machine's IP address by running the command (macOS):
ipconfig getifaddr en0
  1. Find your machine's IP address by running the command (windows):
ipconfig /all

2. Set your IP address as an IP_ADDR variable. If your IP address is 192.xxx.x.xx, then run the command:

IP_ADDR=192.xxx.x.xx

3. Set a volume to store the data for the lightning node and name lnd-data:

docker volume create lnd-data

4. Run the following docker command:

docker run -v lnd-data:/lnd --name=lnd-node -d \
-p 9735:9735 \
-p 10009:10009 \
lnzap/lnd:latest \
--bitcoin.active \
--bitcoin.testnet \
--debuglevel=info \
--bitcoin.node=neutrino \
--neutrino.connect=testnet1-btcd.zaphq.io \
--neutrino.connect=testnet2-btcd.zaphq.io \
--autopilot.active \
--tlsextraip=$IP_ADDR \
--externalip=$IP_ADDR:10009 \
--rpclisten=0.0.0.0:10009

Breakdown of this Docker Command

Below are a few highlights to notice in the docker command above.

Using the Volume lnd-data

-v lnd-data:/lnd --name=lnd-node -d

We are telling docker the node will use the volume created earlier (lnd-data)

Pulling the Zap Lightning Network Image

lnzap/lnd:latest

The image is lnzap/lnd, created by the open-source project, Zap (https://zaphq.io).

Using the Testnet Network

--bitcoin.testnet

For learning purposes, we will only use Bitcoin testnet, so we're not using any real money.

Connect to the Neutrino Public Client

We will connect to a Neutrino public client using Zap's Neutrino testnet client https://zaphq.io/.

A little bit about Neutrino…

Neutrino came out of BIPs 157/158 (Client-Side Block Filtering), which is an improvement from Bloom Filters proposed in BIP 37.

Neutrino clients are lightweight Bitcoin clients that use simplified payment verification (SPV) and client-side filtering. Client-side filtering is used to to sync with the Bitcoin network and retrieve only the transactions relevant to the user’s wallet, without having to download and verify the entire blockchain.

--bitcoin.node=neutrino \
--neutrino.connect=testnet1-btcd.zaphq.io \
--neutrino.connect=testnet2-btcd.zaphq.io \

Checkout Suredbits explainer for a deeper dive into Neutrino:

https://suredbits.com/neutrino-what-is-it-and-why-we-need-it/

Automatically Open Channels with Other Channels

This flag is used to activate the autopilot feature of the Lightning Network Daemon (LND). Autopilot is a feature that automatically opens channels with other nodes on the network based on certain criteria, such as channel size, uptime, and fees.

--autopilot.active \

Set an Additional IP address to include in the TLS certificate

The --tlsextraip flag adds an extra IP address to the TLS certificate that the LND node uses to establish secure connections. The $IP_ADDR variable should be replaced with the IP address of the node.

--tlsextraip=$IP_ADDR \

Advertise IP Address and Port to the Network

This tells the LND node to advertise itself to the network using the given IP address and port number ($IP_ADDR is the IP address of the node). This is useful if the node is behind a NAT or firewall and needs to be reachable from outside the network.

--externalip=$IP_ADDR:10009 \

IP Address and Port for Incoming RPC Connections

This sets the IP address and port number the LND node will listen to for incoming RPC connections. The 0.0.0.0 IP address means that the node will listen on all available network interfaces and $IP_ADDR:10009 specifies the port number to listen on.

--rpclisten=0.0.0.0:10009

📚Obsessed? More Resources

Lightning Network Original Whitepaper

https://lightning.network/lightning-network-paper.pdf

Lightning Node Setup Guide (with Docker)

History of the Lightning Network Infographic

https://i.redd.it/d4ulzl8s5oq21.png

Doug von Kohorn's Run You Own Lightning Node

Bitcoin Magazine: Understanding the Lightning Network — Building a Bi-Directional Payment Channel

LNBook — Mastering Lightning Network

Coindesk Lightning Network Research — 2021.09

https://downloads.coindesk.com/research/Lightning+Network+-+CoinDesk+Research+-+2021.09.pdf

--

--

Mabel Oza
Coinmonks

Making the financial world more secure, accessible, and transparent.