# Lightning Loop Swap Case Study
## Metadata
**Status**:: #x
**Zettel**:: #zettel/literature
**Created**:: [[2025-11-17]]
## Overview
This is a case study on Lightning Loop, a submarine swap implementation.
Lightning Loop is a non-custodial service for moving funds between Bitcoin's Lightning Network (off-chain) and the Bitcoin blockchain (on-chain). All swaps use Hash Time-Locked Contracts (HTLCs) to ensure atomic execution - either both parties succeed or both fail.
### Roles
- **Client**: Loop daemon (`loopd`) connected to user's `lnd` node (Open source, include loop cli and loopd: [loop](https://github.com/lightninglabs/loop))
- **Server**: Loop server operated by Lightning Labs (Close source)
## Standard Loop Out (Off-chain → On-chain)
Move funds from Lightning channels to an on-chain address.
### Protocol Flow
1. **Client** generates swap preimage `s` and computes hash `H(s)`
2. **Client** requests quote from **Server** with desired amount and `H(s)`
3. **Server** returns:
- Server's public key `pk_server`
- Prepayment invoice (small fee, unrestricted)
- Swap invoice (Lightning) with payment hash `H(s)`
- CLTV expiry height for HTLC
4. **Client** pays prepayment invoice (small fee to server)
5. **Client** pays swap invoice (off-chain Lightning, locked to `H(s)`)
6. **Server** creates on-chain P2WSH HTLC:
- **Success path**: Unlocked by `s` + signature from `pk_client`
- **Timeout path**: Unlocked by `pk_server` signature after CLTV expiry
7. **Server** publishes HTLC transaction on-chain
8. **Client** sweeps on-chain HTLC using preimage `s` (reveals it on-chain)
9. **Server** sees preimage on-chain, settles swap invoice using `s`
### Security Properties
- **Client safety**: Only pays after receiving server's commitment (invoices), knowing swap can proceed
- **Server safety**: Receives off-chain payment BEFORE publishing on-chain HTLC, preventing client theft. Can reclaim on-chain funds after timeout if client doesn't sweep
- **Atomicity**: Preimage `s` links both payments - server gets paid iff client gets coins
- **Critical**: Client MUST pay off-chain (steps 4-5) BEFORE server publishes on-chain HTLC (step 7), otherwise client could claim on-chain funds without paying
### Visual Flow
```mermaid
sequenceDiagram
participant Client
participant Server
Note over Client: 1. Generate preimage s, compute H(s)
Client->>Server: 2. Request quote (amount, H(s))
Server->>Client: 3. Prepayment + Swap invoices<br/>(pk_server, CLTV, H(s))
Client->>Server: 4. Pay prepayment invoice
Client->>Server: 5. Pay swap invoice (locked to H(s))
Note over Client,Server: ⚠️ CRITICAL: Client pays off-chain FIRST
Server->>Client: 6/7. Create & publish on-chain HTLC<br/>(unlock: s + sig, timeout: server)
Client->>Server: 8. Sweep on-chain HTLC (reveal s)
Server->>Client: 9. Server sees s on-chain,<br/>settles swap invoice
```
**⚠️ CRITICAL SECURITY**: Client pays off-chain (steps 4-5) BEFORE server publishes on-chain HTLC (step 7). If reversed, client could sweep on-chain HTLC without paying off-chain, stealing funds.
## Standard Loop In (On-chain → Off-chain)
Move on-chain funds into Lightning channels to increase inbound liquidity.
### Protocol Flow
1. **Client** generates swap preimage `s` and computes hash `H(s)`
2. **Client** requests swap from **Server** with amount and `H(s)`
3. **Server** returns:
- Server's public key `pk_server`
- On-chain address for HTLC
- CLTV expiry height
4. **Client** creates on-chain P2WSH HTLC:
- **Success path**: Unlocked by `s` + signature from `pk_server`
- **Timeout path**: Unlocked by `pk_client` signature after CLTV expiry
5. **Client** publishes HTLC transaction on-chain
6. **Server** waits for confirmations, then sends Lightning payment to client with hash `H(s)`
7. **Client** settles Lightning payment by revealing preimage `s`
8. **Server** learns `s`, cooperatively sweeps HTLC with client (or uses preimage alone)
### Security Properties
- **Server safety**: Sends Lightning payment only after HTLC confirmed on-chain
- **Client safety**: Can reclaim on-chain funds after timeout if server doesn't pay
- **Atomicity**: Client reveals preimage to claim Lightning payment, allowing server to claim HTLC
### Visual Flow
```mermaid
sequenceDiagram
participant Client
participant Server
Note over Client: 1. Generate preimage s, compute H(s)
Client->>Server: 2. Request swap (amount, H(s))
Server->>Client: 3. HTLC address + pk_server + CLTV
Client->>Server: 4/5. Create & publish HTLC<br/>(unlock: s + pk_server, timeout: client)
Note over Server: 6.1 Wait for confirmations
Server->>Client: 6.2 Send Lightning payment (H(s))
Client->>Server: 7. Settle payment (reveal s)
Server->>Client: 8. Sweep on-chain HTLC (using s)
```
### Reference
- [Understanding Submarine Swaps](https://docs.lightning.engineering/the-lightning-network/multihop-payments/understanding-submarine-swaps)
## Autoloop (Automated Liquidity Management)
Autoloop automatically manages channel liquidity by monitoring balances and dispatching swaps based on user-defined rules.
### Monitoring Targets
- **Local balance**: Outbound capacity (ability to send payments)
- **Remote balance**: Inbound capacity (ability to receive payments)
- **Scope**: Per-channel, per-peer, or aggregate across all channels
### Rule Types
1. **Threshold Rules**
- Trigger when balance crosses min/max thresholds
- Can target specific channels or peers
2. **Easy Autoloop**
- Simple percentage-based target (e.g., maintain 50/50 balance)
- Automatically calculates swap amounts
### Restrictions
- **Budget limits**: Maximum fees per time period
- **Fee constraints**: Maximum acceptable swap fees
- **Swap limits**: Minimum/maximum swap amounts
- **Channel selection**: Include/exclude specific channels
### Example Rules
```yaml
# If total local balance > 100,000 sats, loop out excess
- rule: "loop_out"
threshold: 100000
type: "threshold"
# If peer's remote balance < 5,000 sats, loop out to create inbound
- rule: "loop_out"
peer: "peer_pubkey"
min_threshold: 5000
amount: 10000
# Maintain 60% local / 40% remote across all channels
- rule: "easy_autoloop"
target_balance: 60
```
### Swap Selection Logic
The liquidity manager evaluates:
1. Channel balances against rules
2. Available fee budget
3. Current on-chain and routing fees
4. Existing pending swaps
Then automatically dispatches Loop In or Loop Out swaps to meet targets.
### Reference
- [Autoloop Documentation](https://docs.lightning.engineering/lightning-network-tools/loop/autoloop)
## Instant Loop Out (Fast Off-chain → On-chain)
**Problem**: Standard Loop Out requires waiting for on-chain HTLC confirmation before paying the invoice, which can take 10-60 minutes.
**Solution**: Use pre-funded **Reservations** (2-of-2 MuSig2 UTXOs) that enable instant swaps with a cooperative path and HTLC fallback.
### Economic Model: Why Centralized Service Only
**The Capital Lock Problem:**
Instant Loop Out fundamentally relies on **pre-funded reservations** where the server must lock capital on-chain before knowing if or when a swap will occur. This creates an economic asymmetry that only makes sense in a centralized client-server model:
**Server's Capital Requirements:**
- Must maintain a pool of on-chain UTXOs reserved for potential instant swaps
- Each reservation ties up capital for weeks (typical expiry: 1008 blocks ≈ 1 week)
- Capital is locked in 2-of-2 multisig, completely unusable for other purposes
- Server needs significant liquidity buffer to serve multiple concurrent clients
- Dead capital: funds earn no yield while waiting in reservations
**Why it Works for Service Providers (Loop Server):**
- **Fee Revenue**: Server charges premium fees for instant service, amortizing capital costs across many clients
- **Demand Forecasting**: Service provider can predict demand patterns and optimize reservation pool size
- **Economies of Scale**: One server manages reservations for hundreds/thousands of clients
- **Business Model**: Recurring revenue from swap fees justifies locked capital opportunity cost
- **Risk Pooling**: Aggregate demand from many clients smooths out capital utilization
**Why it Fails for Peer-to-Peer:**
- **No Fee Incentive**: In P2P scenarios, peers typically want fair/minimal fees, not premium pricing
- **Unpredictable Demand**: Alice can't predict when Bob will need a swap (could be never)
- **Coordination Overhead**: Finding a peer with available reservations of the right size is difficult
- **No Amortization**: Each peer pair requires dedicated reservations, no economies of scale
- **Trust Issues**: P2P users unlikely to lock capital for strangers without compensation
- **Liquidity Fragmentation**: Capital gets trapped in many small, unusable chunks
**Alternative for P2P**: Standard Loop Out (submarine swap without reservations)
- No pre-funding required
- On-chain HTLC created only when swap is needed
- Both parties lock funds simultaneously for the swap duration only
- Slower (10-60 min confirmation wait) but capital-efficient
- Fair fee structure without premium for instant service
**Conclusion**: The instant swap optimization is specifically designed for the **Lightning Labs Loop service business model** where a centralized operator can justify capital lock costs through volume, premium pricing, and professional liquidity management. P2P implementations should use standard submarine swaps to avoid the capital inefficiency trap.
### Reservation UTXOs
Reservations are **server-initiated**, pre-funded on-chain UTXOs:
**Structure**: Taproot P2TR output with two spending paths:
1. **Keyspend (Cooperative)**: MuSig2(client_key, server_key)
- Requires both signatures
- Used for instant swaps and cooperative spends
- 64-byte witness (most efficient)
2. **Scriptspend (Expiry timeout)**:
```
<server_key> OP_CHECKSIGVERIFY <expiry> OP_CHECKLOCKTIMEVERIFY
```
- Server can unilaterally reclaim after expiry
- Prevents client from locking funds indefinitely
- 140-byte witness
**Lifecycle**:
1. Server sends reservation request to client (ID, amount, expiry, server_key)
2. Client derives key and sends client_key to server
3. Server funds the 2-of-2 MuSig2 Taproot UTXO on-chain
4. Client monitors for confirmation
5. Reservation becomes **active** and can be used for instant swaps
6. When a Reservation is spent, the change UTXO can be a new Reservation UTXO for the next swap.
### Protocol Flow
**Phase 1: Setup & Payment**
- 1\. Client requests instant out with H(s) and reservation IDs
- 2\. Server returns Lightning invoice with hash H(s)
- 3\. Client locks selected reservations
- 4\. Client pays Lightning invoice (reveals they have preimage)
- 5\. Both parties build and sign HTLC transaction as fallback:
- Input: Reservation UTXO (MuSig2)
- Output: P2WSH HTLC (server can claim with preimage, client can timeout)
- 6\. HTLC transaction is fully signed but NOT published
**Phase 2: Cooperative Execution (Happy Path - 1 TX)**
- 7\. Client pushes preimage `s` to server
- 8\. Server returns MuSig2 nonces for "sweepless sweep"
- 9\. Both parties create and sign sweepless sweep transaction:
- Input: Reservation UTXO (MuSig2 keyspend)
- Output: Directly to client's destination address
- 10\. Client publishes sweepless sweep
✅ **Complete in 1 on-chain transaction**
**Phase 3: HTLC Fallback (If Cooperative Fails - 2 TX)**
If any error occurs after preimage reveal:
- 11\. Client publishes pre-signed HTLC transaction
- 12\. Client sweeps HTLC using preimage `s`
✅ **Complete in 2 on-chain transactions**
### Visual Flow
**PRE-REQUISITE**: Active Reservation UTXOs (2-of-2 MuSig2 Taproot)
#### PHASE 1: Setup & Payment
```mermaid
sequenceDiagram
participant Client
participant Server
Client->>Server: 1. Request (reservation_ids, amount, H(s))
Server->>Client: 2. Invoice (H(s))
Note over Client: 3. Lock selected reservations
Client->>Server: 4. Pay invoice (Lightning off-chain)
Note over Client,Server: 5. Build HTLC tx (fallback safety)
Client<<->>Server: 6. Exchange MuSig2 nonces + signatures
Note over Client,Server: HTLC transaction signed<br/>but NOT published
```
#### PHASE 2: Cooperative Execution (Happy Path - 1 TX)
```mermaid
sequenceDiagram
participant Client
participant Server
Client->>Server: 7. Push preimage (s)
Server->>Client: 8. MuSig2 nonces for sweepless sweep
Client<<->>Server: 9. Both sign sweepless sweep TX
Server->>Client: 10. Publish sweepless sweep TX
```
#### PHASE 3: HTLC Fallback (If cooperative fails - 2 TX)
```mermaid
sequenceDiagram
participant Client
participant HTLC as HTLC TX<br/>Reservation→HTLC
participant Sweep as Sweep TX<br/>HTLC → Dest
Client->>HTLC: 11. Publish HTLC TX
Client->>Sweep: 12. Sweep HTLC with preimage s
```
### Key Innovations
**Speed**: No waiting for on-chain confirmations
- Reservations are pre-confirmed
- Payment happens instantly off-chain
- HTLC fallback is pre-signed before revealing preimage
**Efficiency**: Cooperative path uses 1 transaction vs 2
- Sweepless sweep: Reservation → Destination (direct)
- Saves on-chain fees and block space
**Non-custodial**: Client maintains full control
- HTLC fallback is signed before revealing preimage
- If server disappears after preimage reveal, client can still claim funds
- Server cannot steal funds (needs client signature)
**Server Safety**: Guaranteed payment or recovery
- Client pays invoice before server commits to cooperative sweep
- Server can reclaim reservation after expiry if client misbehaves
### Trust Model
**Client trusts**: Server won't double-spend reservation before swap completes
- Mitigated by: Pre-signed HTLC transaction provides fallback
- If server tries to cheat, client publishes HTLC and sweeps
**Server trusts**: Client has the preimage (verified by invoice payment)
- After invoice is paid, server knows client can complete the swap
**Neither party can steal**:
- Before preimage reveal: HTLC transaction is signed as fallback
- After preimage reveal: Both can claim their respective outputs
### Comparison with Standard Loop Out
| Aspect | Standard Loop Out | Instant Loop Out |
|--------|------------------|------------------|
| Setup time | None | Requires active reservations |
| Confirmation wait | Yes (10-60 min) | No (instant) |
| Transaction count | 2 (HTLC + sweep) | 1 (sweepless) or 2 (fallback) |
| On-chain fees | Higher | Lower (cooperative path) |
| Complexity | Simple | Higher (MuSig2, FSM) |
### Reference
- [Loop MuSig2 Integration](https://lightning.engineering/posts/2025-02-13-loop-musig2/)