# How Lightning Works ⚡️ --- ## About this presentation - Based on Chapter 3 of [lnbook](https://github.com/lnbook/lnbook) - Prepared for [TAB](https://twitter.com/TAB_ATL) and [Bitcoin Design](https://bitcoin.design) - For review, please see [bitcoinbook](https://github.com/bitcoinbook/bitcoinbook) --- ## Table of Contents 1. What is the Lightning Network 2. Comparisons with Bitcoin 3. Payment Channels 4. Invoices 5. Payments
## What is the Lightning Network? ⚡️ > The Lightning Network (LN) is a peer-to-peer network of payment channels implemented as smart contracts on the Bitcoin blockchain as well as a communication protocol that defines how participants set up and execute these smart contracts.
## Comparisons with Bitcoin

Create a transaction

Send a payment

Send to an address

Pay an invoice

Selecting outputs (UTXOs)

Finding a path

"Change" outputs

No "change"

Mining fees

Routing fees

Fees depend on traffic

Fees are announced

Transactions are public

Payments are private

Wait for confirmation

Instant settlement

Send amounts only limited by UTXOs

Send amounts limited by channel capcity

Incentives for large value transfer

Incentives for small value transfer

Uses the blockchain as a ledger

Uses the blockchain as a court system

Asynchronous (Offline)

Synchronous (Online)

Satoshis

Milli-satoshis

## Payment channels --- ### What is a payment channel? > A payment channel is a financial relationship between [lightning] nodes, allocating funds from a multi-signature address, through a strictly defined cryptographic protocol.
### Payment Channel Basics > You and your channel partner **negotiate** a sequence of transactions that spend from [a] … multisignature address. Instead of transmitting and recording these transactions on the Bitcoin blockchain, you both hold on to them, unspent. --- ![Screenshot from the show Better Call Saul](img/better-call-saul.jpg "Better Call Saul") --- #### Multisig > Payment channels are built on top of 2-of-2 multisignature addresses. --- > In summary, a multi-signature address is where bitcoin is locked so that it requires multiple signatures to unlock and spend. In a 2-of-2 multisignature address, as used in the Lightning Network, there are two participating signers and both need to sign in order to spend the funds.
### Payment Channel Transactions Payment channels involve Bitcoin transactions that are signed by both nodes, but are not broadcast to be included in blocks by the miners. --- #### Funding Transaction > The two channel partners fund the payment channel by sending bitcoin to [a 2-of-2 multisignature address]. This transaction is called the **funding transaction**, and is recorded on the Bitcoin blockchain. --- ##### Note on Funding Transactions A funding *transaction* is **public**. *Payments* between channel partners are **private**. --- ##### Unleashing Funds > … [funds sent to the multisig address in the funding TX] are sometimes referred to as "**locked** in a Lightning channel"… --- ##### Unleashing Funds > … However, in practice, funds in a Lightning channel are not "locked" but rather "**unleashed**". Lightning channel funds are more liquid than funds on the Bitcoin blockchain as they can be spent faster, cheaper and more privately. --- #### Refund Transaction > In order to prevent [Bob from holding her funds hostage], Alice will need to create an additional transaction that spends from the [multisig] address, refunding her mBTC. Alice then has Bob sign the refund transaction before broadcasting her funding [TX] to the Bitcoin network. This way, Alice can get a refund even if Bob disappears or fails to cooperate. --- #### Commitment transactions > After this initial exchange, commitment transactions are created each time the channel balance changes. In other words, each time a payment is sent between Alice and Bob, new commitment transactions are created and signatures are exchanged. Each new commitment transaction encodes the latest balance between Alice and Bob. --- #### Punishment Transactions > So, in our example, Bob holds a commitment transaction that pays Alice immediately, but his own payment is delayed and revocable. Alice also holds a commitment transaction, but hers is the opposite: it pays Bob immediately but her own payment is delayed and revocable. --- #### Punishment Transactions > The two channel partners hold half of the revocation secret, so that neither one knows the whole secret. If they share their half, hen the other channel partner has the full secret and can use it to exercise the revocation condition. --- #### Punishment Transactions > When signing a new commitment transaction, each channel partner revokes the previous commitment by giving the other party their half of the revocation secret.
##### Preventing cheating with prior state Commitment transactions use a **smart contract** to help prevent a channel partner from publishing a prior state TX. The commitment TX that sends Bob his funds is timelocked to 2016 blocks, approximately 2 weeks. If he tries to publish this prior TX, Alice can use the revocation secret to snag the funds before the 2 weeks is up.
##### Smart Contracts In Bitcoin, a "locking script" is used to define what conditions are necessary to spend a UTXO (Unspent Transaction Output). --- ###### Basic Example This output would be spendable by anyone who could solve `X + 3 = 5`. ```text 3 OP_ADD 5 OP_EQUAL ``` *It should go without saying this is a terrible locking script.* --- ###### Typical UTXO This output would be spendable by anyone who could provide a digital signature for the given public key hash. ```text OP_DUP OP_HASH160 (Public Key Hash) OP_EQUALVERIFY OP_CHECKSIG ``` *Commonly referred to as **P2PKH** (Pay to Public Key Hash).* --- ###### Multisig UTXO This output would be spendable by anyone who could provide digital signatures from 2 of 3 of the given public keys. ```text 2 (Public Key A) (Public Key B) (Public Key C) 3 CHECKMULTISIG ``` *Commonly referred to as **2-of-3 multisig**.* --- ###### Complex Unlocking Script This output would be spendable by anyone who could satisfy a *[much more complicated condition]*. ```text 2 (Mohammed's Public Key) (Partner1 Public Key) (Partner2 Public Key) (Partner3 Public Key) (Attorney Public Key) 5 CHECKMULTISIG ``` ```text 54c557e07dde5bb6cb791c7a540e0a4796f5e97e ``` ```text HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e EQUAL ``` *Commonly referred to as **P2SH** (Pay to Script Hash).*
### Closing Chanels - Closing channels is optional. - You could keep a channel open indefinitely. --- #### Mutual close (the good way) - Fastest way to close a channel - Partner who initiated channel open pays on-chain TX fees --- #### Force close (the bad way) - One channel partner is offline or uncooperative - Partner initiating force close has slight disadvantage - Other partner's funds are spendable immediately - Closer's funds are timelocked. - This gives the other partner time to dispute the TX using revocation secret in event that the closing partner is cheating with a prior commitment TX. --- #### Force close (the bad way) - Force close TX will have higher on-chain fees. - The commitment TX has very generous fees included because on-chain TX fees will be unknown at time commitment TX is created. - This TX also includes additional outputs for pending routing attempts, so the TX will be larger. - Force close should be considered a **last resort**. --- #### Protocol breach (the ugly way) - This could be done after a cheating partner initiates a force close with a previous commitment TX. - Other partner can publish a punishment TX and collect cheater's share of the funds, without being encumbered by a timelock. --- ##### How to catch a protocol breach There are 3 ways to do it: 1. Run a LN node 24/7 2. Run a watchtower 3. Use a 3rd party watchtower
## Invoices LN payments begin with an **invoice**. *Example: Bob prompts Alice for payment by sending her an invoice.* --- *There is a way to send uninitiated payments with **keysend**, which will be covered in later chapters of the book.* --- > An invoice is a simple payment instruction containing information such as… - Payment hash (unique identifier) - Recipient - Amount - Optional text description --- ### Payment Hash The payment hash is the most important part of the invoice. To create a **payment hash** *(H)*, Alice first picks a **preimage** *(r)*, a random number that only she knows. *H* is then calculated generating a SHA256 hash of *r*. ```text H = SHA256(r) ``` --- Invoices are sent out of band, not over LN. Bech32 encoded string or QR code, sent over text, email, phone screen, etc. ![Screenshot of BlueWallet Invoice](img/invoice-example.png "Lightning Invoice")
## Delivering a payment --- LN payments are atomic. They succeed or fail -- no middle state. --- ### P2P Gossip Protocol > Channel announcements are communicated over a peer-to-peer gossip protocol. A [P2P] protocol is a communications protocol where each node connects to a random selection of other nodes in the network … each of the nodes that are directly connected … to your node are called your peers. --- When two nodes form a channel, the channel can be **announced** or **unannounced**. --- Gossop protocol only shares partial topology information. - To protect privacy - To scale the amount of payments - Information is outdated by the time it is received --- ### Pathfinding and routing ![Diagram of routing a LN payment](img/routing-payment.png) --- - Payments are forwarded along a **path** made of multiple channels. - **Pathfinding** is the process of finding a path from source to destination. - **Routing** is using the path to make a payment. --- ### Source-based Pathfinding > If we knew the exact channel balances of every channel, we could easily compute a payment path using any of the standard pathfinding algorithms taught in any computer science class. --- > With only partial information about the network topology, pathfinding is a real challenge and active research is still being conducted into this part of the Lightning Network. The fact that the pathfinding problem is not "fully solved" in the Lightning Network is a major point of criticism towards the technology. --- ### Onion routing > A payment package used for routing is called an "onion". --- #### Building an Onion > On its route from payment [payer] to [payee] the onion is passed from node to node along the path. The [payer] constructs the entire onion, from the center out. --- #### Building an Onion > First, the [payer] creates the payment information for the (final) recipient of the payment and encrypts it with a layer of encryption that only the recipient can decrypt. --- #### Building an Onion > Then, the [payer] wraps that layer with instructions for the node in the path immediately preceding the final recipient and encrypts with a layer that only that node can decrypt. --- ### P2P encryption The LN can be thought of as 2 networks: - A network of nodes connected via gossip protocol - A network of partners with payment channels --- #### Lightning messages > All communication between peers is sent via messages called Lightning messages. These messages are all encrypted, using a cryptographic communications framework called the Noise Protocol Framework.